qid
int64
1
74.7M
question
stringlengths
17
39.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
41.1k
response_k
stringlengths
2
47.9k
57,650,739
I don't know how to make the user leave the voice channel. I'm trying to make a verify thing, I have it all setup except for the leave voice channel part. ``` bot.on('voiceStateUpdate', (oldMember, newMember) => { let newUserChannel = newMember.voiceChannel let oldUserChannel = oldMember.voiceChannel var channel = bot.channels.get('614299678300831744'); if(oldUserChannel === undefined && newUserChannel !== 615306755420717143) { channel.send(newMember + ' has been verified.'); let role = newMember.guild.roles.find(role => role.name === "Verified"); newMember.addRole(role); let verifyEmbed = new Discord.RichEmbed() .setAuthor("Verificaiton") .setDescription("You have been verified") .setFooter(newMember.guild.name) .setColor("#98AFC7") newMember.sendMessage(verifyEmbed); newMember.disconnect(); } }); ``` I don't get any error, but it should disconnect me from the voice channel but can't?
2019/08/26
[ "https://Stackoverflow.com/questions/57650739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464450/" ]
Not sure if this is still relevant but since the update you can now do the following. ``` newMember.member.voice.disconnect(); ``` Refer to the [VoiceState](https://discord.js.org/#/docs/main/stable/class/VoiceState) class method `disconnect`.
You can make the bot create a new voice channel, move the user to the newly created voice channel, delete that channel and thus the user being disconnected ``` let randomnumber = Math.floor(Math.random() * 9000 + 1000) await receivedMessage.guild.createChannel(`voice-kick-${randomnumber}`, "voice") await vcUser.setVoiceChannel(receivedMessage.guild.channels.find(r => r.name === `voice-kick-${randomnumber}`)) receivedMessage.guild.channels.find(r => r.name === `voice-${randomnumber}`).delete() ``` Were adding the randomnumber command to make a random number in the VC so that there aren't any VC's that have the same name!
21,225,474
I have used Java for about six months but I am somewhat at a loss as to exactly how the `this` statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method? I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement. Question: The **this** keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object? class: ``` public class DDHThisTest { public int x = 0; public int y = 0; public DDHThisTest(int a, int b) { this.x = a; this.y = b; } public static void main(String[] args) { DDHThisTest i = new DDHThisTest(); this.i.x = 10; } } ``` Error: > > Cannot use this in a static context > > >
2014/01/20
[ "https://Stackoverflow.com/questions/21225474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487995/" ]
main method is a static method. keyword `this` is to be used in object/instance scope not in a static block. Simply replace `this.i.x = 10;` with `i.x = 10;` and you should be fine.
``` i.x = 10; ``` In static function, there is NO `this`.
21,225,474
I have used Java for about six months but I am somewhat at a loss as to exactly how the `this` statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method? I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement. Question: The **this** keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object? class: ``` public class DDHThisTest { public int x = 0; public int y = 0; public DDHThisTest(int a, int b) { this.x = a; this.y = b; } public static void main(String[] args) { DDHThisTest i = new DDHThisTest(); this.i.x = 10; } } ``` Error: > > Cannot use this in a static context > > >
2014/01/20
[ "https://Stackoverflow.com/questions/21225474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487995/" ]
When you are in a `static` block, you have no object scope. That means that there is not a particular instance of the class you are working with, so there is no reference to "this instance of the class".
The keyword "this" is reserved to be used as part of an instance. If you remove the "this.", you should be fine.
21,225,474
I have used Java for about six months but I am somewhat at a loss as to exactly how the `this` statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method? I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement. Question: The **this** keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object? class: ``` public class DDHThisTest { public int x = 0; public int y = 0; public DDHThisTest(int a, int b) { this.x = a; this.y = b; } public static void main(String[] args) { DDHThisTest i = new DDHThisTest(); this.i.x = 10; } } ``` Error: > > Cannot use this in a static context > > >
2014/01/20
[ "https://Stackoverflow.com/questions/21225474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487995/" ]
Main is a static method and it is called before the object of DDHThisTest class is made. So ypu are trying ro refer to an instance of a class which is yet to be instantiated. So you are getting the error. In other words you know that only static variables can be accessed from static methods. But 'this' is an instance variable so to say; because of which you can't access it from static method.
The keyword "this" is reserved to be used as part of an instance. If you remove the "this.", you should be fine.
21,225,474
I have used Java for about six months but I am somewhat at a loss as to exactly how the `this` statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method? I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement. Question: The **this** keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object? class: ``` public class DDHThisTest { public int x = 0; public int y = 0; public DDHThisTest(int a, int b) { this.x = a; this.y = b; } public static void main(String[] args) { DDHThisTest i = new DDHThisTest(); this.i.x = 10; } } ``` Error: > > Cannot use this in a static context > > >
2014/01/20
[ "https://Stackoverflow.com/questions/21225474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487995/" ]
main method is a static method. keyword `this` is to be used in object/instance scope not in a static block. Simply replace `this.i.x = 10;` with `i.x = 10;` and you should be fine.
You cannot use `this.i.x` since you cannot refer to instance variables inside a `static` method, in this case `main()`. To solve this just remove the `this` before `i.x`. ``` public static void main(String[] args) { DDHThisTest i = new DDHThisTest(1, 2); i.x = 10; } ``` **Note:** Don't forget to pass arguments to the constructor while creating an instance of `DDHThisTest`, because you have not declared a constructor without parameters.
21,225,474
I have used Java for about six months but I am somewhat at a loss as to exactly how the `this` statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method? I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement. Question: The **this** keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object? class: ``` public class DDHThisTest { public int x = 0; public int y = 0; public DDHThisTest(int a, int b) { this.x = a; this.y = b; } public static void main(String[] args) { DDHThisTest i = new DDHThisTest(); this.i.x = 10; } } ``` Error: > > Cannot use this in a static context > > >
2014/01/20
[ "https://Stackoverflow.com/questions/21225474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487995/" ]
When you are in a `static` block, you have no object scope. That means that there is not a particular instance of the class you are working with, so there is no reference to "this instance of the class".
``` i.x = 10; ``` In static function, there is NO `this`.
21,225,474
I have used Java for about six months but I am somewhat at a loss as to exactly how the `this` statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method? I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement. Question: The **this** keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object? class: ``` public class DDHThisTest { public int x = 0; public int y = 0; public DDHThisTest(int a, int b) { this.x = a; this.y = b; } public static void main(String[] args) { DDHThisTest i = new DDHThisTest(); this.i.x = 10; } } ``` Error: > > Cannot use this in a static context > > >
2014/01/20
[ "https://Stackoverflow.com/questions/21225474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487995/" ]
main method is a static method. keyword `this` is to be used in object/instance scope not in a static block. Simply replace `this.i.x = 10;` with `i.x = 10;` and you should be fine.
The keyword "this" is reserved to be used as part of an instance. If you remove the "this.", you should be fine.
21,225,474
I have used Java for about six months but I am somewhat at a loss as to exactly how the `this` statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method? I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement. Question: The **this** keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object? class: ``` public class DDHThisTest { public int x = 0; public int y = 0; public DDHThisTest(int a, int b) { this.x = a; this.y = b; } public static void main(String[] args) { DDHThisTest i = new DDHThisTest(); this.i.x = 10; } } ``` Error: > > Cannot use this in a static context > > >
2014/01/20
[ "https://Stackoverflow.com/questions/21225474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487995/" ]
Main is a static method and it is called before the object of DDHThisTest class is made. So ypu are trying ro refer to an instance of a class which is yet to be instantiated. So you are getting the error. In other words you know that only static variables can be accessed from static methods. But 'this' is an instance variable so to say; because of which you can't access it from static method.
``` i.x = 10; ``` In static function, there is NO `this`.
21,225,474
I have used Java for about six months but I am somewhat at a loss as to exactly how the `this` statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method? I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement. Question: The **this** keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object? class: ``` public class DDHThisTest { public int x = 0; public int y = 0; public DDHThisTest(int a, int b) { this.x = a; this.y = b; } public static void main(String[] args) { DDHThisTest i = new DDHThisTest(); this.i.x = 10; } } ``` Error: > > Cannot use this in a static context > > >
2014/01/20
[ "https://Stackoverflow.com/questions/21225474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487995/" ]
You cannot use `this.i.x` since you cannot refer to instance variables inside a `static` method, in this case `main()`. To solve this just remove the `this` before `i.x`. ``` public static void main(String[] args) { DDHThisTest i = new DDHThisTest(1, 2); i.x = 10; } ``` **Note:** Don't forget to pass arguments to the constructor while creating an instance of `DDHThisTest`, because you have not declared a constructor without parameters.
``` i.x = 10; ``` In static function, there is NO `this`.
21,225,474
I have used Java for about six months but I am somewhat at a loss as to exactly how the `this` statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method? I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement. Question: The **this** keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object? class: ``` public class DDHThisTest { public int x = 0; public int y = 0; public DDHThisTest(int a, int b) { this.x = a; this.y = b; } public static void main(String[] args) { DDHThisTest i = new DDHThisTest(); this.i.x = 10; } } ``` Error: > > Cannot use this in a static context > > >
2014/01/20
[ "https://Stackoverflow.com/questions/21225474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487995/" ]
main method is a static method. keyword `this` is to be used in object/instance scope not in a static block. Simply replace `this.i.x = 10;` with `i.x = 10;` and you should be fine.
Main is a static method and it is called before the object of DDHThisTest class is made. So ypu are trying ro refer to an instance of a class which is yet to be instantiated. So you are getting the error. In other words you know that only static variables can be accessed from static methods. But 'this' is an instance variable so to say; because of which you can't access it from static method.
21,225,474
I have used Java for about six months but I am somewhat at a loss as to exactly how the `this` statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method? I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement. Question: The **this** keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object? class: ``` public class DDHThisTest { public int x = 0; public int y = 0; public DDHThisTest(int a, int b) { this.x = a; this.y = b; } public static void main(String[] args) { DDHThisTest i = new DDHThisTest(); this.i.x = 10; } } ``` Error: > > Cannot use this in a static context > > >
2014/01/20
[ "https://Stackoverflow.com/questions/21225474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487995/" ]
You cannot use `this.i.x` since you cannot refer to instance variables inside a `static` method, in this case `main()`. To solve this just remove the `this` before `i.x`. ``` public static void main(String[] args) { DDHThisTest i = new DDHThisTest(1, 2); i.x = 10; } ``` **Note:** Don't forget to pass arguments to the constructor while creating an instance of `DDHThisTest`, because you have not declared a constructor without parameters.
The keyword "this" is reserved to be used as part of an instance. If you remove the "this.", you should be fine.
10,079,707
I am new to Curl and Cacerts world and facing a problem while connecting to a server. Basically, I need to test connectivity over https from one machine to another machine. I have a URL to which I need to connect from Machine A (a linux machine) I tried this on command prompt ``` cmd> curl https://[my domain or IP address] ``` and got the following: ``` curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` On going through some articles over internet I did this: ``` openssl s_client -connect <domain name or Ip address>:443 ``` and got some response including the server certificate (inside `-----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----`). What should I do next from here. I think, I will have to just copy paste the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and save it in a file. But, What type of file it should be? `.pem`, `.crt` ?.. What should I be do after that? I tried this - copied the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and saved it in a `.crt` file - named it as `my-ca.crt` (also tried the same thing by naming it as `my-ca.pem` file) and then did this: ``` cmd>curl --cacert my-ca.crt https://[my domain or IP address] ``` But got the same error.
2012/04/09
[ "https://Stackoverflow.com/questions/10079707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270392/" ]
I had the same problem - I was fetching a page from my own site, which was served over HTTPS, but curl was giving the same "SSL certificate problem" message. I worked around it by adding a `-k` flag to the call to allow insecure connections. ``` curl -k https://whatever.com/script.php ``` Edit: I discovered the root of the problem. I was using an SSL certificate (from StartSSL, but I don't think that matters much) and hadn't set up the intermediate certificate properly. If you're having the same problem as user1270392 above, it's probably a good idea to [test your SSL cert](http://www.sslshopper.com/ssl-checker.html) and fix any issues with it before resorting to the `curl -k` fix.
For me, I just wanted to test a website that had an automatic http->https redirect. I think I had some certs installed already, so this alone works for me on Ubuntu 16.04 running `curl 7.47.0 (x86_64-pc-linux-gnu) libcurl/7.47.0 GnuTLS/3.4.10 zlib/1.2.8 libidn/1.32 librtmp/2.3` `curl --proto-default https <target>`
10,079,707
I am new to Curl and Cacerts world and facing a problem while connecting to a server. Basically, I need to test connectivity over https from one machine to another machine. I have a URL to which I need to connect from Machine A (a linux machine) I tried this on command prompt ``` cmd> curl https://[my domain or IP address] ``` and got the following: ``` curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` On going through some articles over internet I did this: ``` openssl s_client -connect <domain name or Ip address>:443 ``` and got some response including the server certificate (inside `-----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----`). What should I do next from here. I think, I will have to just copy paste the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and save it in a file. But, What type of file it should be? `.pem`, `.crt` ?.. What should I be do after that? I tried this - copied the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and saved it in a `.crt` file - named it as `my-ca.crt` (also tried the same thing by naming it as `my-ca.pem` file) and then did this: ``` cmd>curl --cacert my-ca.crt https://[my domain or IP address] ``` But got the same error.
2012/04/09
[ "https://Stackoverflow.com/questions/10079707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270392/" ]
I had the same problem - I was fetching a page from my own site, which was served over HTTPS, but curl was giving the same "SSL certificate problem" message. I worked around it by adding a `-k` flag to the call to allow insecure connections. ``` curl -k https://whatever.com/script.php ``` Edit: I discovered the root of the problem. I was using an SSL certificate (from StartSSL, but I don't think that matters much) and hadn't set up the intermediate certificate properly. If you're having the same problem as user1270392 above, it's probably a good idea to [test your SSL cert](http://www.sslshopper.com/ssl-checker.html) and fix any issues with it before resorting to the `curl -k` fix.
use `--cacert` to specify a `.crt` file. `ca-root-nss.crt` for example.
10,079,707
I am new to Curl and Cacerts world and facing a problem while connecting to a server. Basically, I need to test connectivity over https from one machine to another machine. I have a URL to which I need to connect from Machine A (a linux machine) I tried this on command prompt ``` cmd> curl https://[my domain or IP address] ``` and got the following: ``` curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` On going through some articles over internet I did this: ``` openssl s_client -connect <domain name or Ip address>:443 ``` and got some response including the server certificate (inside `-----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----`). What should I do next from here. I think, I will have to just copy paste the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and save it in a file. But, What type of file it should be? `.pem`, `.crt` ?.. What should I be do after that? I tried this - copied the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and saved it in a `.crt` file - named it as `my-ca.crt` (also tried the same thing by naming it as `my-ca.pem` file) and then did this: ``` cmd>curl --cacert my-ca.crt https://[my domain or IP address] ``` But got the same error.
2012/04/09
[ "https://Stackoverflow.com/questions/10079707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270392/" ]
use `--cacert` to specify a `.crt` file. `ca-root-nss.crt` for example.
With modern versions of curl, you can simply override which ip-address to connect to, using --resolve or --connect-to (curl newer than version 7.49). This works even with SSL/SNI. All details are in the man page. For example, to override DNS and connect to www.example.com with ssl using a particular ip address: (This will also override ipv6) ``` curl --resolve www.example.com:443:192.168.42.2 https://www.example.com/ ``` Another example, to connect to a particular backend server named backend1 on port 8080 ``` curl --connect-to www.example.com:80:backend1.example.com:8080 http://www.example.com/ ``` Remember to add the host header if the server needs that to answer correctly: ``` -H 'Host:www.example.com' ```
10,079,707
I am new to Curl and Cacerts world and facing a problem while connecting to a server. Basically, I need to test connectivity over https from one machine to another machine. I have a URL to which I need to connect from Machine A (a linux machine) I tried this on command prompt ``` cmd> curl https://[my domain or IP address] ``` and got the following: ``` curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` On going through some articles over internet I did this: ``` openssl s_client -connect <domain name or Ip address>:443 ``` and got some response including the server certificate (inside `-----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----`). What should I do next from here. I think, I will have to just copy paste the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and save it in a file. But, What type of file it should be? `.pem`, `.crt` ?.. What should I be do after that? I tried this - copied the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and saved it in a `.crt` file - named it as `my-ca.crt` (also tried the same thing by naming it as `my-ca.pem` file) and then did this: ``` cmd>curl --cacert my-ca.crt https://[my domain or IP address] ``` But got the same error.
2012/04/09
[ "https://Stackoverflow.com/questions/10079707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270392/" ]
[Here you could find the CA certs with instructions to download and convert Mozilla CA certs](http://curl.haxx.se/docs/caextract.html). Once you get `ca-bundle.crt` or `cacert.pem` you just use: ``` curl.exe --cacert cacert.pem https://www.google.com ``` or ``` curl.exe --cacert ca-bundle.crt https://www.google.com ```
**Converting a Java KeyStore (.jks) to a Privacy Enhanced Mail file (.pem)** Use keytool to convert the JKS into PKCS: ``` keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.pkcs -srcstoretype JKS -deststoretype PKCS12 ``` Now convert the PKCS into PEM by using openssl: ``` openssl pkcs12 -in keystore.pkcs -out certificate.pem ```
10,079,707
I am new to Curl and Cacerts world and facing a problem while connecting to a server. Basically, I need to test connectivity over https from one machine to another machine. I have a URL to which I need to connect from Machine A (a linux machine) I tried this on command prompt ``` cmd> curl https://[my domain or IP address] ``` and got the following: ``` curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` On going through some articles over internet I did this: ``` openssl s_client -connect <domain name or Ip address>:443 ``` and got some response including the server certificate (inside `-----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----`). What should I do next from here. I think, I will have to just copy paste the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and save it in a file. But, What type of file it should be? `.pem`, `.crt` ?.. What should I be do after that? I tried this - copied the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and saved it in a `.crt` file - named it as `my-ca.crt` (also tried the same thing by naming it as `my-ca.pem` file) and then did this: ``` cmd>curl --cacert my-ca.crt https://[my domain or IP address] ``` But got the same error.
2012/04/09
[ "https://Stackoverflow.com/questions/10079707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270392/" ]
[Here you could find the CA certs with instructions to download and convert Mozilla CA certs](http://curl.haxx.se/docs/caextract.html). Once you get `ca-bundle.crt` or `cacert.pem` you just use: ``` curl.exe --cacert cacert.pem https://www.google.com ``` or ``` curl.exe --cacert ca-bundle.crt https://www.google.com ```
having dignosed the problem I was able to use the existing system default CA file, on debian6 this is: ``` /etc/ssl/certs/ca-certificates.crt ``` as root this can be done like: ``` echo curl.cainfo=/etc/ssl/certs/ca-certificates.crt >> /etc/php5/mods-available/curl.ini ``` then re-start the web-server.
10,079,707
I am new to Curl and Cacerts world and facing a problem while connecting to a server. Basically, I need to test connectivity over https from one machine to another machine. I have a URL to which I need to connect from Machine A (a linux machine) I tried this on command prompt ``` cmd> curl https://[my domain or IP address] ``` and got the following: ``` curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` On going through some articles over internet I did this: ``` openssl s_client -connect <domain name or Ip address>:443 ``` and got some response including the server certificate (inside `-----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----`). What should I do next from here. I think, I will have to just copy paste the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and save it in a file. But, What type of file it should be? `.pem`, `.crt` ?.. What should I be do after that? I tried this - copied the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and saved it in a `.crt` file - named it as `my-ca.crt` (also tried the same thing by naming it as `my-ca.pem` file) and then did this: ``` cmd>curl --cacert my-ca.crt https://[my domain or IP address] ``` But got the same error.
2012/04/09
[ "https://Stackoverflow.com/questions/10079707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270392/" ]
Basic certificate info ---------------------- That's my everyday script: ``` curl --insecure -vvI https://www.example.com 2>&1 | awk 'BEGIN { cert=0 } /^\* SSL connection/ { cert=1 } /^\*/ { if (cert) print }' ``` **Output:** ``` * SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 * ALPN, server accepted to use h2 * Server certificate: * subject: C=US; ST=California; L=Los Angeles; O=Verizon Digital Media Services, Inc.; CN=www.example.org * start date: Dec 10 00:00:00 2021 GMT * expire date: Dec 9 23:59:59 2022 GMT * issuer: C=US; O=DigiCert Inc; CN=DigiCert TLS RSA SHA256 2020 CA1 * SSL certificate verify ok. * Using HTTP2, server supports multi-use * Connection state changed (HTTP/2 confirmed) * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0 * Using Stream ID: 1 (easy handle 0x5588e1f5ae30) * TLSv1.3 (IN), TLS handshake, Newsession Ticket (4): * TLSv1.3 (IN), TLS handshake, Newsession Ticket (4): * old SSL session ID is stale, removing * Connection state changed (MAX_CONCURRENT_STREAMS == 100)! * Connection #0 to host www.example.com left intact ``` Full certificate info --------------------- ``` openssl s_client -connect www.example.com:443 </dev/null 2>/dev/null | openssl x509 -inform pem -text ```
You need the certificates chain and not a single certificate. It is easy to get it using Firefox: 1. Open the url in Firefox. 2. Click on the security icon on the address box left to the url. 3. Click on `connection not secure`, `more information`. Under the `security` tab, select `view certificate`, scroll toward the end. Next to `download`, select the **PEM(chain)** to download the chain of certificates. Now you have the chain of certificates as a file that you can use in the curl request after the `--cacert` flag: `curl --cacert downloaded.pem -X POST https://the-url-to-access`
10,079,707
I am new to Curl and Cacerts world and facing a problem while connecting to a server. Basically, I need to test connectivity over https from one machine to another machine. I have a URL to which I need to connect from Machine A (a linux machine) I tried this on command prompt ``` cmd> curl https://[my domain or IP address] ``` and got the following: ``` curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` On going through some articles over internet I did this: ``` openssl s_client -connect <domain name or Ip address>:443 ``` and got some response including the server certificate (inside `-----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----`). What should I do next from here. I think, I will have to just copy paste the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and save it in a file. But, What type of file it should be? `.pem`, `.crt` ?.. What should I be do after that? I tried this - copied the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and saved it in a `.crt` file - named it as `my-ca.crt` (also tried the same thing by naming it as `my-ca.pem` file) and then did this: ``` cmd>curl --cacert my-ca.crt https://[my domain or IP address] ``` But got the same error.
2012/04/09
[ "https://Stackoverflow.com/questions/10079707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270392/" ]
[Here you could find the CA certs with instructions to download and convert Mozilla CA certs](http://curl.haxx.se/docs/caextract.html). Once you get `ca-bundle.crt` or `cacert.pem` you just use: ``` curl.exe --cacert cacert.pem https://www.google.com ``` or ``` curl.exe --cacert ca-bundle.crt https://www.google.com ```
With modern versions of curl, you can simply override which ip-address to connect to, using --resolve or --connect-to (curl newer than version 7.49). This works even with SSL/SNI. All details are in the man page. For example, to override DNS and connect to www.example.com with ssl using a particular ip address: (This will also override ipv6) ``` curl --resolve www.example.com:443:192.168.42.2 https://www.example.com/ ``` Another example, to connect to a particular backend server named backend1 on port 8080 ``` curl --connect-to www.example.com:80:backend1.example.com:8080 http://www.example.com/ ``` Remember to add the host header if the server needs that to answer correctly: ``` -H 'Host:www.example.com' ```
10,079,707
I am new to Curl and Cacerts world and facing a problem while connecting to a server. Basically, I need to test connectivity over https from one machine to another machine. I have a URL to which I need to connect from Machine A (a linux machine) I tried this on command prompt ``` cmd> curl https://[my domain or IP address] ``` and got the following: ``` curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` On going through some articles over internet I did this: ``` openssl s_client -connect <domain name or Ip address>:443 ``` and got some response including the server certificate (inside `-----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----`). What should I do next from here. I think, I will have to just copy paste the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and save it in a file. But, What type of file it should be? `.pem`, `.crt` ?.. What should I be do after that? I tried this - copied the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and saved it in a `.crt` file - named it as `my-ca.crt` (also tried the same thing by naming it as `my-ca.pem` file) and then did this: ``` cmd>curl --cacert my-ca.crt https://[my domain or IP address] ``` But got the same error.
2012/04/09
[ "https://Stackoverflow.com/questions/10079707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270392/" ]
Basic certificate info ---------------------- That's my everyday script: ``` curl --insecure -vvI https://www.example.com 2>&1 | awk 'BEGIN { cert=0 } /^\* SSL connection/ { cert=1 } /^\*/ { if (cert) print }' ``` **Output:** ``` * SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 * ALPN, server accepted to use h2 * Server certificate: * subject: C=US; ST=California; L=Los Angeles; O=Verizon Digital Media Services, Inc.; CN=www.example.org * start date: Dec 10 00:00:00 2021 GMT * expire date: Dec 9 23:59:59 2022 GMT * issuer: C=US; O=DigiCert Inc; CN=DigiCert TLS RSA SHA256 2020 CA1 * SSL certificate verify ok. * Using HTTP2, server supports multi-use * Connection state changed (HTTP/2 confirmed) * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0 * Using Stream ID: 1 (easy handle 0x5588e1f5ae30) * TLSv1.3 (IN), TLS handshake, Newsession Ticket (4): * TLSv1.3 (IN), TLS handshake, Newsession Ticket (4): * old SSL session ID is stale, removing * Connection state changed (MAX_CONCURRENT_STREAMS == 100)! * Connection #0 to host www.example.com left intact ``` Full certificate info --------------------- ``` openssl s_client -connect www.example.com:443 </dev/null 2>/dev/null | openssl x509 -inform pem -text ```
For me, I just wanted to test a website that had an automatic http->https redirect. I think I had some certs installed already, so this alone works for me on Ubuntu 16.04 running `curl 7.47.0 (x86_64-pc-linux-gnu) libcurl/7.47.0 GnuTLS/3.4.10 zlib/1.2.8 libidn/1.32 librtmp/2.3` `curl --proto-default https <target>`
10,079,707
I am new to Curl and Cacerts world and facing a problem while connecting to a server. Basically, I need to test connectivity over https from one machine to another machine. I have a URL to which I need to connect from Machine A (a linux machine) I tried this on command prompt ``` cmd> curl https://[my domain or IP address] ``` and got the following: ``` curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` On going through some articles over internet I did this: ``` openssl s_client -connect <domain name or Ip address>:443 ``` and got some response including the server certificate (inside `-----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----`). What should I do next from here. I think, I will have to just copy paste the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and save it in a file. But, What type of file it should be? `.pem`, `.crt` ?.. What should I be do after that? I tried this - copied the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and saved it in a `.crt` file - named it as `my-ca.crt` (also tried the same thing by naming it as `my-ca.pem` file) and then did this: ``` cmd>curl --cacert my-ca.crt https://[my domain or IP address] ``` But got the same error.
2012/04/09
[ "https://Stackoverflow.com/questions/10079707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270392/" ]
You need the certificates chain and not a single certificate. It is easy to get it using Firefox: 1. Open the url in Firefox. 2. Click on the security icon on the address box left to the url. 3. Click on `connection not secure`, `more information`. Under the `security` tab, select `view certificate`, scroll toward the end. Next to `download`, select the **PEM(chain)** to download the chain of certificates. Now you have the chain of certificates as a file that you can use in the curl request after the `--cacert` flag: `curl --cacert downloaded.pem -X POST https://the-url-to-access`
With modern versions of curl, you can simply override which ip-address to connect to, using --resolve or --connect-to (curl newer than version 7.49). This works even with SSL/SNI. All details are in the man page. For example, to override DNS and connect to www.example.com with ssl using a particular ip address: (This will also override ipv6) ``` curl --resolve www.example.com:443:192.168.42.2 https://www.example.com/ ``` Another example, to connect to a particular backend server named backend1 on port 8080 ``` curl --connect-to www.example.com:80:backend1.example.com:8080 http://www.example.com/ ``` Remember to add the host header if the server needs that to answer correctly: ``` -H 'Host:www.example.com' ```
10,079,707
I am new to Curl and Cacerts world and facing a problem while connecting to a server. Basically, I need to test connectivity over https from one machine to another machine. I have a URL to which I need to connect from Machine A (a linux machine) I tried this on command prompt ``` cmd> curl https://[my domain or IP address] ``` and got the following: ``` curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` On going through some articles over internet I did this: ``` openssl s_client -connect <domain name or Ip address>:443 ``` and got some response including the server certificate (inside `-----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----`). What should I do next from here. I think, I will have to just copy paste the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and save it in a file. But, What type of file it should be? `.pem`, `.crt` ?.. What should I be do after that? I tried this - copied the text inside `BEGIN CERTIFICATE & END CERTIFICATE` and saved it in a `.crt` file - named it as `my-ca.crt` (also tried the same thing by naming it as `my-ca.pem` file) and then did this: ``` cmd>curl --cacert my-ca.crt https://[my domain or IP address] ``` But got the same error.
2012/04/09
[ "https://Stackoverflow.com/questions/10079707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270392/" ]
You need to provide the entire certificate chain to curl, since curl no longer ships with any CA certs. Since the cacert option can only use one file, you need to concat the full chain info into 1 file Copy the certificate chain (from your browser, for example) into DER encoded binary x.509(.cer). Do this for each cert. Convert the certs into PEM, and concat them into 1 file. ``` openssl x509 -inform DES -in file1.cer -out file1.pem -text openssl x509 -inform DES -in file2.cer -out file2.pem -text openssl x509 -inform DES -in file3.cer -out file3.pem -text cat *.pem > certRepo curl --cacert certRepo -u user:passwd -X GET -H 'Content-Type: application/json' "https//somesecureserver.com/rest/field" ``` I wrote a blog on how to do this here: <http://javamemento.blogspot.no/2015/10/using-curl-with-ssl-cert-chain.html>
For me, I just wanted to test a website that had an automatic http->https redirect. I think I had some certs installed already, so this alone works for me on Ubuntu 16.04 running `curl 7.47.0 (x86_64-pc-linux-gnu) libcurl/7.47.0 GnuTLS/3.4.10 zlib/1.2.8 libidn/1.32 librtmp/2.3` `curl --proto-default https <target>`
17,505,054
I am trying to use Python 2.7 `mechanize` to log into `Mint.com` with the following code: ``` import mechanize br = mechanize.Browser() br.open("https://wwws.mint.com/login.event") ``` this works just fine on OSX, but it **hangs** on debian. The issue seems to be ssl-related; the traceback ends with ``` File "/usr/lib/python2.7/ssl.py", line 305, in do_handshake self._sslobj.do_handshake() ``` EDIT: the issue persists on Debian using `urllib2`. As suggested in the comments, it seems the issue is actually ssl related. Why would this be a problem on Debian and not OSX?
2013/07/06
[ "https://Stackoverflow.com/questions/17505054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1628796/" ]
Your routes have problem. Instead of fixing the problem directly which is easy, better to double check your code logic. You should not define user id as path param to create a new project. Instead, the project instance should be initiated by current\_user. To associate a new project with user, just do it in controller ``` @project = current_user.projects.new ``` In conclusion: 1. Change the controller code similar to above 2. Restore your routes to conventional resource. 3. Then, use your test as it is, though a bit more expectations should be appended.
Assuming `login_with_oauth` is a spec helper method that you wrote, you can have that return the user that it setup. Then you can do: ``` feature "User creates a project" do scenario "Logged in User creates a project" do user = login_with_oauth visit new_user_project_path(user) ``` If that doesn't work, and `login_with_oauth` is something you don't control (say it comes from some library), you can fetch the first user out of the database. This is assuming no other users are in the db, but there shouldn't be because your tests should be clean and autonomous. Then do: ``` feature "User creates a project" do scenario "Logged in User creates a project" do login_with_oauth user = User.first visit new_user_project_path(user) ```
49,893,993
I have been reading about Neural Networks in general and trying to understand the basic theory behind it. I am getting a bit confused and wondering if someone could help me out. The way I understand Neural Networks is as follows: Input layer + hidden layers + output layers, where each layer has nodes, or neurons. Each Neuron obtains input from all neurons in the previous layer and also send to each neuron in the next layer. Then it is said that the neuron calculates the sum of the weights and then utilises an activation function to either fire or not (or send a number between 0 and 1). What gets me confused is HOW it calculates the sum of the weights? [![Simple Neural Network with one hidden layer](https://i.stack.imgur.com/j397R.png)](https://i.stack.imgur.com/j397R.png) In the figure above I have created a simple neural network and called the input as Andrew Ng does in his lectures (Youtube). So, take neuron a1 in layer 1: This will get the value a1 and a2 from layer 0, and also the corresponding weights and biases, which will be gathered in the vectors b1 and w1 for layer 1. Is the sum then calculated from the following formula? z = w1\*x + b? Is this in general for all Neural Networks or is this just one single type of NN? Will z1 in layer 1 also be a vector? Is it the activation function which makes it a scalar? I understand that there are different activation functions which calculate the final scalar value which is sent to the next layer of neurons together with weights and biases. But I guess I am very confused about the weights and biases and where they come from/are calculated etc. I hope my explanation wasn't too confusing, because I am pretty confused.
2018/04/18
[ "https://Stackoverflow.com/questions/49893993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9489131/" ]
The operation z1 = w1\*x + b is just for fully connected layers. [Convolutional Neural Networks](https://en.wikipedia.org/wiki/Convolutional_neural_network), for instance, use different operations. I think there is a bit of confusion with the notation. The value of a1 in layer 1 is a scalar, and to get this you need to apply the activation function to another scalar, z1, which can be calculated z1 = w1\*x + b. Here, w1 is not a matrix, but a vector of the weights that go to the neuron a1. However, this is not the usual way to do the computations, as this does not take the advantage of vectorization. In general, you want to do z = W\*x + b, where W is the matrix of all the weights and z is a vector, and then apply the activation function element-wise, obtaining a vector of activations for that layer, a.
Look this playlist. You learn how to implement your on nn. [Shiffmann Coding Train Neurol Network](https://www.youtube.com/watch?v=XJ7HLz9VYz0&list=PLRqwX-V7Uu6aCibgK1PTWWu9by6XFdCfh), [Feedforward Algorithm Part 1](https://www.youtube.com/watch?v=qWK7yW8oS0I&index=12&list=PLRqwX-V7Uu6aCibgK1PTWWu9by6XFdCfh)
49,893,993
I have been reading about Neural Networks in general and trying to understand the basic theory behind it. I am getting a bit confused and wondering if someone could help me out. The way I understand Neural Networks is as follows: Input layer + hidden layers + output layers, where each layer has nodes, or neurons. Each Neuron obtains input from all neurons in the previous layer and also send to each neuron in the next layer. Then it is said that the neuron calculates the sum of the weights and then utilises an activation function to either fire or not (or send a number between 0 and 1). What gets me confused is HOW it calculates the sum of the weights? [![Simple Neural Network with one hidden layer](https://i.stack.imgur.com/j397R.png)](https://i.stack.imgur.com/j397R.png) In the figure above I have created a simple neural network and called the input as Andrew Ng does in his lectures (Youtube). So, take neuron a1 in layer 1: This will get the value a1 and a2 from layer 0, and also the corresponding weights and biases, which will be gathered in the vectors b1 and w1 for layer 1. Is the sum then calculated from the following formula? z = w1\*x + b? Is this in general for all Neural Networks or is this just one single type of NN? Will z1 in layer 1 also be a vector? Is it the activation function which makes it a scalar? I understand that there are different activation functions which calculate the final scalar value which is sent to the next layer of neurons together with weights and biases. But I guess I am very confused about the weights and biases and where they come from/are calculated etc. I hope my explanation wasn't too confusing, because I am pretty confused.
2018/04/18
[ "https://Stackoverflow.com/questions/49893993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9489131/" ]
You can think of the weights as the arrows that connect your neurons. For every neuron in a layer, you have a weight for every neuron in the next layer. That means you can use one matrix between two layers to store the weights. To calculate the values of the next layer neurons, you do this: For every node in the second layer, you calculate `z1[0] = w1*a1[0] + w2*a2[0] + w3*a3[0]`. This will be a scalar value. Now you can apply the sigmoid function that will squash the scalar (but it will still be a scalar). Instead of doing this for every single neuron, we can use a vectorized implementation and calculate all values for a whole layer at once: ``` z[1] = a[0] * layer1_weights a[1] = sigmoid(z[1]) ```
Look this playlist. You learn how to implement your on nn. [Shiffmann Coding Train Neurol Network](https://www.youtube.com/watch?v=XJ7HLz9VYz0&list=PLRqwX-V7Uu6aCibgK1PTWWu9by6XFdCfh), [Feedforward Algorithm Part 1](https://www.youtube.com/watch?v=qWK7yW8oS0I&index=12&list=PLRqwX-V7Uu6aCibgK1PTWWu9by6XFdCfh)
49,893,993
I have been reading about Neural Networks in general and trying to understand the basic theory behind it. I am getting a bit confused and wondering if someone could help me out. The way I understand Neural Networks is as follows: Input layer + hidden layers + output layers, where each layer has nodes, or neurons. Each Neuron obtains input from all neurons in the previous layer and also send to each neuron in the next layer. Then it is said that the neuron calculates the sum of the weights and then utilises an activation function to either fire or not (or send a number between 0 and 1). What gets me confused is HOW it calculates the sum of the weights? [![Simple Neural Network with one hidden layer](https://i.stack.imgur.com/j397R.png)](https://i.stack.imgur.com/j397R.png) In the figure above I have created a simple neural network and called the input as Andrew Ng does in his lectures (Youtube). So, take neuron a1 in layer 1: This will get the value a1 and a2 from layer 0, and also the corresponding weights and biases, which will be gathered in the vectors b1 and w1 for layer 1. Is the sum then calculated from the following formula? z = w1\*x + b? Is this in general for all Neural Networks or is this just one single type of NN? Will z1 in layer 1 also be a vector? Is it the activation function which makes it a scalar? I understand that there are different activation functions which calculate the final scalar value which is sent to the next layer of neurons together with weights and biases. But I guess I am very confused about the weights and biases and where they come from/are calculated etc. I hope my explanation wasn't too confusing, because I am pretty confused.
2018/04/18
[ "https://Stackoverflow.com/questions/49893993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9489131/" ]
The operation z1 = w1\*x + b is just for fully connected layers. [Convolutional Neural Networks](https://en.wikipedia.org/wiki/Convolutional_neural_network), for instance, use different operations. I think there is a bit of confusion with the notation. The value of a1 in layer 1 is a scalar, and to get this you need to apply the activation function to another scalar, z1, which can be calculated z1 = w1\*x + b. Here, w1 is not a matrix, but a vector of the weights that go to the neuron a1. However, this is not the usual way to do the computations, as this does not take the advantage of vectorization. In general, you want to do z = W\*x + b, where W is the matrix of all the weights and z is a vector, and then apply the activation function element-wise, obtaining a vector of activations for that layer, a.
You can think of the weights as the arrows that connect your neurons. For every neuron in a layer, you have a weight for every neuron in the next layer. That means you can use one matrix between two layers to store the weights. To calculate the values of the next layer neurons, you do this: For every node in the second layer, you calculate `z1[0] = w1*a1[0] + w2*a2[0] + w3*a3[0]`. This will be a scalar value. Now you can apply the sigmoid function that will squash the scalar (but it will still be a scalar). Instead of doing this for every single neuron, we can use a vectorized implementation and calculate all values for a whole layer at once: ``` z[1] = a[0] * layer1_weights a[1] = sigmoid(z[1]) ```
49,893,993
I have been reading about Neural Networks in general and trying to understand the basic theory behind it. I am getting a bit confused and wondering if someone could help me out. The way I understand Neural Networks is as follows: Input layer + hidden layers + output layers, where each layer has nodes, or neurons. Each Neuron obtains input from all neurons in the previous layer and also send to each neuron in the next layer. Then it is said that the neuron calculates the sum of the weights and then utilises an activation function to either fire or not (or send a number between 0 and 1). What gets me confused is HOW it calculates the sum of the weights? [![Simple Neural Network with one hidden layer](https://i.stack.imgur.com/j397R.png)](https://i.stack.imgur.com/j397R.png) In the figure above I have created a simple neural network and called the input as Andrew Ng does in his lectures (Youtube). So, take neuron a1 in layer 1: This will get the value a1 and a2 from layer 0, and also the corresponding weights and biases, which will be gathered in the vectors b1 and w1 for layer 1. Is the sum then calculated from the following formula? z = w1\*x + b? Is this in general for all Neural Networks or is this just one single type of NN? Will z1 in layer 1 also be a vector? Is it the activation function which makes it a scalar? I understand that there are different activation functions which calculate the final scalar value which is sent to the next layer of neurons together with weights and biases. But I guess I am very confused about the weights and biases and where they come from/are calculated etc. I hope my explanation wasn't too confusing, because I am pretty confused.
2018/04/18
[ "https://Stackoverflow.com/questions/49893993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9489131/" ]
The operation z1 = w1\*x + b is just for fully connected layers. [Convolutional Neural Networks](https://en.wikipedia.org/wiki/Convolutional_neural_network), for instance, use different operations. I think there is a bit of confusion with the notation. The value of a1 in layer 1 is a scalar, and to get this you need to apply the activation function to another scalar, z1, which can be calculated z1 = w1\*x + b. Here, w1 is not a matrix, but a vector of the weights that go to the neuron a1. However, this is not the usual way to do the computations, as this does not take the advantage of vectorization. In general, you want to do z = W\*x + b, where W is the matrix of all the weights and z is a vector, and then apply the activation function element-wise, obtaining a vector of activations for that layer, a.
Let us consider all the numbers here as matrix. Your input a[0] is a 1x3 matrix i.e., a column vector. Now, as you had mentioned, without a activation function for a layer, the layer output would be a[1] = a[0].w[01] + b[1], where w[01] weight between 0th layer and 1st layer. Similarly b[1] is the bias added to the first layer. So, for matrix multiplication, your w[01] would be a 3x4 matrix and the bias will be a 1x4 matrix. If let's say you had a sigmoid activation to this later, in this case, sigmoid function will be applied to your a[1] to obtain the final output from this layer. It is always easier to understand the operations of NN using matrix! Hope that helps!
49,893,993
I have been reading about Neural Networks in general and trying to understand the basic theory behind it. I am getting a bit confused and wondering if someone could help me out. The way I understand Neural Networks is as follows: Input layer + hidden layers + output layers, where each layer has nodes, or neurons. Each Neuron obtains input from all neurons in the previous layer and also send to each neuron in the next layer. Then it is said that the neuron calculates the sum of the weights and then utilises an activation function to either fire or not (or send a number between 0 and 1). What gets me confused is HOW it calculates the sum of the weights? [![Simple Neural Network with one hidden layer](https://i.stack.imgur.com/j397R.png)](https://i.stack.imgur.com/j397R.png) In the figure above I have created a simple neural network and called the input as Andrew Ng does in his lectures (Youtube). So, take neuron a1 in layer 1: This will get the value a1 and a2 from layer 0, and also the corresponding weights and biases, which will be gathered in the vectors b1 and w1 for layer 1. Is the sum then calculated from the following formula? z = w1\*x + b? Is this in general for all Neural Networks or is this just one single type of NN? Will z1 in layer 1 also be a vector? Is it the activation function which makes it a scalar? I understand that there are different activation functions which calculate the final scalar value which is sent to the next layer of neurons together with weights and biases. But I guess I am very confused about the weights and biases and where they come from/are calculated etc. I hope my explanation wasn't too confusing, because I am pretty confused.
2018/04/18
[ "https://Stackoverflow.com/questions/49893993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9489131/" ]
You can think of the weights as the arrows that connect your neurons. For every neuron in a layer, you have a weight for every neuron in the next layer. That means you can use one matrix between two layers to store the weights. To calculate the values of the next layer neurons, you do this: For every node in the second layer, you calculate `z1[0] = w1*a1[0] + w2*a2[0] + w3*a3[0]`. This will be a scalar value. Now you can apply the sigmoid function that will squash the scalar (but it will still be a scalar). Instead of doing this for every single neuron, we can use a vectorized implementation and calculate all values for a whole layer at once: ``` z[1] = a[0] * layer1_weights a[1] = sigmoid(z[1]) ```
Let us consider all the numbers here as matrix. Your input a[0] is a 1x3 matrix i.e., a column vector. Now, as you had mentioned, without a activation function for a layer, the layer output would be a[1] = a[0].w[01] + b[1], where w[01] weight between 0th layer and 1st layer. Similarly b[1] is the bias added to the first layer. So, for matrix multiplication, your w[01] would be a 3x4 matrix and the bias will be a 1x4 matrix. If let's say you had a sigmoid activation to this later, in this case, sigmoid function will be applied to your a[1] to obtain the final output from this layer. It is always easier to understand the operations of NN using matrix! Hope that helps!
216,083
Can anyone explain how force is exerted on car seats during a crash? I am being told in car seat safety forums that $force=mass \times acceleration$. So if a $2000 \;\text{lb}$ vehicle bumps you at even $5 \;\text{mph}$, the force exerted on your car seat equals $10000 \;\text{lb}$, which is good reason to replace the seat. My husband (an engineer), says it's not that simple and that the mass being used in the above equation should not be the mass of the vehicle but that of the child and car seat combined. So at $5 \;\text{mph}$ the force exerted on the car seat would be something much less, on the order $500 \;\text{lb}$, depending on total weight of the seat and child. He also said something about the energy transfer into the brakes, the bumper, and car seats - therefore not all of that force is being applied to the car seat. What mass should be used to calculate the force exerted on a car seat during a collision, $m\_\text{vehicle}$ or $m\_\text{seat+child}$? Can anyone shed some light on this or explain better what either my husband or the car seat safety forums are trying to say?
2015/11/02
[ "https://physics.stackexchange.com/questions/216083", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/97309/" ]
**The short answer- The force exerted on a car seat depends on how much your car crushes to absorb the impact.** The more your car deforms, the lower the force. --- When you are thinking about this type of problem, remember that $5 \text{mph}$ is a speed (velocity), not an acceleration. Acceleration describes how quickly an object changes speed ($a = \frac {v\_{f}-v\_{i}}{t}$). As you correctly noted, $F = ma$, **however, forces are caused by accelerations, not speeds!** \*\*To calculate Force in [$\text{lbf}$]: Acceleration has units [$\frac {ft}{s^2}$], with velocity in [$\frac {ft}{s}$] and time in [$\text{s}$]; Mass has units [$\text{slug} = \frac {\text{lbm}}{\text{g}}$] where $g=32.2 \;[\frac {ft}{s^2}]$. Calculate Acceleration: ----------------------- > > $$a = \frac {0 \;\text{[ft/s]} - 7.33 \;\text{[ft/s]}}{t}$$ > > > This is where your question becomes a matter of guess work, because we dont know how long the crash takes- it depends on how much your car deforms during a crash. As a ballpark guess, lets assume that the crash takes $t = 0.25 \;\text{seconds}$. > > > $$\therefore a = \frac {0 \;\text{[ft/s]} - 7.33 \;\text{[ft/s]}}{\approx 0.25 \;[\text{s}]} \approx -29 \;[\frac {ft}{s^2}]$$ > > > Calculate Force: ---------------- > > The mass of the driver and the mass of the car seat are accelerated with the car body. Assuming the driver weighs $150 \;\text{[lbm]}$ and the car seat weighs $50 \;\text{[lbm]}$, their masses are $4.6 \;\text{[slug]}$ and $1.5 \;\text{[slug]}$. The force on the car seat is calculated by: > > > $$F\_{seat} = (m\_{driver}+m\_{seat})a \qquad \Rightarrow \qquad \therefore F\_{seat} \approx 182 \;\text{[lbf]}$$ > > > Similarly, to determine force exerted on the driver: > > > $$F\_{driver} = (m\_{driver})a \qquad \Rightarrow \qquad \therefore F\_{driver} \approx 137 \;\text{[lbf]}$$ > > > In reality, the seat cushion compresses, increasing the impact time (felt by the driver). This decreases the drivers acceleration and reduces the force felt by the driver. > > > While braking does exert force on the seat and driver, it is calculated separately because it occurs before the collision. For example, you might calculate the force as the car decelerates from $30 \;\text{[mph]}$ to $5 \;\text{[mph]}$ (in some time interval) before the collision. However, this deceleration is much less than the deceleration/force involved in the collision and can be safely ignored. After all, you dont need to replace a car seat after braking! The car seat is easily strong enough to handle these forces. However, this is a concern in high speed crashes, where forces are large enough to create stresses in the seat frame that exceed the yield limit, the seat should be replaced.
**I am not a physicist** The force applied to the seat will be the net (difference) of all the following: 1. Force absorbed by the car body. 2. Force absorbed by the brakes/friction. 3. Force dissipated through the frame (on to which the car seat is attached). 4. Force absorbed by the car seat itself. Finally, whatever may be left will be transferred to the occupant. The only way you can affect a 10,000 lbs of force onto an object is if you discount all the other forces in effect and exert a *much larger force* in terms of the momentum of the object. Keep in mind that vehicles are designed with a certain amount of safety and that there are many mechanisms in place (in terms of the structural design) absorb any force and dissipate it away from the occupants. These design mechanisms include the placements and size/shape of the seats. At 5 miles per hour - which is nearly idle speed any bump to a vehicle will result in at most a small dent to the part of the body hit by the vehicle; the force exerted would not be sufficient to **structurally compromise the car seat** such that it would need replacement. Source: Sadly, experience with car accidents first hand.
216,083
Can anyone explain how force is exerted on car seats during a crash? I am being told in car seat safety forums that $force=mass \times acceleration$. So if a $2000 \;\text{lb}$ vehicle bumps you at even $5 \;\text{mph}$, the force exerted on your car seat equals $10000 \;\text{lb}$, which is good reason to replace the seat. My husband (an engineer), says it's not that simple and that the mass being used in the above equation should not be the mass of the vehicle but that of the child and car seat combined. So at $5 \;\text{mph}$ the force exerted on the car seat would be something much less, on the order $500 \;\text{lb}$, depending on total weight of the seat and child. He also said something about the energy transfer into the brakes, the bumper, and car seats - therefore not all of that force is being applied to the car seat. What mass should be used to calculate the force exerted on a car seat during a collision, $m\_\text{vehicle}$ or $m\_\text{seat+child}$? Can anyone shed some light on this or explain better what either my husband or the car seat safety forums are trying to say?
2015/11/02
[ "https://physics.stackexchange.com/questions/216083", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/97309/" ]
**I am not a physicist** The force applied to the seat will be the net (difference) of all the following: 1. Force absorbed by the car body. 2. Force absorbed by the brakes/friction. 3. Force dissipated through the frame (on to which the car seat is attached). 4. Force absorbed by the car seat itself. Finally, whatever may be left will be transferred to the occupant. The only way you can affect a 10,000 lbs of force onto an object is if you discount all the other forces in effect and exert a *much larger force* in terms of the momentum of the object. Keep in mind that vehicles are designed with a certain amount of safety and that there are many mechanisms in place (in terms of the structural design) absorb any force and dissipate it away from the occupants. These design mechanisms include the placements and size/shape of the seats. At 5 miles per hour - which is nearly idle speed any bump to a vehicle will result in at most a small dent to the part of the body hit by the vehicle; the force exerted would not be sufficient to **structurally compromise the car seat** such that it would need replacement. Source: Sadly, experience with car accidents first hand.
Your husband is right. The mass to use in that equation is the mass of the car seat and passenger combined.
216,083
Can anyone explain how force is exerted on car seats during a crash? I am being told in car seat safety forums that $force=mass \times acceleration$. So if a $2000 \;\text{lb}$ vehicle bumps you at even $5 \;\text{mph}$, the force exerted on your car seat equals $10000 \;\text{lb}$, which is good reason to replace the seat. My husband (an engineer), says it's not that simple and that the mass being used in the above equation should not be the mass of the vehicle but that of the child and car seat combined. So at $5 \;\text{mph}$ the force exerted on the car seat would be something much less, on the order $500 \;\text{lb}$, depending on total weight of the seat and child. He also said something about the energy transfer into the brakes, the bumper, and car seats - therefore not all of that force is being applied to the car seat. What mass should be used to calculate the force exerted on a car seat during a collision, $m\_\text{vehicle}$ or $m\_\text{seat+child}$? Can anyone shed some light on this or explain better what either my husband or the car seat safety forums are trying to say?
2015/11/02
[ "https://physics.stackexchange.com/questions/216083", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/97309/" ]
> > Can anyone explain how force is exerted on car seats during a crash? > > > I am being told in car seat safety forums that force=mass×acceleration. So if a 2000lb vehicle bumps you at even 5mph, the force exerted on your car seat equals 10000lb, which is good reason to replace the seat. > > > The formula is correct. $F=ma$. This is the total force $F$ it takes to accelerate a mass $m$ with the acceleration $a$. Now, the point is - maybe surprisingly - **not the speed of the car**! The point is **not how fast you are going** (or how fast the bumping car is going). The point is how fast you are **decelerating**. In other words, **how fast you are speeding down**! If you drive the car strait into a stone wall, it is a lot more damaging for the child on the back seat than if you drive into a large soft vertical foam matress. Why? Because the foam matress makes the car (and you) slow down slowlier! It simply takes longer for the speed to go from 5mhp to 0mhp, which means that the deceleration (negative acceleration) $a$ is smaller and therefore the force $F$ is smaller as well. > > My husband (an engineer), says it's not that simple and that the mass being used in the above equation should not be the mass of the vehicle but that of the child and car seat combined. > > > Yes, because $F$ in the formula above is the total force needed to accelerate the mass $m$. And what you are interested in is the force on the child, so the child would be your $m$. The force on the car might be very different and much larger than the force on the child. I am not quite sure from the question, exactly what object you wish to look at, so I've assumed we are looking at the impact on the child. If you wish to look at the seat alone, we should define what the seat exactly is (or is a childs seat?) > > He also said something about the energy transfer into the brakes, the bumper, and car seats - therefore not all of that force is being applied to the car seat. > > > Yes, here comes a point of car evolution and improvements. This is the reason that we cannot just *calculate* the impact force on people in a car - it is way too complicated with way too many unknown factors - so crash tests are what is being used. The point is again that the foam wall is making the impact softer because is gives the car more time to slow down from the 5mhp to 0mhp. We want to avoid a sudden stop, which would cause a large deceleration. So, if we *do* hit a stone wall, we must instead imitate the foam somewhere else. For example in the structure of the car before the impact reaches the child on the backseat. In accidents you very often see extremely damaged and crumbled cars - it looks very violent even when the people inside weren't that injured. That is because many bigger cars are made so their frontend will crumble a lot. This is like a foam sponge that absorbs the energy because it slows the car down more slowly than if the car was totally rigid. This foam sponge effect is the case in many cases throughout the car chasis - everywhere where the car is not perfectly rigid, energy is absorbed for the car deformation giving the rest of the car and passengers more time to slow down. The airbag on the frontseats works like a pillow that your head can hit. Then, when the head flies forward, because the car is being stopped suddenly, it is slowly slowed down by this "pillow" and decelerated less just over a longer period of time. If the airbag wasn't there, the head might continue with the same speed until it hits the dashboard and *there* it would be stopped suddenly and experience a large deceleration. Or, the neck would have to stop the head and maybe the bones and the body is not strong enough the cause this deceleration of the head, so something will break.
**I am not a physicist** The force applied to the seat will be the net (difference) of all the following: 1. Force absorbed by the car body. 2. Force absorbed by the brakes/friction. 3. Force dissipated through the frame (on to which the car seat is attached). 4. Force absorbed by the car seat itself. Finally, whatever may be left will be transferred to the occupant. The only way you can affect a 10,000 lbs of force onto an object is if you discount all the other forces in effect and exert a *much larger force* in terms of the momentum of the object. Keep in mind that vehicles are designed with a certain amount of safety and that there are many mechanisms in place (in terms of the structural design) absorb any force and dissipate it away from the occupants. These design mechanisms include the placements and size/shape of the seats. At 5 miles per hour - which is nearly idle speed any bump to a vehicle will result in at most a small dent to the part of the body hit by the vehicle; the force exerted would not be sufficient to **structurally compromise the car seat** such that it would need replacement. Source: Sadly, experience with car accidents first hand.
216,083
Can anyone explain how force is exerted on car seats during a crash? I am being told in car seat safety forums that $force=mass \times acceleration$. So if a $2000 \;\text{lb}$ vehicle bumps you at even $5 \;\text{mph}$, the force exerted on your car seat equals $10000 \;\text{lb}$, which is good reason to replace the seat. My husband (an engineer), says it's not that simple and that the mass being used in the above equation should not be the mass of the vehicle but that of the child and car seat combined. So at $5 \;\text{mph}$ the force exerted on the car seat would be something much less, on the order $500 \;\text{lb}$, depending on total weight of the seat and child. He also said something about the energy transfer into the brakes, the bumper, and car seats - therefore not all of that force is being applied to the car seat. What mass should be used to calculate the force exerted on a car seat during a collision, $m\_\text{vehicle}$ or $m\_\text{seat+child}$? Can anyone shed some light on this or explain better what either my husband or the car seat safety forums are trying to say?
2015/11/02
[ "https://physics.stackexchange.com/questions/216083", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/97309/" ]
**The short answer- The force exerted on a car seat depends on how much your car crushes to absorb the impact.** The more your car deforms, the lower the force. --- When you are thinking about this type of problem, remember that $5 \text{mph}$ is a speed (velocity), not an acceleration. Acceleration describes how quickly an object changes speed ($a = \frac {v\_{f}-v\_{i}}{t}$). As you correctly noted, $F = ma$, **however, forces are caused by accelerations, not speeds!** \*\*To calculate Force in [$\text{lbf}$]: Acceleration has units [$\frac {ft}{s^2}$], with velocity in [$\frac {ft}{s}$] and time in [$\text{s}$]; Mass has units [$\text{slug} = \frac {\text{lbm}}{\text{g}}$] where $g=32.2 \;[\frac {ft}{s^2}]$. Calculate Acceleration: ----------------------- > > $$a = \frac {0 \;\text{[ft/s]} - 7.33 \;\text{[ft/s]}}{t}$$ > > > This is where your question becomes a matter of guess work, because we dont know how long the crash takes- it depends on how much your car deforms during a crash. As a ballpark guess, lets assume that the crash takes $t = 0.25 \;\text{seconds}$. > > > $$\therefore a = \frac {0 \;\text{[ft/s]} - 7.33 \;\text{[ft/s]}}{\approx 0.25 \;[\text{s}]} \approx -29 \;[\frac {ft}{s^2}]$$ > > > Calculate Force: ---------------- > > The mass of the driver and the mass of the car seat are accelerated with the car body. Assuming the driver weighs $150 \;\text{[lbm]}$ and the car seat weighs $50 \;\text{[lbm]}$, their masses are $4.6 \;\text{[slug]}$ and $1.5 \;\text{[slug]}$. The force on the car seat is calculated by: > > > $$F\_{seat} = (m\_{driver}+m\_{seat})a \qquad \Rightarrow \qquad \therefore F\_{seat} \approx 182 \;\text{[lbf]}$$ > > > Similarly, to determine force exerted on the driver: > > > $$F\_{driver} = (m\_{driver})a \qquad \Rightarrow \qquad \therefore F\_{driver} \approx 137 \;\text{[lbf]}$$ > > > In reality, the seat cushion compresses, increasing the impact time (felt by the driver). This decreases the drivers acceleration and reduces the force felt by the driver. > > > While braking does exert force on the seat and driver, it is calculated separately because it occurs before the collision. For example, you might calculate the force as the car decelerates from $30 \;\text{[mph]}$ to $5 \;\text{[mph]}$ (in some time interval) before the collision. However, this deceleration is much less than the deceleration/force involved in the collision and can be safely ignored. After all, you dont need to replace a car seat after braking! The car seat is easily strong enough to handle these forces. However, this is a concern in high speed crashes, where forces are large enough to create stresses in the seat frame that exceed the yield limit, the seat should be replaced.
Your husband is right. The mass to use in that equation is the mass of the car seat and passenger combined.
216,083
Can anyone explain how force is exerted on car seats during a crash? I am being told in car seat safety forums that $force=mass \times acceleration$. So if a $2000 \;\text{lb}$ vehicle bumps you at even $5 \;\text{mph}$, the force exerted on your car seat equals $10000 \;\text{lb}$, which is good reason to replace the seat. My husband (an engineer), says it's not that simple and that the mass being used in the above equation should not be the mass of the vehicle but that of the child and car seat combined. So at $5 \;\text{mph}$ the force exerted on the car seat would be something much less, on the order $500 \;\text{lb}$, depending on total weight of the seat and child. He also said something about the energy transfer into the brakes, the bumper, and car seats - therefore not all of that force is being applied to the car seat. What mass should be used to calculate the force exerted on a car seat during a collision, $m\_\text{vehicle}$ or $m\_\text{seat+child}$? Can anyone shed some light on this or explain better what either my husband or the car seat safety forums are trying to say?
2015/11/02
[ "https://physics.stackexchange.com/questions/216083", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/97309/" ]
> > Can anyone explain how force is exerted on car seats during a crash? > > > I am being told in car seat safety forums that force=mass×acceleration. So if a 2000lb vehicle bumps you at even 5mph, the force exerted on your car seat equals 10000lb, which is good reason to replace the seat. > > > The formula is correct. $F=ma$. This is the total force $F$ it takes to accelerate a mass $m$ with the acceleration $a$. Now, the point is - maybe surprisingly - **not the speed of the car**! The point is **not how fast you are going** (or how fast the bumping car is going). The point is how fast you are **decelerating**. In other words, **how fast you are speeding down**! If you drive the car strait into a stone wall, it is a lot more damaging for the child on the back seat than if you drive into a large soft vertical foam matress. Why? Because the foam matress makes the car (and you) slow down slowlier! It simply takes longer for the speed to go from 5mhp to 0mhp, which means that the deceleration (negative acceleration) $a$ is smaller and therefore the force $F$ is smaller as well. > > My husband (an engineer), says it's not that simple and that the mass being used in the above equation should not be the mass of the vehicle but that of the child and car seat combined. > > > Yes, because $F$ in the formula above is the total force needed to accelerate the mass $m$. And what you are interested in is the force on the child, so the child would be your $m$. The force on the car might be very different and much larger than the force on the child. I am not quite sure from the question, exactly what object you wish to look at, so I've assumed we are looking at the impact on the child. If you wish to look at the seat alone, we should define what the seat exactly is (or is a childs seat?) > > He also said something about the energy transfer into the brakes, the bumper, and car seats - therefore not all of that force is being applied to the car seat. > > > Yes, here comes a point of car evolution and improvements. This is the reason that we cannot just *calculate* the impact force on people in a car - it is way too complicated with way too many unknown factors - so crash tests are what is being used. The point is again that the foam wall is making the impact softer because is gives the car more time to slow down from the 5mhp to 0mhp. We want to avoid a sudden stop, which would cause a large deceleration. So, if we *do* hit a stone wall, we must instead imitate the foam somewhere else. For example in the structure of the car before the impact reaches the child on the backseat. In accidents you very often see extremely damaged and crumbled cars - it looks very violent even when the people inside weren't that injured. That is because many bigger cars are made so their frontend will crumble a lot. This is like a foam sponge that absorbs the energy because it slows the car down more slowly than if the car was totally rigid. This foam sponge effect is the case in many cases throughout the car chasis - everywhere where the car is not perfectly rigid, energy is absorbed for the car deformation giving the rest of the car and passengers more time to slow down. The airbag on the frontseats works like a pillow that your head can hit. Then, when the head flies forward, because the car is being stopped suddenly, it is slowly slowed down by this "pillow" and decelerated less just over a longer period of time. If the airbag wasn't there, the head might continue with the same speed until it hits the dashboard and *there* it would be stopped suddenly and experience a large deceleration. Or, the neck would have to stop the head and maybe the bones and the body is not strong enough the cause this deceleration of the head, so something will break.
Your husband is right. The mass to use in that equation is the mass of the car seat and passenger combined.
39,030,248
Deploy weblogic using jenkins without jenkins plugin. jenkins weblogic plugin use this command. So I try use it. ``` /bin/java -Xms256M -Xmx256M -cp /root/wls12210/wlserver/server/lib/weblogic.jar weblogic.Deployer -debug -stage -remote -verbose -upload -name testPage -source /root/.jenkins/workspace/WebLogic/target/testPage.war -targets AdminServer -adminurl t3://127.0.0.1:7001 -user {ID} -password {password} -deploy ``` But If I use this command not use plugin but only raw command, there is error. > > error: Cannot find basic class weblogic.Deployer or cannot load weblogic.Deployer. > > > above error evoke as korean language, so I translated to english. under error is jenkins error part. > > [WeblogicDeploymentPlugin] - ARTIFACT UNDEPLOYED SUCCESSFULLY. > [WeblogicDeploymentPlugin] - DEPLOYING ARTIFACT... $ > /bin/java -Xms256M -Xmx256M -cp > /root/wls12210/wlserver/server/lib/weblogic.jar weblogic.Deployer > -debug -stage -remote -verbose -upload -name testPage -source /root/.jenkins/workspace/WebLogic/target/testPage.war -targets > AdminServer -adminurl t3://127.0.0.1:7001 -user {id} -password > {passwd} -deploy [WeblogicDeploymentPlugin] - ARTIFACT DEPLOYED > SUCCESSFULLY. [INFO] > [INFO] DEPLOYMENT SUCCESS [INFO] > > > SSH: Connecting from host [localhost.localdomain] > > > SSH: Connecting with configuration [weblogic] ... > > > SSH: EXEC: STDOUT/STDERR from command[ > /bin/java -Xms256M -Xmx256M -cp /root/wls12210/wlserver/server/lib/weblogic.jar weblogic.Deployer > -debug -stage -remote -verbose -upload -name testPage -source /root/.jenkins/workspace/WebLogic/target/testPage.war -targets > AdminServer -adminurl t3://127.0.0.1:7001 -user {id} -password > {passwd} -deploy > > > error: Cannot find basic class weblogic.Deployer or cannot load weblogic.Deployer. > > > How can I solve this error?
2016/08/19
[ "https://Stackoverflow.com/questions/39030248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Just use recursion ``` function do_consecutive_action() { Promise.resolve() .then(() => do_X() ) .then(() => Delay(1000)) .then(() => do_Y()) .then(() => Delay(1000)) .then(() => do_consecutive_action()) // You will also want to include a catch handler if an error happens .catch((err) => { ... }); } ```
``` function cb(func) { try { func(); } catch (e) { do_consecutive_action(); } } function do_consecutive_action() { Promise.resolve() .then(() => cb(do_X)) .then(() => Delay(1000)) .then(() => cb(do_Y)) .then(() => Delay(1000)) .then(() => do_consecutive_action()) // You will also want to include a catch handler if an error happens .catch((err) => { ... }); ``` }
39,599,961
I have the latest PhpStorm (2016.2) and PHPUnit phar (5.5.4). For some reason when I run a PHPUnit test in my project in PhpStorm, it is adding on `--teamcity` to the run command, resulting in a failure: ``` Testing started at 12:52 PM ... Unit test suite invoked with a path to a non-unit test: --teamcity Process finished with exit code 1 ``` I have no idea where this `--teamcity` option is coming from, it happens no matter what test I run, and even when starting from a blank configuration. I also do NOT have the TeamCity plugin installed, I don't even use TeamCity. Here's what the full command appears as: ``` /usr/local/Cellar/php70/7.0.9/bin/php /Users/name/bin/phpunit-5.5.4.phar --configuration /path/to/config/my-phpunit.xml ClassNameTest /Users/name/PhpstormProjects/path/to/tests/unit/app/ClassNameTest.php --teamcity ``` (sensitive information swapped out) All I want to do is get rid of this `--teamcity` option, everything works if I run in a separate terminal window without that option. This only recently started happening, maybe after a PhpStorm update.
2016/09/20
[ "https://Stackoverflow.com/questions/39599961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245988/" ]
I spent half a day struggling with this. The underlying issue is switching between PHPUnit versions (`6.x.x` -> `4.x.x`). (Happened to me by switching branches) A click on the refresh button in the PHPUnit preferences fixes it. (`Languages & Frameworks > PHP > PHPUnit`) Make sure the version of PHPUnit it thinks you have matches the one it reports. [![screenshot](https://i.stack.imgur.com/HnrcU.png)](https://i.stack.imgur.com/HnrcU.png)
Problem was internal to the project. PHPUnit does not contain that error message. Sorry!
39,599,961
I have the latest PhpStorm (2016.2) and PHPUnit phar (5.5.4). For some reason when I run a PHPUnit test in my project in PhpStorm, it is adding on `--teamcity` to the run command, resulting in a failure: ``` Testing started at 12:52 PM ... Unit test suite invoked with a path to a non-unit test: --teamcity Process finished with exit code 1 ``` I have no idea where this `--teamcity` option is coming from, it happens no matter what test I run, and even when starting from a blank configuration. I also do NOT have the TeamCity plugin installed, I don't even use TeamCity. Here's what the full command appears as: ``` /usr/local/Cellar/php70/7.0.9/bin/php /Users/name/bin/phpunit-5.5.4.phar --configuration /path/to/config/my-phpunit.xml ClassNameTest /Users/name/PhpstormProjects/path/to/tests/unit/app/ClassNameTest.php --teamcity ``` (sensitive information swapped out) All I want to do is get rid of this `--teamcity` option, everything works if I run in a separate terminal window without that option. This only recently started happening, maybe after a PhpStorm update.
2016/09/20
[ "https://Stackoverflow.com/questions/39599961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245988/" ]
**tl;dr** I only could resolve this by removing the system installed phpunit instance from my system (Linux): ``` sudo apt remove phpunit-* ``` **Details** Even if the setting in PhpStorm was to use composer autoloader: [![phpunit library should use composer](https://i.stack.imgur.com/dLGDL.jpg)](https://i.stack.imgur.com/dLGDL.jpg) for some reason it ended up using TeamCity from `/usr/share/php/PHPUnit/Util/Log/TeamCity.php`: [![enter image description here](https://i.stack.imgur.com/YJWNc.png)](https://i.stack.imgur.com/YJWNc.png) Project's local PHPUnit was 6.2 while the system default was 5.1 -> they're incompatible.
Problem was internal to the project. PHPUnit does not contain that error message. Sorry!
39,599,961
I have the latest PhpStorm (2016.2) and PHPUnit phar (5.5.4). For some reason when I run a PHPUnit test in my project in PhpStorm, it is adding on `--teamcity` to the run command, resulting in a failure: ``` Testing started at 12:52 PM ... Unit test suite invoked with a path to a non-unit test: --teamcity Process finished with exit code 1 ``` I have no idea where this `--teamcity` option is coming from, it happens no matter what test I run, and even when starting from a blank configuration. I also do NOT have the TeamCity plugin installed, I don't even use TeamCity. Here's what the full command appears as: ``` /usr/local/Cellar/php70/7.0.9/bin/php /Users/name/bin/phpunit-5.5.4.phar --configuration /path/to/config/my-phpunit.xml ClassNameTest /Users/name/PhpstormProjects/path/to/tests/unit/app/ClassNameTest.php --teamcity ``` (sensitive information swapped out) All I want to do is get rid of this `--teamcity` option, everything works if I run in a separate terminal window without that option. This only recently started happening, maybe after a PhpStorm update.
2016/09/20
[ "https://Stackoverflow.com/questions/39599961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245988/" ]
This `--teamcity` option is used by PHPStorm to output tests result. What you're facing is an issue caused by PHP7 and an old version of PHPUnit. Remove your PHPUnit 5 and install the latest one (currently 6.2) with composer and use PHPUnit namespaces instead. More info on this bug: <https://github.com/sebastianbergmann/phpunit/issues/2460>
Problem was internal to the project. PHPUnit does not contain that error message. Sorry!
39,599,961
I have the latest PhpStorm (2016.2) and PHPUnit phar (5.5.4). For some reason when I run a PHPUnit test in my project in PhpStorm, it is adding on `--teamcity` to the run command, resulting in a failure: ``` Testing started at 12:52 PM ... Unit test suite invoked with a path to a non-unit test: --teamcity Process finished with exit code 1 ``` I have no idea where this `--teamcity` option is coming from, it happens no matter what test I run, and even when starting from a blank configuration. I also do NOT have the TeamCity plugin installed, I don't even use TeamCity. Here's what the full command appears as: ``` /usr/local/Cellar/php70/7.0.9/bin/php /Users/name/bin/phpunit-5.5.4.phar --configuration /path/to/config/my-phpunit.xml ClassNameTest /Users/name/PhpstormProjects/path/to/tests/unit/app/ClassNameTest.php --teamcity ``` (sensitive information swapped out) All I want to do is get rid of this `--teamcity` option, everything works if I run in a separate terminal window without that option. This only recently started happening, maybe after a PhpStorm update.
2016/09/20
[ "https://Stackoverflow.com/questions/39599961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245988/" ]
I spent half a day struggling with this. The underlying issue is switching between PHPUnit versions (`6.x.x` -> `4.x.x`). (Happened to me by switching branches) A click on the refresh button in the PHPUnit preferences fixes it. (`Languages & Frameworks > PHP > PHPUnit`) Make sure the version of PHPUnit it thinks you have matches the one it reports. [![screenshot](https://i.stack.imgur.com/HnrcU.png)](https://i.stack.imgur.com/HnrcU.png)
This `--teamcity` option is used by PHPStorm to output tests result. What you're facing is an issue caused by PHP7 and an old version of PHPUnit. Remove your PHPUnit 5 and install the latest one (currently 6.2) with composer and use PHPUnit namespaces instead. More info on this bug: <https://github.com/sebastianbergmann/phpunit/issues/2460>
39,599,961
I have the latest PhpStorm (2016.2) and PHPUnit phar (5.5.4). For some reason when I run a PHPUnit test in my project in PhpStorm, it is adding on `--teamcity` to the run command, resulting in a failure: ``` Testing started at 12:52 PM ... Unit test suite invoked with a path to a non-unit test: --teamcity Process finished with exit code 1 ``` I have no idea where this `--teamcity` option is coming from, it happens no matter what test I run, and even when starting from a blank configuration. I also do NOT have the TeamCity plugin installed, I don't even use TeamCity. Here's what the full command appears as: ``` /usr/local/Cellar/php70/7.0.9/bin/php /Users/name/bin/phpunit-5.5.4.phar --configuration /path/to/config/my-phpunit.xml ClassNameTest /Users/name/PhpstormProjects/path/to/tests/unit/app/ClassNameTest.php --teamcity ``` (sensitive information swapped out) All I want to do is get rid of this `--teamcity` option, everything works if I run in a separate terminal window without that option. This only recently started happening, maybe after a PhpStorm update.
2016/09/20
[ "https://Stackoverflow.com/questions/39599961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245988/" ]
**tl;dr** I only could resolve this by removing the system installed phpunit instance from my system (Linux): ``` sudo apt remove phpunit-* ``` **Details** Even if the setting in PhpStorm was to use composer autoloader: [![phpunit library should use composer](https://i.stack.imgur.com/dLGDL.jpg)](https://i.stack.imgur.com/dLGDL.jpg) for some reason it ended up using TeamCity from `/usr/share/php/PHPUnit/Util/Log/TeamCity.php`: [![enter image description here](https://i.stack.imgur.com/YJWNc.png)](https://i.stack.imgur.com/YJWNc.png) Project's local PHPUnit was 6.2 while the system default was 5.1 -> they're incompatible.
This `--teamcity` option is used by PHPStorm to output tests result. What you're facing is an issue caused by PHP7 and an old version of PHPUnit. Remove your PHPUnit 5 and install the latest one (currently 6.2) with composer and use PHPUnit namespaces instead. More info on this bug: <https://github.com/sebastianbergmann/phpunit/issues/2460>
95,843
I have roughly $30,000 CAD saved already and I've been looking to get my own place, perhaps a Condo but the prices in the GTA are just absurd, you're looking at 500k for a 1 bedroom/1 den/1 bath pre construction condo these days. I live with my parents and they are the ones getting a large windfall of money and the 100k is a portion they are gifting to me. So put yourself in my shoes, debt free, 25 years old, $130,000 in your account. Do I throw a large chunk of this on a down payment for a property or should I keep it, part of me just wants to sit on it because lets be honest its nice to open up your mobile banking app and see that kind of balance. Thanks.
2018/05/28
[ "https://money.stackexchange.com/questions/95843", "https://money.stackexchange.com", "https://money.stackexchange.com/users/72724/" ]
You probably know this already. Don't pull all of your eggs in one basket. Putting all of this money in real estate would be a giant mistake as it would tie up all your cash for a good amount of time, you run the risk of a market correction, etc. General advice would be to diversify between equities and bonds, perhaps some real instate. All of this depends on the investment opportunities at your disposal. If you haven't already, it's probably a good idea to max out your RRSP and TFSA.
Have you considered moving somewhere else or just renting? ========================================================== There must be somewhere in Canada where the real estate market is more reasonable, if you want to move out, maybe you should consider it. There seems to be a bit of ambiguity on what you exactly mean by investing in 'real-estate'. There are a lot of unit-trusts that focus on real-estate, that would be fine, but buying actual property to rent out is a risky proposition. Take the human element out of your investing and don't rent out your own place. Personally, I would rather consolidate your position with a well-rounded basket of investments and just move to a region with more reasonable properties to rent. Renting is just the most responsible way for young people to live. I know you are thinking something along the lines of getting that 20-year mortgage as soon as possible so you can start paying it off, but I would caution against this. If you rent you have much more control in living within your means. If you get a good job you can rent a place that you know you would be able to afford, if you lose your job, you can get out of the agreement much easier than if you have a mortgage. If you do well in your job and you get regular raises you can again probably within a year move to a place that is every time one peg higher on the socio-economic ladder, you cannot do this as easily with a house. Consider this money more in line with a 100K kickstart to a pension fund, you can later settle down and buy some property but for a 25 year old building a position is much better
2,558,164
I have a `Post` Class and a `Comment` Class. I have a post object and want to convert it to a Comment object. I went through Rails api and found becomes(klass).For now there is not association between a Post and Comment. So i tried ``` @post.becomes(Comment) ``` but becomes method could not be found for `@post` object. Am i missing something ?
2010/04/01
[ "https://Stackoverflow.com/questions/2558164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301419/" ]
Put the methods you want both models to use on a module. Then include that module in both models.
I'm assuming you are talking about classes deriving from ActiveRecord::Base. In that case, I think you have two options if you really want to convert posts into comments (which seems a bit strange to me): * You can have just one class (e.g. Entry) with an attribute which marks it as a post or a comment, which you would set as appropriate * You could create and save a new comment object containing the text of the post object, and then delete the post object.
2,558,164
I have a `Post` Class and a `Comment` Class. I have a post object and want to convert it to a Comment object. I went through Rails api and found becomes(klass).For now there is not association between a Post and Comment. So i tried ``` @post.becomes(Comment) ``` but becomes method could not be found for `@post` object. Am i missing something ?
2010/04/01
[ "https://Stackoverflow.com/questions/2558164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301419/" ]
Please note that *becomes* returns a new object but does not modify the existing object. You need to do the assignment yourself ``` @post = @post.becomes(Comment) ``` See the documentation [ActiveRecord::Persistence#becomes](http://apidock.com/rails/ActiveRecord/Persistence/becomes)
I'm assuming you are talking about classes deriving from ActiveRecord::Base. In that case, I think you have two options if you really want to convert posts into comments (which seems a bit strange to me): * You can have just one class (e.g. Entry) with an attribute which marks it as a post or a comment, which you would set as appropriate * You could create and save a new comment object containing the text of the post object, and then delete the post object.
39,061,046
I am trying to perform some actions when the view first loads. According to the ion-view documentation (<http://ionicframework.com/docs/api/directive/ionView/>), I should listen to the event `$ionicView.loaded`, which fires when the view is first loaded (*The view has loaded. This event only happens once per view being created and added to the DOM*). I am trying to listen the following way: ``` $scope.$on("$ionicView.loaded", function(event, data){ // handle event console.log("IONIC VIEW LOADED"); //updateScansList(db, $scope); //Populate list from table }); ``` When executing the program, I expect to see "IONIC VIEW LOADED" on the console, but that never happens. Is there a mistake that I am not catching? Is there a better way to listen to the first load of a View in Ionic? Thank you!
2016/08/21
[ "https://Stackoverflow.com/questions/39061046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413536/" ]
I had to add an API Usage plan, and then link the plan to the API stage. Seems like this is the only way to link the key to the API, not sure if this is a recent change on AWS.
For Private API Gateways accessed through public DNS, we need to pass additional header of 'x-apigw-api-id' with the api id along with 'x-api-key' if configured. curl -v https://{vpce-id}.execute-api.{region}.vpce.amazonaws.com/test -H 'x-apigw-api-id:{api-id}' Its documented below, <https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-api-test-invoke-url.html#w20aac13c16c28c11>
39,061,046
I am trying to perform some actions when the view first loads. According to the ion-view documentation (<http://ionicframework.com/docs/api/directive/ionView/>), I should listen to the event `$ionicView.loaded`, which fires when the view is first loaded (*The view has loaded. This event only happens once per view being created and added to the DOM*). I am trying to listen the following way: ``` $scope.$on("$ionicView.loaded", function(event, data){ // handle event console.log("IONIC VIEW LOADED"); //updateScansList(db, $scope); //Populate list from table }); ``` When executing the program, I expect to see "IONIC VIEW LOADED" on the console, but that never happens. Is there a mistake that I am not catching? Is there a better way to listen to the first load of a View in Ionic? Thank you!
2016/08/21
[ "https://Stackoverflow.com/questions/39061046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413536/" ]
I hope you are not missing to link the API key with the API [![API-Gateway Configuration](https://i.stack.imgur.com/KuqEb.png)](https://i.stack.imgur.com/KuqEb.png)
I don't have enough reputation to set this as a comment, But I was finally able to find the document specifying that 'x-api-key' belongs in the header for API Gateway calls that come from outside clients (like postman, swagger, etc.) in the AWS Documentation. The relevant part: > > To use header-sourced API keys: > > > 1. Create an API with desired API methods. And deploy the API to a > stage. > 2. Create a new usage plan or choose an existing one. Add the deployed > API stage to the usage plan. Attach an API key to the usage plan or > choose an existing API key in the plan. Note the chosen API key > value. > 3. Set up API methods to require an API key. > 4. Redeploy the API to the same stage. If you deploy the API to a new > stage, make sure to update the usage plan to attach the new API > stage. > > > The client can now call the API methods while supplying the x-api-key > header with the chosen API key as the header value. > > > [Choose an API key source](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-key-source.html)
39,061,046
I am trying to perform some actions when the view first loads. According to the ion-view documentation (<http://ionicframework.com/docs/api/directive/ionView/>), I should listen to the event `$ionicView.loaded`, which fires when the view is first loaded (*The view has loaded. This event only happens once per view being created and added to the DOM*). I am trying to listen the following way: ``` $scope.$on("$ionicView.loaded", function(event, data){ // handle event console.log("IONIC VIEW LOADED"); //updateScansList(db, $scope); //Populate list from table }); ``` When executing the program, I expect to see "IONIC VIEW LOADED" on the console, but that never happens. Is there a mistake that I am not catching? Is there a better way to listen to the first load of a View in Ionic? Thank you!
2016/08/21
[ "https://Stackoverflow.com/questions/39061046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413536/" ]
I was able to get a successful response from Lambda using below configuration in Postman native app - Under authorization tab (For some reason this didn't work when i passed the same parameters under header) Key : x-api-key Value : your-api-key-value Add to : Header
For Private API Gateways accessed through public DNS, we need to pass additional header of 'x-apigw-api-id' with the api id along with 'x-api-key' if configured. curl -v https://{vpce-id}.execute-api.{region}.vpce.amazonaws.com/test -H 'x-apigw-api-id:{api-id}' Its documented below, <https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-api-test-invoke-url.html#w20aac13c16c28c11>
39,061,046
I am trying to perform some actions when the view first loads. According to the ion-view documentation (<http://ionicframework.com/docs/api/directive/ionView/>), I should listen to the event `$ionicView.loaded`, which fires when the view is first loaded (*The view has loaded. This event only happens once per view being created and added to the DOM*). I am trying to listen the following way: ``` $scope.$on("$ionicView.loaded", function(event, data){ // handle event console.log("IONIC VIEW LOADED"); //updateScansList(db, $scope); //Populate list from table }); ``` When executing the program, I expect to see "IONIC VIEW LOADED" on the console, but that never happens. Is there a mistake that I am not catching? Is there a better way to listen to the first load of a View in Ionic? Thank you!
2016/08/21
[ "https://Stackoverflow.com/questions/39061046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413536/" ]
If you set 'API Key Required' option to true, please check below. 1. you have to pass 'x-api-key' HTTP Header Parameter to API Gateway. 2. The API Key had to be created. 3. In addition, you need to check a Usage Plan for the API Key on API Gateway Console.
I was able to get a successful response from Lambda using below configuration in Postman native app - Under authorization tab (For some reason this didn't work when i passed the same parameters under header) Key : x-api-key Value : your-api-key-value Add to : Header
39,061,046
I am trying to perform some actions when the view first loads. According to the ion-view documentation (<http://ionicframework.com/docs/api/directive/ionView/>), I should listen to the event `$ionicView.loaded`, which fires when the view is first loaded (*The view has loaded. This event only happens once per view being created and added to the DOM*). I am trying to listen the following way: ``` $scope.$on("$ionicView.loaded", function(event, data){ // handle event console.log("IONIC VIEW LOADED"); //updateScansList(db, $scope); //Populate list from table }); ``` When executing the program, I expect to see "IONIC VIEW LOADED" on the console, but that never happens. Is there a mistake that I am not catching? Is there a better way to listen to the first load of a View in Ionic? Thank you!
2016/08/21
[ "https://Stackoverflow.com/questions/39061046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413536/" ]
I was able to get a successful response from Lambda using below configuration in Postman native app - Under authorization tab (For some reason this didn't work when i passed the same parameters under header) Key : x-api-key Value : your-api-key-value Add to : Header
I don't have enough reputation to set this as a comment, But I was finally able to find the document specifying that 'x-api-key' belongs in the header for API Gateway calls that come from outside clients (like postman, swagger, etc.) in the AWS Documentation. The relevant part: > > To use header-sourced API keys: > > > 1. Create an API with desired API methods. And deploy the API to a > stage. > 2. Create a new usage plan or choose an existing one. Add the deployed > API stage to the usage plan. Attach an API key to the usage plan or > choose an existing API key in the plan. Note the chosen API key > value. > 3. Set up API methods to require an API key. > 4. Redeploy the API to the same stage. If you deploy the API to a new > stage, make sure to update the usage plan to attach the new API > stage. > > > The client can now call the API methods while supplying the x-api-key > header with the chosen API key as the header value. > > > [Choose an API key source](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-key-source.html)
39,061,046
I am trying to perform some actions when the view first loads. According to the ion-view documentation (<http://ionicframework.com/docs/api/directive/ionView/>), I should listen to the event `$ionicView.loaded`, which fires when the view is first loaded (*The view has loaded. This event only happens once per view being created and added to the DOM*). I am trying to listen the following way: ``` $scope.$on("$ionicView.loaded", function(event, data){ // handle event console.log("IONIC VIEW LOADED"); //updateScansList(db, $scope); //Populate list from table }); ``` When executing the program, I expect to see "IONIC VIEW LOADED" on the console, but that never happens. Is there a mistake that I am not catching? Is there a better way to listen to the first load of a View in Ionic? Thank you!
2016/08/21
[ "https://Stackoverflow.com/questions/39061046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413536/" ]
The `x-api-key` parameter is passed as a HTTP header parameter (i.e. it is not added to the JSON body). How you pass HTTP headers depend on the HTTP client you use. For example, if you use curl and assuming that you `POST` the JSON payload, a request would look something like (where you replace `[api-id]` with the actual id and `[region]` with the AWS region of your API): ``` $ curl -X POST -H "x-api-key: theKey" -H "Content-Type: application/json" -d '{"key":"val"}' https://[api-id].execute-api.[region].amazonaws.com ```
I had to add an API Usage plan, and then link the plan to the API stage. Seems like this is the only way to link the key to the API, not sure if this is a recent change on AWS.
39,061,046
I am trying to perform some actions when the view first loads. According to the ion-view documentation (<http://ionicframework.com/docs/api/directive/ionView/>), I should listen to the event `$ionicView.loaded`, which fires when the view is first loaded (*The view has loaded. This event only happens once per view being created and added to the DOM*). I am trying to listen the following way: ``` $scope.$on("$ionicView.loaded", function(event, data){ // handle event console.log("IONIC VIEW LOADED"); //updateScansList(db, $scope); //Populate list from table }); ``` When executing the program, I expect to see "IONIC VIEW LOADED" on the console, but that never happens. Is there a mistake that I am not catching? Is there a better way to listen to the first load of a View in Ionic? Thank you!
2016/08/21
[ "https://Stackoverflow.com/questions/39061046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413536/" ]
If you set 'API' key required to true, you need to pass the api key as header. API Key is passed as header field 'x-api-key'. Even after adding this field in header, this issue may occur. In that case, please validate below points 1. Do you have a Usage Plan? if not need to create one. 2. Link you API with Usage Plan. For that add a stage, it will link your API 3. Do you have API Key? if not you need to create an API Key and enable it. 4. Add the Usage Plan which is linked with your API to this API Key. For that, add Usage Plan.
For Private API Gateways accessed through public DNS, we need to pass additional header of 'x-apigw-api-id' with the api id along with 'x-api-key' if configured. curl -v https://{vpce-id}.execute-api.{region}.vpce.amazonaws.com/test -H 'x-apigw-api-id:{api-id}' Its documented below, <https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-api-test-invoke-url.html#w20aac13c16c28c11>
39,061,046
I am trying to perform some actions when the view first loads. According to the ion-view documentation (<http://ionicframework.com/docs/api/directive/ionView/>), I should listen to the event `$ionicView.loaded`, which fires when the view is first loaded (*The view has loaded. This event only happens once per view being created and added to the DOM*). I am trying to listen the following way: ``` $scope.$on("$ionicView.loaded", function(event, data){ // handle event console.log("IONIC VIEW LOADED"); //updateScansList(db, $scope); //Populate list from table }); ``` When executing the program, I expect to see "IONIC VIEW LOADED" on the console, but that never happens. Is there a mistake that I am not catching? Is there a better way to listen to the first load of a View in Ionic? Thank you!
2016/08/21
[ "https://Stackoverflow.com/questions/39061046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413536/" ]
I had to add an API Usage plan, and then link the plan to the API stage. Seems like this is the only way to link the key to the API, not sure if this is a recent change on AWS.
I was able to get a successful response from Lambda using below configuration in Postman native app - Under authorization tab (For some reason this didn't work when i passed the same parameters under header) Key : x-api-key Value : your-api-key-value Add to : Header
39,061,046
I am trying to perform some actions when the view first loads. According to the ion-view documentation (<http://ionicframework.com/docs/api/directive/ionView/>), I should listen to the event `$ionicView.loaded`, which fires when the view is first loaded (*The view has loaded. This event only happens once per view being created and added to the DOM*). I am trying to listen the following way: ``` $scope.$on("$ionicView.loaded", function(event, data){ // handle event console.log("IONIC VIEW LOADED"); //updateScansList(db, $scope); //Populate list from table }); ``` When executing the program, I expect to see "IONIC VIEW LOADED" on the console, but that never happens. Is there a mistake that I am not catching? Is there a better way to listen to the first load of a View in Ionic? Thank you!
2016/08/21
[ "https://Stackoverflow.com/questions/39061046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413536/" ]
I had to add an API Usage plan, and then link the plan to the API stage. Seems like this is the only way to link the key to the API, not sure if this is a recent change on AWS.
If you set 'API Key Required' option to true, please check below. 1. you have to pass 'x-api-key' HTTP Header Parameter to API Gateway. 2. The API Key had to be created. 3. In addition, you need to check a Usage Plan for the API Key on API Gateway Console.
39,061,046
I am trying to perform some actions when the view first loads. According to the ion-view documentation (<http://ionicframework.com/docs/api/directive/ionView/>), I should listen to the event `$ionicView.loaded`, which fires when the view is first loaded (*The view has loaded. This event only happens once per view being created and added to the DOM*). I am trying to listen the following way: ``` $scope.$on("$ionicView.loaded", function(event, data){ // handle event console.log("IONIC VIEW LOADED"); //updateScansList(db, $scope); //Populate list from table }); ``` When executing the program, I expect to see "IONIC VIEW LOADED" on the console, but that never happens. Is there a mistake that I am not catching? Is there a better way to listen to the first load of a View in Ionic? Thank you!
2016/08/21
[ "https://Stackoverflow.com/questions/39061046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413536/" ]
I hope you are not missing to link the API key with the API [![API-Gateway Configuration](https://i.stack.imgur.com/KuqEb.png)](https://i.stack.imgur.com/KuqEb.png)
For Private API Gateways accessed through public DNS, we need to pass additional header of 'x-apigw-api-id' with the api id along with 'x-api-key' if configured. curl -v https://{vpce-id}.execute-api.{region}.vpce.amazonaws.com/test -H 'x-apigw-api-id:{api-id}' Its documented below, <https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-api-test-invoke-url.html#w20aac13c16c28c11>
368,662
My clientmqueue folder contains almost twice as many mails as what mailq -Ac shows as enqueued messages in that folder. When I look at them individually, it looks like the headers and the contents are stored in seperate files. Is there a tool or different value to pass to mailq to where I can view the whole e-mails together? (especially the sender, receiver, subject and body)
2012/03/12
[ "https://serverfault.com/questions/368662", "https://serverfault.com", "https://serverfault.com/users/113702/" ]
Most of the times your files in the queue directory will be x2 the messages in queue. There may also be files in the the queue directory that do not correspond to queued messages because they are left there as leftovers which for some reason were not erased after the queue was processed. If you observe the message identifiers and the queue file names you will see that they are linked. According to the "[bat book](http://shop.oreilly.com/product/9780596510299.do)" (page 396) the complete form for each filename is: ``` Xfident ``` The X is one of the leading letters. The f is the constant letter f.The ident is a unique queue identifier associated with each mail message. About the leading letters now: * df - Data (message body) * lf - Lock file (obsolete and removed as of V5.62) * nf - ID creation file (obsolete and removed as of V5.62) * tf - Temporary qf rewrite image * xf - Transcript file * qf - Queue control file (and headers) Armed with the above information you can script your way around the `mailq` output and do whatever you like. You may also want to check the sources of `qtool.pl` that comes with sendmail if you want to do elaborate stuff.
The value shown by the mailq command is correct. As you've surmised sendmail stores the message and its headers separately in the queue directory. AFAIK there is no way to view the whole message using mailq - Its showing you a queue summary, it's not a tool for snooping into mail contents. The best you can do is cat the header & data file together to view them on the console (why you would want to do this, and the ethics of reading other people's mail are beyond me though...)
3,352,300
I got the code from wikipedia for linked list ( <http://en.wikipedia.org/wiki/Linked_list> ). But it prints the result in reverse order (5 4 3 2 1 ). How to make this to print from beginning ( 1 2 3 4 5).
2010/07/28
[ "https://Stackoverflow.com/questions/3352300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400085/" ]
I assume you're talking about the C implementation in "Language support". It doesn't print in reverse order. It's because elements are inserted in the head of the list, so inserting 1, 2, 3 would result in a list that contains 3, 2, 1. This is because the list is represented by its head, so it's faster inserting at the head than the tail. To insert at the tail you would have to go through the entire list. This makes insertion O(n) instead of O(1). Seeing as this is a singly-linked list, you cannot print it in the other order because you can only step forward.
That is because the way the list is constructed. To print it in reverse, just recurse to the last entry and print from there.
3,352,300
I got the code from wikipedia for linked list ( <http://en.wikipedia.org/wiki/Linked_list> ). But it prints the result in reverse order (5 4 3 2 1 ). How to make this to print from beginning ( 1 2 3 4 5).
2010/07/28
[ "https://Stackoverflow.com/questions/3352300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400085/" ]
I assume you're talking about the C implementation in "Language support". It doesn't print in reverse order. It's because elements are inserted in the head of the list, so inserting 1, 2, 3 would result in a list that contains 3, 2, 1. This is because the list is represented by its head, so it's faster inserting at the head than the tail. To insert at the tail you would have to go through the entire list. This makes insertion O(n) instead of O(1). Seeing as this is a singly-linked list, you cannot print it in the other order because you can only step forward.
The order in which list is being printed is the order in which elements are present in the list. You can print it in reverse order (i.e in order in which elements were inserted) using recursion. following code will print the list in reverse order > > void list\_print(LLIST \*n) { > > if (n == NULL) > > { > > printf("list is empty\n"); > > return; > > } > > } > > > void print\_recursive(LLIST \*n) { > > if(n->next==NULL) > > printf("%d\n",n->data); > > else > > print\_recursive(LLIST n->next); > > } > > >
3,352,300
I got the code from wikipedia for linked list ( <http://en.wikipedia.org/wiki/Linked_list> ). But it prints the result in reverse order (5 4 3 2 1 ). How to make this to print from beginning ( 1 2 3 4 5).
2010/07/28
[ "https://Stackoverflow.com/questions/3352300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400085/" ]
I assume you're talking about the C implementation in "Language support". It doesn't print in reverse order. It's because elements are inserted in the head of the list, so inserting 1, 2, 3 would result in a list that contains 3, 2, 1. This is because the list is represented by its head, so it's faster inserting at the head than the tail. To insert at the tail you would have to go through the entire list. This makes insertion O(n) instead of O(1). Seeing as this is a singly-linked list, you cannot print it in the other order because you can only step forward.
I have this program which prints a string in reverse using recursion. Can you please use your linked list as input to it? ``` void reversePrint(char *str) { if(*str == '\0') return; reversePrint(str+1); printf("%c",*str); } int main() { char *input; input = malloc(10); strcpy(input,"wolfrevo"); reversePrint(input); } ``` I can change it myself, but hope it will be a nice excercise for you. **Hints:** 1. Pass linked list instead of string // Change the protype too 2. Check for list being NULL 3. Recurse by pass next element of Linked list 4. Print the data inside list instead of string
3,352,300
I got the code from wikipedia for linked list ( <http://en.wikipedia.org/wiki/Linked_list> ). But it prints the result in reverse order (5 4 3 2 1 ). How to make this to print from beginning ( 1 2 3 4 5).
2010/07/28
[ "https://Stackoverflow.com/questions/3352300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400085/" ]
I assume you're talking about the C implementation in "Language support". It doesn't print in reverse order. It's because elements are inserted in the head of the list, so inserting 1, 2, 3 would result in a list that contains 3, 2, 1. This is because the list is represented by its head, so it's faster inserting at the head than the tail. To insert at the tail you would have to go through the entire list. This makes insertion O(n) instead of O(1). Seeing as this is a singly-linked list, you cannot print it in the other order because you can only step forward.
You can also try a double-linked list. Basically, you have an additional pointer to the previous element ``` typedef struct node { int data; struct node *next; /* pointer to next element in list */ struct node *previous; /* pointer to previous element in list */ } node; typedef struct list { node *head; /* first element in list */ node *tail; /* last element in list */ } list; ``` You can then print the list from the head and/or from the tail.
3,352,300
I got the code from wikipedia for linked list ( <http://en.wikipedia.org/wiki/Linked_list> ). But it prints the result in reverse order (5 4 3 2 1 ). How to make this to print from beginning ( 1 2 3 4 5).
2010/07/28
[ "https://Stackoverflow.com/questions/3352300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400085/" ]
Looking at the following example: ``` /****************************************************************/ /* Function: Add an element to our list */ /* */ /* Parameters: **p is the node that we wish to insert at. */ /* if the node is the null insert it at the beginning */ /* Other wise put it in the next space */ LLIST *list_add(LLIST **p, int i) { if (p == NULL) /*checks to see if the pointer points somewhere in space*/ return NULL; LLIST *n = malloc(sizeof(LLIST)); /* creates a new node of the correct data size */ if (n == NULL) return NULL; n->next = *p; /* the previous element (*p) now becomes the "next" element */ *p = n; /* add new empty element to the front (head) of the list */ n->data = i; return *p; } ``` Elements are being added to the *beginning* of the linked list when you call `list_add`. This is for efficiency reasons; you don't have to transverse the entire linked list to insert an element (which you would have to do if you wanted to append). To print in reverse, you can use recursion, build your own stack (which is the blind man's recursion), or recreate the list in reverse. A recursive version: ``` void list_print_reverse(LLIST *n) { if (n == NULL) { printf("list is empty\n"); return; } if (n->next != NULL) { list_print_reverse(n->next); } printf("print %p %p %d\n", n, n->next, n->data); } ```
That is because the way the list is constructed. To print it in reverse, just recurse to the last entry and print from there.
3,352,300
I got the code from wikipedia for linked list ( <http://en.wikipedia.org/wiki/Linked_list> ). But it prints the result in reverse order (5 4 3 2 1 ). How to make this to print from beginning ( 1 2 3 4 5).
2010/07/28
[ "https://Stackoverflow.com/questions/3352300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400085/" ]
Looking at the following example: ``` /****************************************************************/ /* Function: Add an element to our list */ /* */ /* Parameters: **p is the node that we wish to insert at. */ /* if the node is the null insert it at the beginning */ /* Other wise put it in the next space */ LLIST *list_add(LLIST **p, int i) { if (p == NULL) /*checks to see if the pointer points somewhere in space*/ return NULL; LLIST *n = malloc(sizeof(LLIST)); /* creates a new node of the correct data size */ if (n == NULL) return NULL; n->next = *p; /* the previous element (*p) now becomes the "next" element */ *p = n; /* add new empty element to the front (head) of the list */ n->data = i; return *p; } ``` Elements are being added to the *beginning* of the linked list when you call `list_add`. This is for efficiency reasons; you don't have to transverse the entire linked list to insert an element (which you would have to do if you wanted to append). To print in reverse, you can use recursion, build your own stack (which is the blind man's recursion), or recreate the list in reverse. A recursive version: ``` void list_print_reverse(LLIST *n) { if (n == NULL) { printf("list is empty\n"); return; } if (n->next != NULL) { list_print_reverse(n->next); } printf("print %p %p %d\n", n, n->next, n->data); } ```
The order in which list is being printed is the order in which elements are present in the list. You can print it in reverse order (i.e in order in which elements were inserted) using recursion. following code will print the list in reverse order > > void list\_print(LLIST \*n) { > > if (n == NULL) > > { > > printf("list is empty\n"); > > return; > > } > > } > > > void print\_recursive(LLIST \*n) { > > if(n->next==NULL) > > printf("%d\n",n->data); > > else > > print\_recursive(LLIST n->next); > > } > > >
3,352,300
I got the code from wikipedia for linked list ( <http://en.wikipedia.org/wiki/Linked_list> ). But it prints the result in reverse order (5 4 3 2 1 ). How to make this to print from beginning ( 1 2 3 4 5).
2010/07/28
[ "https://Stackoverflow.com/questions/3352300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400085/" ]
Looking at the following example: ``` /****************************************************************/ /* Function: Add an element to our list */ /* */ /* Parameters: **p is the node that we wish to insert at. */ /* if the node is the null insert it at the beginning */ /* Other wise put it in the next space */ LLIST *list_add(LLIST **p, int i) { if (p == NULL) /*checks to see if the pointer points somewhere in space*/ return NULL; LLIST *n = malloc(sizeof(LLIST)); /* creates a new node of the correct data size */ if (n == NULL) return NULL; n->next = *p; /* the previous element (*p) now becomes the "next" element */ *p = n; /* add new empty element to the front (head) of the list */ n->data = i; return *p; } ``` Elements are being added to the *beginning* of the linked list when you call `list_add`. This is for efficiency reasons; you don't have to transverse the entire linked list to insert an element (which you would have to do if you wanted to append). To print in reverse, you can use recursion, build your own stack (which is the blind man's recursion), or recreate the list in reverse. A recursive version: ``` void list_print_reverse(LLIST *n) { if (n == NULL) { printf("list is empty\n"); return; } if (n->next != NULL) { list_print_reverse(n->next); } printf("print %p %p %d\n", n, n->next, n->data); } ```
I have this program which prints a string in reverse using recursion. Can you please use your linked list as input to it? ``` void reversePrint(char *str) { if(*str == '\0') return; reversePrint(str+1); printf("%c",*str); } int main() { char *input; input = malloc(10); strcpy(input,"wolfrevo"); reversePrint(input); } ``` I can change it myself, but hope it will be a nice excercise for you. **Hints:** 1. Pass linked list instead of string // Change the protype too 2. Check for list being NULL 3. Recurse by pass next element of Linked list 4. Print the data inside list instead of string
3,352,300
I got the code from wikipedia for linked list ( <http://en.wikipedia.org/wiki/Linked_list> ). But it prints the result in reverse order (5 4 3 2 1 ). How to make this to print from beginning ( 1 2 3 4 5).
2010/07/28
[ "https://Stackoverflow.com/questions/3352300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/400085/" ]
Looking at the following example: ``` /****************************************************************/ /* Function: Add an element to our list */ /* */ /* Parameters: **p is the node that we wish to insert at. */ /* if the node is the null insert it at the beginning */ /* Other wise put it in the next space */ LLIST *list_add(LLIST **p, int i) { if (p == NULL) /*checks to see if the pointer points somewhere in space*/ return NULL; LLIST *n = malloc(sizeof(LLIST)); /* creates a new node of the correct data size */ if (n == NULL) return NULL; n->next = *p; /* the previous element (*p) now becomes the "next" element */ *p = n; /* add new empty element to the front (head) of the list */ n->data = i; return *p; } ``` Elements are being added to the *beginning* of the linked list when you call `list_add`. This is for efficiency reasons; you don't have to transverse the entire linked list to insert an element (which you would have to do if you wanted to append). To print in reverse, you can use recursion, build your own stack (which is the blind man's recursion), or recreate the list in reverse. A recursive version: ``` void list_print_reverse(LLIST *n) { if (n == NULL) { printf("list is empty\n"); return; } if (n->next != NULL) { list_print_reverse(n->next); } printf("print %p %p %d\n", n, n->next, n->data); } ```
You can also try a double-linked list. Basically, you have an additional pointer to the previous element ``` typedef struct node { int data; struct node *next; /* pointer to next element in list */ struct node *previous; /* pointer to previous element in list */ } node; typedef struct list { node *head; /* first element in list */ node *tail; /* last element in list */ } list; ``` You can then print the list from the head and/or from the tail.
15,157,370
I have one console app which receives a variable number of arguments. I need to remove the first element (args[0]) and merge all the others into a single string. How I can do that in .NET 2.0?
2013/03/01
[ "https://Stackoverflow.com/questions/15157370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/503831/" ]
``` string result = string.Join(" ", args, 1, args.Count-1); ``` This concatenates all the arguments but the first, separating them with spaces. See <http://msdn.microsoft.com/en-us/library/tk0xe5h0.aspx>
You could do the following: If you need a delimiter: ``` string delim = "%"; string merge = args[1]; for (int i = 2; i < args.Length; i++) { merge = delim + args[i]; } ``` If you don't need a delimiter: ``` args[0] = ""; string merge = String.Join("", args); ```
26,383,776
I have a `data.frame` and I want to split one of its columns to two based on a regular expression. More specifically the strings have a suffix in parentheses that needs to be extracted to a column of its own. So e.g. I want to get from here: ``` dfInit <- data.frame(VAR = paste0(c(1:10),"(",c("A","B"),")")) ``` to here: ``` dfFinal <- data.frame(VAR1 = c(1:10), VAR2 = c("A","B")) ```
2014/10/15
[ "https://Stackoverflow.com/questions/26383776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289444/" ]
**1) gsubfn::read.pattern** `read.pattern` in the gsubfn package can do that. The matches to the parenthesized portions of the regular rexpression are regarded as the fields: ``` library(gsubfn) read.pattern(text = as.character(dfInit$VAR), pattern = "(.*)[(](.*)[)]$") ``` giving: ``` V1 V2 1 1 A 2 2 B 3 3 A 4 4 B 5 5 A 6 6 B 7 7 A 8 8 B 9 9 A 10 10 B ``` **2) sub** Another way is to use `sub`: ``` data.frame(V1=sub("\\(.*", "", dfInit$VAR), V2=sub(".*\\((.)\\)$", "\\1", dfInit$VAR)) ``` giving the same result. **3) read.table** This solution does not use a regular expression: ``` read.table(text = as.character(dfInit$VAR), sep = "(", comment = ")") ``` giving the same result.
See [Split column at delimiter in data frame](https://stackoverflow.com/questions/7069076/split-column-at-delimiter-in-data-frame) ``` dfFinal <- within(dfInit, VAR<-data.frame(do.call('rbind', strsplit(as.character(VAR), '[[:punct:]]')))) > dfFinal VAR.X1 VAR.X2 1 1 A 2 2 B 3 3 A 4 4 B 5 5 A 6 6 B 7 7 A 8 8 B 9 9 A 10 10 B ```
26,383,776
I have a `data.frame` and I want to split one of its columns to two based on a regular expression. More specifically the strings have a suffix in parentheses that needs to be extracted to a column of its own. So e.g. I want to get from here: ``` dfInit <- data.frame(VAR = paste0(c(1:10),"(",c("A","B"),")")) ``` to here: ``` dfFinal <- data.frame(VAR1 = c(1:10), VAR2 = c("A","B")) ```
2014/10/15
[ "https://Stackoverflow.com/questions/26383776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289444/" ]
**1) gsubfn::read.pattern** `read.pattern` in the gsubfn package can do that. The matches to the parenthesized portions of the regular rexpression are regarded as the fields: ``` library(gsubfn) read.pattern(text = as.character(dfInit$VAR), pattern = "(.*)[(](.*)[)]$") ``` giving: ``` V1 V2 1 1 A 2 2 B 3 3 A 4 4 B 5 5 A 6 6 B 7 7 A 8 8 B 9 9 A 10 10 B ``` **2) sub** Another way is to use `sub`: ``` data.frame(V1=sub("\\(.*", "", dfInit$VAR), V2=sub(".*\\((.)\\)$", "\\1", dfInit$VAR)) ``` giving the same result. **3) read.table** This solution does not use a regular expression: ``` read.table(text = as.character(dfInit$VAR), sep = "(", comment = ")") ``` giving the same result.
You could also use `extract` from `tidyr` ``` library(tidyr) extract(dfInit, VAR, c("VAR1", "VAR2"), "(\\d+).([[:alpha:]]+).", convert=TRUE) # edited and added `convert=TRUE` as per @aosmith's comments. # VAR1 VAR2 #1 1 A #2 2 B #3 3 A #4 4 B #5 5 A #6 6 B #7 7 A #8 8 B #9 9 A #10 10 B ```
26,383,776
I have a `data.frame` and I want to split one of its columns to two based on a regular expression. More specifically the strings have a suffix in parentheses that needs to be extracted to a column of its own. So e.g. I want to get from here: ``` dfInit <- data.frame(VAR = paste0(c(1:10),"(",c("A","B"),")")) ``` to here: ``` dfFinal <- data.frame(VAR1 = c(1:10), VAR2 = c("A","B")) ```
2014/10/15
[ "https://Stackoverflow.com/questions/26383776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289444/" ]
**1) gsubfn::read.pattern** `read.pattern` in the gsubfn package can do that. The matches to the parenthesized portions of the regular rexpression are regarded as the fields: ``` library(gsubfn) read.pattern(text = as.character(dfInit$VAR), pattern = "(.*)[(](.*)[)]$") ``` giving: ``` V1 V2 1 1 A 2 2 B 3 3 A 4 4 B 5 5 A 6 6 B 7 7 A 8 8 B 9 9 A 10 10 B ``` **2) sub** Another way is to use `sub`: ``` data.frame(V1=sub("\\(.*", "", dfInit$VAR), V2=sub(".*\\((.)\\)$", "\\1", dfInit$VAR)) ``` giving the same result. **3) read.table** This solution does not use a regular expression: ``` read.table(text = as.character(dfInit$VAR), sep = "(", comment = ")") ``` giving the same result.
You can also use `cSplit` from `splitstackshape`. ``` library(splitstackshape) cSplit(dfInit, "VAR", "[()]", fixed=FALSE) # VAR_1 VAR_2 # 1: 1 A # 2: 2 B # 3: 3 A # 4: 4 B # 5: 5 A # 6: 6 B # 7: 7 A # 8: 8 B # 9: 9 A #10: 10 B ```
26,383,776
I have a `data.frame` and I want to split one of its columns to two based on a regular expression. More specifically the strings have a suffix in parentheses that needs to be extracted to a column of its own. So e.g. I want to get from here: ``` dfInit <- data.frame(VAR = paste0(c(1:10),"(",c("A","B"),")")) ``` to here: ``` dfFinal <- data.frame(VAR1 = c(1:10), VAR2 = c("A","B")) ```
2014/10/15
[ "https://Stackoverflow.com/questions/26383776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289444/" ]
**1) gsubfn::read.pattern** `read.pattern` in the gsubfn package can do that. The matches to the parenthesized portions of the regular rexpression are regarded as the fields: ``` library(gsubfn) read.pattern(text = as.character(dfInit$VAR), pattern = "(.*)[(](.*)[)]$") ``` giving: ``` V1 V2 1 1 A 2 2 B 3 3 A 4 4 B 5 5 A 6 6 B 7 7 A 8 8 B 9 9 A 10 10 B ``` **2) sub** Another way is to use `sub`: ``` data.frame(V1=sub("\\(.*", "", dfInit$VAR), V2=sub(".*\\((.)\\)$", "\\1", dfInit$VAR)) ``` giving the same result. **3) read.table** This solution does not use a regular expression: ``` read.table(text = as.character(dfInit$VAR), sep = "(", comment = ")") ``` giving the same result.
An approach with `regmatches` and `gregexpr`: ``` as.data.frame(do.call(rbind, regmatches(dfInit$VAR, gregexpr("\\w+", dfInit$VAR)))) ```
26,383,776
I have a `data.frame` and I want to split one of its columns to two based on a regular expression. More specifically the strings have a suffix in parentheses that needs to be extracted to a column of its own. So e.g. I want to get from here: ``` dfInit <- data.frame(VAR = paste0(c(1:10),"(",c("A","B"),")")) ``` to here: ``` dfFinal <- data.frame(VAR1 = c(1:10), VAR2 = c("A","B")) ```
2014/10/15
[ "https://Stackoverflow.com/questions/26383776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289444/" ]
You could also use `extract` from `tidyr` ``` library(tidyr) extract(dfInit, VAR, c("VAR1", "VAR2"), "(\\d+).([[:alpha:]]+).", convert=TRUE) # edited and added `convert=TRUE` as per @aosmith's comments. # VAR1 VAR2 #1 1 A #2 2 B #3 3 A #4 4 B #5 5 A #6 6 B #7 7 A #8 8 B #9 9 A #10 10 B ```
See [Split column at delimiter in data frame](https://stackoverflow.com/questions/7069076/split-column-at-delimiter-in-data-frame) ``` dfFinal <- within(dfInit, VAR<-data.frame(do.call('rbind', strsplit(as.character(VAR), '[[:punct:]]')))) > dfFinal VAR.X1 VAR.X2 1 1 A 2 2 B 3 3 A 4 4 B 5 5 A 6 6 B 7 7 A 8 8 B 9 9 A 10 10 B ```
26,383,776
I have a `data.frame` and I want to split one of its columns to two based on a regular expression. More specifically the strings have a suffix in parentheses that needs to be extracted to a column of its own. So e.g. I want to get from here: ``` dfInit <- data.frame(VAR = paste0(c(1:10),"(",c("A","B"),")")) ``` to here: ``` dfFinal <- data.frame(VAR1 = c(1:10), VAR2 = c("A","B")) ```
2014/10/15
[ "https://Stackoverflow.com/questions/26383776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289444/" ]
You could also use `extract` from `tidyr` ``` library(tidyr) extract(dfInit, VAR, c("VAR1", "VAR2"), "(\\d+).([[:alpha:]]+).", convert=TRUE) # edited and added `convert=TRUE` as per @aosmith's comments. # VAR1 VAR2 #1 1 A #2 2 B #3 3 A #4 4 B #5 5 A #6 6 B #7 7 A #8 8 B #9 9 A #10 10 B ```
You can also use `cSplit` from `splitstackshape`. ``` library(splitstackshape) cSplit(dfInit, "VAR", "[()]", fixed=FALSE) # VAR_1 VAR_2 # 1: 1 A # 2: 2 B # 3: 3 A # 4: 4 B # 5: 5 A # 6: 6 B # 7: 7 A # 8: 8 B # 9: 9 A #10: 10 B ```
26,383,776
I have a `data.frame` and I want to split one of its columns to two based on a regular expression. More specifically the strings have a suffix in parentheses that needs to be extracted to a column of its own. So e.g. I want to get from here: ``` dfInit <- data.frame(VAR = paste0(c(1:10),"(",c("A","B"),")")) ``` to here: ``` dfFinal <- data.frame(VAR1 = c(1:10), VAR2 = c("A","B")) ```
2014/10/15
[ "https://Stackoverflow.com/questions/26383776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289444/" ]
You could also use `extract` from `tidyr` ``` library(tidyr) extract(dfInit, VAR, c("VAR1", "VAR2"), "(\\d+).([[:alpha:]]+).", convert=TRUE) # edited and added `convert=TRUE` as per @aosmith's comments. # VAR1 VAR2 #1 1 A #2 2 B #3 3 A #4 4 B #5 5 A #6 6 B #7 7 A #8 8 B #9 9 A #10 10 B ```
An approach with `regmatches` and `gregexpr`: ``` as.data.frame(do.call(rbind, regmatches(dfInit$VAR, gregexpr("\\w+", dfInit$VAR)))) ```
7,513,638
The problem is, that this sensors should be available: * int TYPE\_ACCELEROMETER * int TYPE\_ALL * int **TYPE\_GRAVITY** * int TYPE\_GYROSCOPE * int TYPE\_LIGHT * int **\*TYPE\_LINEAR\_ACCELERATION\*** * int TYPE\_MAGNETIC\_FIELD * int TYPE\_ORIENTATION * int TYPE\_PRESSURE * int TYPE\_PROXIMITY * int **TYPE\_ROTATION\_VECTOR** * int TYPE\_TEMPERATURE Why are these three disabled? They are not recognised..."TYPE\_ROTATION\_VECTOR cannot be resolved or is not a field" Only these are recognised: * int TYPE\_ACCELEROMETER * int TYPE\_ALL * int TYPE\_GYROSCOPE * int TYPE\_LIGHT * int TYPE\_MAGNETIC\_FIELD * int TYPE\_ORIENTATION * int TYPE\_PRESSURE * int TYPE\_PROXIMITY * int TYPE\_TEMPERATURE code is: ``` mRotationVectorSensor = mSensorManager.getDefaultSensor( Sensor.TYPE_ROTATION_VECTOR); ``` Project build target is 2.2, API 8. Why i can not use TYPE\_ROTATION\_VECTOR and other types? Tnx for andswer!
2011/09/22
[ "https://Stackoverflow.com/questions/7513638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/958868/" ]
You are trying to access a sensor that is available only from API version 9 (you are using API version 8). <http://developer.android.com/reference/android/hardware/Sensor.html#TYPE_ROTATION_VECTOR> Check the "Since API level ..." at the right of each method/field
in Android 2.2, Gravity and linear Acceleration Vectors are not available... Only for versions 2.3 (GingerBread) and newer... Greetings Ralf
48,847,528
I'm making a Discord bot and there's a channel in my server allocated to our rules and I want this bot to automatically send a message in that channel. Is it possible to check if the channel exists? Thanks.
2018/02/18
[ "https://Stackoverflow.com/questions/48847528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9197625/" ]
Ideally, on the main thread, you don't do anything with the data until the last object has been received. So, passing the whole array in one go is a better approach. You can do this instead: ``` func didGetPasses(_ passes: Passes) { passes.append(passes); passList.reloadData(); } ``` And call ``` self.delegate?.didGetPasses(passes) ``` once the for loop is completed. PS: You should also consider using closures. It helps in handling logic and makes code more 'in-place' at the call site.
Is ``` guard let cell = tableView.dequeueReusableCell(withIdentifier: "passCell") as? PassCell else { return PassCell() } ``` correct? seems you are returning an uninitialised PassCell there
48,847,528
I'm making a Discord bot and there's a channel in my server allocated to our rules and I want this bot to automatically send a message in that channel. Is it possible to check if the channel exists? Thanks.
2018/02/18
[ "https://Stackoverflow.com/questions/48847528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9197625/" ]
Ideally, on the main thread, you don't do anything with the data until the last object has been received. So, passing the whole array in one go is a better approach. You can do this instead: ``` func didGetPasses(_ passes: Passes) { passes.append(passes); passList.reloadData(); } ``` And call ``` self.delegate?.didGetPasses(passes) ``` once the for loop is completed. PS: You should also consider using closures. It helps in handling logic and makes code more 'in-place' at the call site.
I decided on an answer inspired by advice from Kunal Shah. I stopped looping the delegate call and instead put together a collection of Pass objects to send to the main thread. I didn't want to do this as my previous experience with this led to empty collections being sent for some reason, but it seems to work here. This way I still only reload the tableview once, but also only call the delegate method once.
8,310,716
I am not experienced in handling of the memory in a C++ program, so I would like a piece of advice in that case: I want to create a `new Object` in a function in a class which is essential till the end of the program. As far as I am concerned, if I use the operator `new`, I should sometimes delete it. Taking into account that it must be initialized inside a class, when and how must I finally delete it?
2011/11/29
[ "https://Stackoverflow.com/questions/8310716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954724/" ]
I suggest the *smart pointer idiom* ``` #include <memory> struct X { void foo() { } }; std::share_ptr<X> makeX() // could also be a class member of course { return std::make_shared<X>(); } int main() { std::share_ptr<X> stayaround = makeX(); // can just be used like an ordinary pointer: stayaround->foo(); // auto-deletes <sup>1</sup> } ``` If the pointer is truly a static variable, you can substitute a `unique_ptr` (which works similarly, but passes ownership on assignment; this means that the pointer doesn't have to keep a *reference count*) ***Note*** To learn more about C++ smart pointers in general, see **[smart pointers (boost) explained](https://stackoverflow.com/questions/569775/smart-pointers-boost-explained)** ***Note*** If you don't have the TR1/C++0x support for this, you can just use Boost Smartpointer --- 1 unless you are *leaking* copies of the shared\_ptr itself; that would be some strange use of smart pointers previously unseen :)
On most operating systems (in particular Linux), if you allocate an object pointer with `new Object`, and don't bother `delete`-ing because you'll need it till the program ends, no harm is really done. There is some memory leak inside your program (you can use [valgrind](http://valgrind.org/) to hunt such leaks) but the kernel will release all the memory used by a process when it has ended. A better alternative is to have a singleton class for the application data, like e.g. [QApplication](http://doc.qt.nokia.com/latest/qapplication.html) in Qt, ahd construct a single instance in that class early in your `main`, and have that class contain a smart or dumb pointer to your `Object`. The destructor should `delete` that object.
8,310,716
I am not experienced in handling of the memory in a C++ program, so I would like a piece of advice in that case: I want to create a `new Object` in a function in a class which is essential till the end of the program. As far as I am concerned, if I use the operator `new`, I should sometimes delete it. Taking into account that it must be initialized inside a class, when and how must I finally delete it?
2011/11/29
[ "https://Stackoverflow.com/questions/8310716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954724/" ]
I suggest the *smart pointer idiom* ``` #include <memory> struct X { void foo() { } }; std::share_ptr<X> makeX() // could also be a class member of course { return std::make_shared<X>(); } int main() { std::share_ptr<X> stayaround = makeX(); // can just be used like an ordinary pointer: stayaround->foo(); // auto-deletes <sup>1</sup> } ``` If the pointer is truly a static variable, you can substitute a `unique_ptr` (which works similarly, but passes ownership on assignment; this means that the pointer doesn't have to keep a *reference count*) ***Note*** To learn more about C++ smart pointers in general, see **[smart pointers (boost) explained](https://stackoverflow.com/questions/569775/smart-pointers-boost-explained)** ***Note*** If you don't have the TR1/C++0x support for this, you can just use Boost Smartpointer --- 1 unless you are *leaking* copies of the shared\_ptr itself; that would be some strange use of smart pointers previously unseen :)
You can use the smart pointer as suggested by Sehe or you can create a static object in the function and return a reference to it. You need not explictly delete the object, when the process terminates the object will be deleted. Like: ``` struct X {}; X& makeX() // could also be a class member of course { static X x; return x; } int main() { X& stayaround = makeX(); } ```
8,310,716
I am not experienced in handling of the memory in a C++ program, so I would like a piece of advice in that case: I want to create a `new Object` in a function in a class which is essential till the end of the program. As far as I am concerned, if I use the operator `new`, I should sometimes delete it. Taking into account that it must be initialized inside a class, when and how must I finally delete it?
2011/11/29
[ "https://Stackoverflow.com/questions/8310716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954724/" ]
You can use the smart pointer as suggested by Sehe or you can create a static object in the function and return a reference to it. You need not explictly delete the object, when the process terminates the object will be deleted. Like: ``` struct X {}; X& makeX() // could also be a class member of course { static X x; return x; } int main() { X& stayaround = makeX(); } ```
On most operating systems (in particular Linux), if you allocate an object pointer with `new Object`, and don't bother `delete`-ing because you'll need it till the program ends, no harm is really done. There is some memory leak inside your program (you can use [valgrind](http://valgrind.org/) to hunt such leaks) but the kernel will release all the memory used by a process when it has ended. A better alternative is to have a singleton class for the application data, like e.g. [QApplication](http://doc.qt.nokia.com/latest/qapplication.html) in Qt, ahd construct a single instance in that class early in your `main`, and have that class contain a smart or dumb pointer to your `Object`. The destructor should `delete` that object.
8,310,716
I am not experienced in handling of the memory in a C++ program, so I would like a piece of advice in that case: I want to create a `new Object` in a function in a class which is essential till the end of the program. As far as I am concerned, if I use the operator `new`, I should sometimes delete it. Taking into account that it must be initialized inside a class, when and how must I finally delete it?
2011/11/29
[ "https://Stackoverflow.com/questions/8310716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954724/" ]
Edit: Using some sort of smart pointer is often a good idea, but I believe it is still essential to have a solid understanding of manual memory management in C++. If you want an object in a class to persist until the end of the program, you can simply make it a member variable. From what you've said, there's nothing to suggest you need to use `new` or `delete` here, just make it an automatic variable. If you did want to use `new` and `delete` for practice, you should read up on *constructors* and *destructors* for a class (you can and will use `new` and `delete` outside of classes, but I'm trying to keep this relevant to your question). Here's one I prepared earlier: ``` class Foo { public: Foo(); // Default constructor. ~Foo(); // Destructor. private: int *member; } Foo::Foo() // Default constructor definition. { member = new int; // Creating a new int on the heap. } Foo::~Foo() // Destructor. { delete member; // Free up the memory that was allocated in the constructor. } ``` This is a simple example, but it will hopefully help you out. Note that the variable will only persist as long as the object is alive. If the object is destroyed or goes out of scope, the destructor will be called and the memory will be freed.
On most operating systems (in particular Linux), if you allocate an object pointer with `new Object`, and don't bother `delete`-ing because you'll need it till the program ends, no harm is really done. There is some memory leak inside your program (you can use [valgrind](http://valgrind.org/) to hunt such leaks) but the kernel will release all the memory used by a process when it has ended. A better alternative is to have a singleton class for the application data, like e.g. [QApplication](http://doc.qt.nokia.com/latest/qapplication.html) in Qt, ahd construct a single instance in that class early in your `main`, and have that class contain a smart or dumb pointer to your `Object`. The destructor should `delete` that object.
8,310,716
I am not experienced in handling of the memory in a C++ program, so I would like a piece of advice in that case: I want to create a `new Object` in a function in a class which is essential till the end of the program. As far as I am concerned, if I use the operator `new`, I should sometimes delete it. Taking into account that it must be initialized inside a class, when and how must I finally delete it?
2011/11/29
[ "https://Stackoverflow.com/questions/8310716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954724/" ]
Edit: Using some sort of smart pointer is often a good idea, but I believe it is still essential to have a solid understanding of manual memory management in C++. If you want an object in a class to persist until the end of the program, you can simply make it a member variable. From what you've said, there's nothing to suggest you need to use `new` or `delete` here, just make it an automatic variable. If you did want to use `new` and `delete` for practice, you should read up on *constructors* and *destructors* for a class (you can and will use `new` and `delete` outside of classes, but I'm trying to keep this relevant to your question). Here's one I prepared earlier: ``` class Foo { public: Foo(); // Default constructor. ~Foo(); // Destructor. private: int *member; } Foo::Foo() // Default constructor definition. { member = new int; // Creating a new int on the heap. } Foo::~Foo() // Destructor. { delete member; // Free up the memory that was allocated in the constructor. } ``` This is a simple example, but it will hopefully help you out. Note that the variable will only persist as long as the object is alive. If the object is destroyed or goes out of scope, the destructor will be called and the memory will be freed.
You can use the smart pointer as suggested by Sehe or you can create a static object in the function and return a reference to it. You need not explictly delete the object, when the process terminates the object will be deleted. Like: ``` struct X {}; X& makeX() // could also be a class member of course { static X x; return x; } int main() { X& stayaround = makeX(); } ```
36,480,233
I am working with discrete *Kalman Filter* on a system. > > x(k+1)=A\_k x(k)+B\_k u(k) > > > y(k)=C\_k x(k) > > > I have estimated the state from the available noised `y(k)`, which one is generated from the same system state equations with *Reference Trajectory* of the state. Then I have tested it with wrong initial state `x0` and a big initial co-variance (simulation 1). I have noticed that the *KF* works very well, after a few steps the gain `k` quickly converges to a very small value near zero. I think it is may be caused by the process noise `Q`. I have set it small because the `Q` stands for the accuracy of the model. Now I want to modify it to a steady state *Kalman Filter*. I used the steady gain from simulation-1 as constant instead of the calculation in every iteration. And then, the five equations can be simplified to one equation: > > x(k+1)^=(I-KC)A x(k)^+(I-KC)B u(k)+K y(k+1) > > > I want to test it with same initial state and co-variance matrix as the one in simulation-1. But the result is very different from reference trajectory and even the result of simulation-1. I have tested it with the co-variance matrix `p_infi`, which is solved from the *Discrete Riccati Equation*: > > k\_infi=p\_infi*C'/(C*p\_infi\*C'+R) > > > This neither works. I am wondering- 1. How should I apply steady state KF and how should I set the initial state for it? 2. Is steady state KF used for scalar system? 3. Should I use it with LQ-controller or some others?
2016/04/07
[ "https://Stackoverflow.com/questions/36480233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5737807/" ]
Let me first simplify the discussion to a filter with a fixed transition matrix, **A** rather then **A\_k** above. When the Kalman filter reaches steady-state in this case, one can extract the gains and make a fixed-gain filter that utilizes the steady-state Kalman gains. That filter is *not* a Kalman filter, it is a fixed-gain filter. It's start-up performance will generally be worse than the Kalman filter. That is the price one pays for replacing the Kalman gain computation with fixed gains. A fixed-gain filter has no covariance (**P**) and no **Q** or **R**. Given **A**, **C** and **Q**, the steady-state gains can be computed directly. Using the discrete Kalman filter model, and setting the a-posteriori covarance matrix equal to the propagated a-posteriori covariance matrix from the prior measurement cycle one has: **P = (I - KC) (A P A^T + Q)** Solving that equation for **K** results in the steady-state Kalman gains for fixed **A**, **Q** and **C**. Where is **R**? Well it has no role in the steady-state gain computation because the measurement noise has been averaged down in steady-state. Steady-state means the state estimate is as good as it can get with the amount of process noise (**Q**) we have. If **A** is time-varying, much of this discussion does not hold. There is no assurance that a Kalman filter will reach steady-state. There may be no **Pinf**. Another implicit assumption in using the steady-state gains from a Kalman filter in a fixed gain filter is that all of the measurements will remain available at the same rates. The Kalman filter is robust to measurement loss, the fixed-gain filter is not.
Steady state KF requires the initial state matches the steady state covariance. Otherwise, the KF could diverge. You can start using the steady state KF when the filter enters the steady state. The steady state Kalman filter can be used for systems with multiple dimension state.
34,989,166
I'm fetching the data from database for a particular record using email id in the hidden field. If I try to add as `input type="text"` it is not working for me, can any one check this. Here is my code. **Index.php:** ``` <?php session_start(); $username = $_SESSION['username']; if($username) { ?> <h3> Welcome <?php echo $username; ?></h3> <?php } else { echo "no"; } ?> <html> <body> <table class="table table-hover"> <form action="personalinfo.php" METHOD="POST"> <input type="hidden" value="<?php echo $username;?>" name="email"> <tr> <th><label for="first_name">Name</label></th> </tr> <?php include "personalinfo.php"; while($row = mysql_fetch_array($result)) { echo "<tr>"; <input type="text" name="first_name" value="<?php echo $row->first_name;?>" /> echo "</tr>"; } echo "</table>"; ?> </form> </body> </html> ``` **personalinfo.php :** ``` <?php $connection = mysql_connect("localhost", "root", "") or die(mysql_error()); $db = mysql_select_db("accountant", $connection); $result = mysql_query("SELECT * FROM registered where email='$username'"); ?> ``` In index.php, if I use like this in while condition 'first\_name';?> name="first\_name"/> so that I can update the record but if i remove this ``` echo "<td>" . $row['first_name'] . "</td>"; ``` and if I add like this instead of that echo ``` <?php echo $row->first_name;?> ``` it gives error as ``` Parse error: syntax error, unexpected '<' in C:\xampp\htdocs\index\index.php on line 44 ```
2016/01/25
[ "https://Stackoverflow.com/questions/34989166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5836176/" ]
You have to expliciltely cast `obj` to `MyObj1` as the compiler does not know that you assign an instance of that class to `obj`. ``` IMyInterface obj = new MyObj1(); var s = Process((MyObj1) obj); ``` The actual type of `obj` is only known at runtime. A better appraoch would be two define the method `Process` on your interface itself: ``` IMyInterface { public string Process(); } ``` Now your two classes implement this by: ``` class MyObj1 : IMyInterface { public string Process() { return "did one" ; } } ``` Thus you do not even have to pass that instance to the method.
Why not use open generics with [type constraints](https://msdn.microsoft.com/en-us/library/d5x73970.aspx)? No need for casting, no need for factory classes or anything *hacky*. ``` public string Process<T>(T obj) where T : IMyInterface { ... } ``` Call it like ``` IMyInterface obj = new MyObj1(); var s = Process(obj); ``` as intended.
52,146,053
I'm trying to use node-fetch with nodejs to make api calls to my personal api. I would like to be able to update certain values synchronously within this periodically as things update/change with my database behind the scenes. I know that async and await exist but with all my googling I still don't quite understand them or how they interact with fetch requests. This is a bit of example code I'm trying to get working but still just logs undefined ``` const fetch = require('node-fetch'); const url = 'http://example.com'; let logs; example(); console.log(logs); async function example(){ //Do things here logs = await retrieveLogs(); //Do more things here } async function retrieveLogs(){ await fetch(url) .then(res => res.json()) .then(json => {return json}) .catch(e => console.log(e)) } ```
2018/09/03
[ "https://Stackoverflow.com/questions/52146053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9674259/" ]
I think you need to return retrieveLogs function result like this: ``` async function retrieveLogs(){ return await fetch(url) .then(res => res.json()) } ```
As Ali Torki said in comment, `fetch()` is an async function and cannot be "made" sync no matter what. If you MUST fetch synchronously with HTTP (e.g. because you MUST use it in a property getter which MUSTN'T be async), then you MUST use a different HTTP client, full stop.
52,146,053
I'm trying to use node-fetch with nodejs to make api calls to my personal api. I would like to be able to update certain values synchronously within this periodically as things update/change with my database behind the scenes. I know that async and await exist but with all my googling I still don't quite understand them or how they interact with fetch requests. This is a bit of example code I'm trying to get working but still just logs undefined ``` const fetch = require('node-fetch'); const url = 'http://example.com'; let logs; example(); console.log(logs); async function example(){ //Do things here logs = await retrieveLogs(); //Do more things here } async function retrieveLogs(){ await fetch(url) .then(res => res.json()) .then(json => {return json}) .catch(e => console.log(e)) } ```
2018/09/03
[ "https://Stackoverflow.com/questions/52146053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9674259/" ]
I think you need to return retrieveLogs function result like this: ``` async function retrieveLogs(){ return await fetch(url) .then(res => res.json()) } ```
Using Immediately Invoked Async Function Expression: ``` (async () => { try { const response = await fetch('http://example.com') const json = await response.json() } catch (error) { console.log(error); } })(); ```
52,146,053
I'm trying to use node-fetch with nodejs to make api calls to my personal api. I would like to be able to update certain values synchronously within this periodically as things update/change with my database behind the scenes. I know that async and await exist but with all my googling I still don't quite understand them or how they interact with fetch requests. This is a bit of example code I'm trying to get working but still just logs undefined ``` const fetch = require('node-fetch'); const url = 'http://example.com'; let logs; example(); console.log(logs); async function example(){ //Do things here logs = await retrieveLogs(); //Do more things here } async function retrieveLogs(){ await fetch(url) .then(res => res.json()) .then(json => {return json}) .catch(e => console.log(e)) } ```
2018/09/03
[ "https://Stackoverflow.com/questions/52146053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9674259/" ]
I think you need to return retrieveLogs function result like this: ``` async function retrieveLogs(){ return await fetch(url) .then(res => res.json()) } ```
``` npm install sync-fetch ``` Synchronous wrapper around the Fetch API. Uses node-fetch under the hood, and for some input-parsing code and test cases too. <https://www.npmjs.com/package/sync-fetch>
52,146,053
I'm trying to use node-fetch with nodejs to make api calls to my personal api. I would like to be able to update certain values synchronously within this periodically as things update/change with my database behind the scenes. I know that async and await exist but with all my googling I still don't quite understand them or how they interact with fetch requests. This is a bit of example code I'm trying to get working but still just logs undefined ``` const fetch = require('node-fetch'); const url = 'http://example.com'; let logs; example(); console.log(logs); async function example(){ //Do things here logs = await retrieveLogs(); //Do more things here } async function retrieveLogs(){ await fetch(url) .then(res => res.json()) .then(json => {return json}) .catch(e => console.log(e)) } ```
2018/09/03
[ "https://Stackoverflow.com/questions/52146053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9674259/" ]
As Ali Torki said in comment, `fetch()` is an async function and cannot be "made" sync no matter what. If you MUST fetch synchronously with HTTP (e.g. because you MUST use it in a property getter which MUSTN'T be async), then you MUST use a different HTTP client, full stop.
Using Immediately Invoked Async Function Expression: ``` (async () => { try { const response = await fetch('http://example.com') const json = await response.json() } catch (error) { console.log(error); } })(); ```
52,146,053
I'm trying to use node-fetch with nodejs to make api calls to my personal api. I would like to be able to update certain values synchronously within this periodically as things update/change with my database behind the scenes. I know that async and await exist but with all my googling I still don't quite understand them or how they interact with fetch requests. This is a bit of example code I'm trying to get working but still just logs undefined ``` const fetch = require('node-fetch'); const url = 'http://example.com'; let logs; example(); console.log(logs); async function example(){ //Do things here logs = await retrieveLogs(); //Do more things here } async function retrieveLogs(){ await fetch(url) .then(res => res.json()) .then(json => {return json}) .catch(e => console.log(e)) } ```
2018/09/03
[ "https://Stackoverflow.com/questions/52146053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9674259/" ]
As Ali Torki said in comment, `fetch()` is an async function and cannot be "made" sync no matter what. If you MUST fetch synchronously with HTTP (e.g. because you MUST use it in a property getter which MUSTN'T be async), then you MUST use a different HTTP client, full stop.
``` npm install sync-fetch ``` Synchronous wrapper around the Fetch API. Uses node-fetch under the hood, and for some input-parsing code and test cases too. <https://www.npmjs.com/package/sync-fetch>
52,146,053
I'm trying to use node-fetch with nodejs to make api calls to my personal api. I would like to be able to update certain values synchronously within this periodically as things update/change with my database behind the scenes. I know that async and await exist but with all my googling I still don't quite understand them or how they interact with fetch requests. This is a bit of example code I'm trying to get working but still just logs undefined ``` const fetch = require('node-fetch'); const url = 'http://example.com'; let logs; example(); console.log(logs); async function example(){ //Do things here logs = await retrieveLogs(); //Do more things here } async function retrieveLogs(){ await fetch(url) .then(res => res.json()) .then(json => {return json}) .catch(e => console.log(e)) } ```
2018/09/03
[ "https://Stackoverflow.com/questions/52146053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9674259/" ]
``` npm install sync-fetch ``` Synchronous wrapper around the Fetch API. Uses node-fetch under the hood, and for some input-parsing code and test cases too. <https://www.npmjs.com/package/sync-fetch>
Using Immediately Invoked Async Function Expression: ``` (async () => { try { const response = await fetch('http://example.com') const json = await response.json() } catch (error) { console.log(error); } })(); ```
281,152
This container reduces the number of memory allocations on queue-type operations (push + pop) compared to std::deque. Basic performance tests indicates a performance similar to std::deque where main cost is the calculation of index ((mFront+pos)%mReserved). A [first review](https://codereview.stackexchange.com/questions/281005/simple-c-circular-queue) was done by [G.Sliepen](https://codereview.stackexchange.com/users/129343/g-sliepen). I tried to solve almost all reported issues and replaced the system-managed memory (based on std::unique\_ptr) by a user-managed memory. The big game started. Playing with soap in the prison shower! Great chances that mistakes or errors are presents in the code. I will appreciate you comments and suggestions. Here is cqueue.hpp ``` #pragma once #include <memory> #include <limits> #include <utility> #include <concepts> #include <algorithm> #include <stdexcept> namespace gto { /** * @brief Circular queue. * @details Iterators are invalidated by: * push(), push_front(), emplace(), pop(), pop_back(), reserve(), * shrink_to_fit(), reset() and clear(). * @see https://en.wikipedia.org/wiki/Circular_buffer * @see https://github.com/torrentg/cqueue * @note This class is not thread-safe. * @version 1.0.0 */ template<std::copyable T, typename Allocator = std::allocator<T>> class cqueue { public: // declarations // Aliases using value_type = T; using reference = value_type &; using const_reference = const value_type &; using pointer = T *; using const_pointer = const pointer; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using allocator_type = Allocator; using const_alloc_reference = const allocator_type &; //! cqueue iterator. class iterator { public: using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; private: cqueue *queue = nullptr; difference_type pos = 0; private: size_type cast(difference_type n) const { return (n < 0 ? queue->size() : static_cast<size_type>(n)); } difference_type size() const { return static_cast<difference_type>(queue->size()); } public: explicit iterator(cqueue *o, difference_type p = 0) : queue(o), pos(p < 0 ? -1 : (p < size() ? p : size())) {} reference operator*() { return queue->operator[](cast(pos)); } pointer operator->() { return &(queue->operator[](cast(pos))); } reference operator[](difference_type rhs) const { return (queue->operator[](cast(pos + rhs))); } bool operator==(const iterator &rhs) const { return (queue == rhs.queue && pos == rhs.pos); } bool operator!=(const iterator &rhs) const { return (queue != rhs.queue || pos != rhs.pos); } bool operator >(const iterator &rhs) const { return (queue == rhs.queue && pos > rhs.pos); } bool operator <(const iterator &rhs) const { return (queue == rhs.queue && pos < rhs.pos); } bool operator>=(const iterator &rhs) const { return (queue == rhs.queue && pos >= rhs.pos); } bool operator<=(const iterator &rhs) const { return (queue == rhs.queue && pos <= rhs.pos); } iterator& operator++() { pos = (pos + 1 < size() ? pos + 1 : size()); return *this; } iterator& operator--() { pos = (pos < 0 ? -1 : pos -1); return *this; } iterator operator++(int) { iterator tmp(queue, pos); operator++(); return tmp; } iterator operator--(int) { iterator tmp(queue, pos); operator--(); return tmp; } iterator& operator+=(difference_type rhs) { pos = (pos + rhs < size() ? pos + rhs : size()); return *this; } iterator& operator-=(difference_type rhs) { pos = (pos - rhs < 0 ? -1 : pos - rhs); return *this; } iterator operator+(difference_type rhs) const { return iterator(queue, pos + rhs); } iterator operator-(difference_type rhs) const { return iterator(queue, pos - rhs); } friend iterator operator+(difference_type lhs, const iterator &rhs) { return iterator(rhs.queue, lhs + rhs.pos); } friend iterator operator-(difference_type lhs, const iterator &rhs) { return iterator(rhs.queue, lhs - rhs.pos); } difference_type operator-(const iterator &rhs) const { return (pos - rhs.pos); } }; //! cqueue const iterator. class const_iterator { public: using iterator_category = std::random_access_iterator_tag; using value_type = const T; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; private: const cqueue *queue = nullptr; difference_type pos = 0; private: size_type cast(difference_type n) const { return (n < 0 ? queue->size() : static_cast<size_type>(n)); } difference_type size() const { return static_cast<difference_type>(queue->size()); } public: explicit const_iterator(const cqueue *o, difference_type p = 0) : queue(o), pos(p < 0 ? -1 : (p < size() ? p : size())) {} reference operator*() { return queue->operator[](cast(pos)); } pointer operator->() { return &(queue->operator[](cast(pos))); } reference operator[](difference_type rhs) const { return (queue->operator[](cast(pos + rhs))); } bool operator==(const const_iterator &rhs) const { return (queue == rhs.queue && pos == rhs.pos); } bool operator!=(const const_iterator &rhs) const { return (queue != rhs.queue || pos != rhs.pos); } bool operator >(const const_iterator &rhs) const { return (queue == rhs.queue && pos > rhs.pos); } bool operator <(const const_iterator &rhs) const { return (queue == rhs.queue && pos < rhs.pos); } bool operator>=(const const_iterator &rhs) const { return (queue == rhs.queue && pos >= rhs.pos); } bool operator<=(const const_iterator &rhs) const { return (queue == rhs.queue && pos <= rhs.pos); } const_iterator& operator++() { pos = (pos + 1 < size() ? pos + 1 : size()); return *this; } const_iterator& operator--() { pos = (pos < 0 ? -1 : pos -1); return *this; } const_iterator operator++(int) { const_iterator tmp(queue, pos); operator++(); return tmp; } const_iterator operator--(int) { const_iterator tmp(queue, pos); operator--(); return tmp; } const_iterator& operator+=(difference_type rhs) { pos = (pos + rhs < size() ? pos + rhs : size()); return *this; } const_iterator& operator-=(difference_type rhs) { pos = (pos - rhs < 0 ? -1 : pos - rhs); return *this; } const_iterator operator+(difference_type rhs) const { return const_iterator(queue, pos + rhs); } const_iterator operator-(difference_type rhs) const { return const_iterator(queue, pos - rhs); } friend const_iterator operator+(difference_type lhs, const const_iterator &rhs) { return const_iterator(rhs.queue, lhs + rhs.pos); } friend const_iterator operator-(difference_type lhs, const const_iterator &rhs) { return const_iterator(rhs.queue, lhs - rhs.pos); } difference_type operator-(const const_iterator &rhs) const { return (pos - rhs.pos); } }; private: // static members //! Capacity increase factor. static constexpr size_type GROWTH_FACTOR = 2; //! Default initial capacity (power of 2). static constexpr size_type DEFAULT_RESERVED = 8; private: // members //! Memory allocator. [[no_unique_address]] allocator_type mAllocator; //! Buffer. pointer mData = nullptr; //! Buffer size. size_type mReserved = 0; //! Maximum number of elements (always > 0). size_type mCapacity = 0; //! Index representing first entry (0 <= mFront < mReserved). size_type mFront = 0; //! Number of entries in the queue (empty = 0, full = mReserved). size_type mLength = 0; private: // methods //! Convert from pos to index (throw exception if out-of-bounds). constexpr size_type getCheckedIndex(size_type pos) const noexcept(false); //! Convert from pos to index. constexpr size_type getUncheckedIndex(size_type pos) const noexcept; //! Compute memory size to reserve. constexpr size_type getNewMemoryLength(size_type n) const noexcept; //! Resize buffer. constexpr void resizeIfRequired(size_type n); //! Resize buffer. void resize(size_type n); //! Clear and dealloc memory (preserve capacity and allocator). void reset() noexcept; public: // static methods //! Maximum capacity the container is able to hold. static constexpr size_type max_capacity() noexcept { return (std::numeric_limits<difference_type>::max()); } public: // methods //! Constructor. constexpr explicit cqueue(const_alloc_reference alloc = Allocator()) : cqueue(0, alloc) {} //! Constructor (capacity=0 means unlimited). constexpr explicit cqueue(size_type capacity, const_alloc_reference alloc = Allocator()); //! Copy constructor. constexpr cqueue(const cqueue &other); //! Copy constructor with allocator. constexpr cqueue(const cqueue &other, const_alloc_reference alloc); //! Move constructor. constexpr cqueue(cqueue &&other) noexcept { this->swap(other); } //! Move constructor. constexpr cqueue(cqueue &&other, const_alloc_reference alloc); //! Destructor. ~cqueue() noexcept { reset(); }; //! Copy assignment. constexpr cqueue & operator=(const cqueue &other); //! Move assignment. constexpr cqueue & operator=(cqueue &&other) { this->swap(other); return *this; } //! Return container allocator. [[nodiscard]] constexpr allocator_type get_allocator() const noexcept { return mAllocator; } //! Return queue capacity. [[nodiscard]] constexpr size_type capacity() const noexcept { return (mCapacity == max_capacity() ? 0 : mCapacity); } //! Return the number of items. [[nodiscard]] constexpr size_type size() const noexcept { return mLength; } //! Current reserved size (numbers of items). [[nodiscard]] constexpr size_type reserved() const noexcept { return mReserved; } //! Check if there are items in the queue. [[nodiscard]] constexpr bool empty() const noexcept { return (mLength == 0); } //! Return the first element. [[nodiscard]] constexpr const_reference front() const { return operator[](0); } //! Return the first element. [[nodiscard]] constexpr reference front() { return operator[](0); } //! Return the last element. [[nodiscard]] constexpr const_reference back() const { return operator[](mLength-1); } //! Return the last element. [[nodiscard]] constexpr reference back() { return operator[](mLength-1); } //! Insert an element at the end. constexpr void push(const T &val); //! Insert an element at the end. constexpr void push(T &&val); //! Insert an element at the front. constexpr void push_front(const T &val); //! Insert an element at the front. constexpr void push_front(T &&val); //! Construct and insert an element at the end. template <class... Args> constexpr void emplace(Args&&... args); //! Remove the front element. constexpr bool pop(); //! Remove the back element. constexpr bool pop_back(); //! Returns a reference to the element at position n. [[nodiscard]] constexpr reference operator[](size_type n) { return mData[getCheckedIndex(n)]; } //! Returns a const reference to the element at position n. [[nodiscard]] constexpr const_reference operator[](size_type n) const { return mData[getCheckedIndex(n)]; } //! Returns an iterator to the first element. [[nodiscard]] constexpr iterator begin() noexcept { return iterator(this, 0); } //! Returns an iterator to the element following the last element. [[nodiscard]] constexpr iterator end() noexcept { return iterator(this, static_cast<difference_type>(size())); } //! Returns an iterator to the first element. [[nodiscard]] constexpr const_iterator begin() const noexcept { return const_iterator(this, 0); } //! Returns an iterator to the element following the last element. [[nodiscard]] constexpr const_iterator end() const noexcept { return const_iterator(this, static_cast<difference_type>(size())); } //! Clear content. void clear() noexcept; //! Swap content. constexpr void swap (cqueue &x) noexcept; //! Ensure buffer size. constexpr void reserve(size_type n); //! Shrink reserved memory to current size. constexpr void shrink_to_fit(); }; } // namespace gto /** * @param[in] capacity Container capacity. * @param[in] alloc Allocator to use. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(size_type capacity, const_alloc_reference alloc) : mAllocator(alloc), mData{nullptr}, mReserved{0}, mCapacity{max_capacity()}, mFront{0}, mLength{0} { if (capacity > max_capacity()) { throw std::length_error("cqueue max capacity exceeded"); } else { mCapacity = (capacity == 0 ? max_capacity() : capacity); } } /** * @param[in] other Queue to copy. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(const cqueue &other) : mAllocator{std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator())}, mData{nullptr}, mReserved{0}, mCapacity{other.mCapacity}, mFront{0}, mLength{0} { resizeIfRequired(other.mLength); for (size_type i = 0; i < other.size(); ++i) { push(other[i]); } } /** * @param[in] other Queue to copy. * @param[in] alloc Allocator to use. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(const cqueue &other, const_alloc_reference alloc) : mAllocator{alloc}, mData{nullptr}, mReserved{0}, mCapacity{other.mCapacity}, mFront{0}, mLength{0} { resizeIfRequired(other.mLength); for (size_type i = 0; i < other.size(); ++i) { push(other[i]); } } /** * @param[in] other Queue to copy. * @param[in] alloc Allocator to use */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator>::cqueue(cqueue &&other, const_alloc_reference alloc) : mData{nullptr}, mReserved{0}, mCapacity{max_capacity()}, mFront{0}, mLength{0} { if (alloc == other.mAllocator) { this->swap(other); } else { mAllocator = alloc; mCapacity = other.mCapacity; resizeIfRequired(other.mLength); for (size_type i = 0; i < other.size(); ++i) { push(std::move(other[i])); } other.reset(); other.mCapacity = 0; } } /** * @param[in] other Queue to copy. */ template<std::copyable T, typename Allocator> constexpr gto::cqueue<T, Allocator> & gto::cqueue<T, Allocator>::operator=(const cqueue &other) { if (this != &other) { cqueue tmp(other); this->swap(tmp); } return *this; } /** * @param[in] num Element position. * @return Index in buffer. */ template<std::copyable T, typename Allocator> constexpr typename gto::cqueue<T, Allocator>::size_type gto::cqueue<T, Allocator>::getUncheckedIndex(size_type pos) const noexcept { return ((mFront + pos) % (mReserved == 0 ? 1 : mReserved)); } /** * @param[in] num Element position. * @return Index in buffer. * @exception std::out_of_range Invalid position. */ template<std::copyable T, typename Allocator> constexpr typename gto::cqueue<T, Allocator>::size_type gto::cqueue<T, Allocator>::getCheckedIndex(size_type pos) const noexcept(false) { if (pos >= mLength) { throw std::out_of_range("cqueue access out-of-range"); } else { return getUncheckedIndex(pos); } } /** * @details Remove all elements. */ template<std::copyable T, typename Allocator> void gto::cqueue<T, Allocator>::clear() noexcept { for (size_type i = 0; i < mLength; ++i) { size_type index = getUncheckedIndex(i); std::allocator_traits<allocator_type>::destroy(mAllocator, mData + index); } mFront = 0; mLength = 0; } /** * @details Remove all elements and frees memory. */ template<std::copyable T, typename Allocator> void gto::cqueue<T, Allocator>::reset() noexcept { clear(); std::allocator_traits<allocator_type>::deallocate(mAllocator, mData, mReserved); mData = nullptr; mReserved = 0; } /** * @details Swap content with another same-type cqueue. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::swap(cqueue &other) noexcept { if (this == &other) { return; } if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_swap::value) { std::swap(mAllocator, other.mAllocator); } std::swap(mData, other.mData); std::swap(mFront, other.mFront); std::swap(mLength, other.mLength); std::swap(mReserved, other.mReserved); std::swap(mCapacity, other.mCapacity); } /** * @brief Compute the new buffer size. * @param[in] n New queue size. */ template<std::copyable T, typename Allocator> constexpr typename gto::cqueue<T, Allocator>::size_type gto::cqueue<T, Allocator>::getNewMemoryLength(size_type n) const noexcept { size_type ret = (mReserved == 0 ? std::min(mCapacity, DEFAULT_RESERVED) : mReserved); while (ret < n) { ret *= GROWTH_FACTOR; } return std::min(ret, mCapacity); } /** * @param[in] n Expected future queue size. * @exception std::length_error Capacity exceeded. * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::resizeIfRequired(size_type n) { if (n < mReserved) { [[likely]] return; } else if (n > mCapacity) { [[unlikely]] throw std::length_error("cqueue capacity exceeded"); } else { size_type len = getNewMemoryLength(n); resize(len); } } /** * @param[in] n Expected future queue size. * @exception std::length_error Capacity exceeded. * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::reserve(size_type n) { if (n < mReserved) { return; } else if (n > mCapacity) { throw std::length_error("cqueue capacity exceeded"); } else { resize(n); } } /** * @details Memory is not shrink if current length below DEFAULT_RESERVED. * @exception std::length_error Capacity exceeded. * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::shrink_to_fit() { if (mLength == 0 || mLength == mReserved || mLength <= DEFAULT_RESERVED) { return; } else { resize(mLength); } } /** * @param[in] n New reserved size. * @details Provides strong exception guarantee. * @see https://en.cppreference.com/w/cpp/language/exceptions#Exception_safety * @exception ... Error throwed by move contructors. */ template<std::copyable T, typename Allocator> void gto::cqueue<T, Allocator>::resize(size_type len) { pointer tmp = std::allocator_traits<allocator_type>::allocate(mAllocator, len); if constexpr (std::is_nothrow_move_constructible<T>::value) { // move elements from mData to tmp for (size_type i = 0; i < mLength; ++i) { size_type index = getUncheckedIndex(i); std::allocator_traits<allocator_type>::construct(mAllocator, tmp + i, std::move(mData[index])); } } else { // copy elements from mData to tmp size_type i = 0; try { for (i = 0; i < mLength; ++i) { size_type index = getUncheckedIndex(i); std::allocator_traits<allocator_type>::construct(mAllocator, tmp + i, mData[index]); } } catch (...) { for (size_type j = 0; j < i; ++j) { std::allocator_traits<allocator_type>::destroy(mAllocator, tmp + j); } std::allocator_traits<allocator_type>::deallocate(mAllocator, tmp, len); throw; } } // destroy mData elements for (size_type j = 0; j < mLength; ++j) { size_type index = getUncheckedIndex(j); std::allocator_traits<allocator_type>::destroy(mAllocator, mData + index); } // deallocate mData std::allocator_traits<allocator_type>::deallocate(mAllocator, mData, mReserved); // assign new content mData = tmp; mReserved = len; mFront = 0; } /** * @param[in] val Value to add. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push(const T &val) { resizeIfRequired(mLength + 1); size_type index = getUncheckedIndex(mLength); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, val); ++mLength; } /** * @param[in] val Value to add. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push(T &&val) { resizeIfRequired(mLength + 1); size_type index = getUncheckedIndex(mLength); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, std::move(val)); ++mLength; } /** * @param[in] val Value to add. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push_front(const T &val) { resizeIfRequired(mLength + 1); size_type index = (mLength == 0 ? 0 : (mFront == 0 ? mReserved : mFront) - 1); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, val); mFront = index; ++mLength; } /** * @param[in] val Value to add. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> constexpr void gto::cqueue<T, Allocator>::push_front(T &&val) { resizeIfRequired(mLength + 1); size_type index = (mLength == 0 ? 0 : (mFront == 0 ? mReserved : mFront) - 1); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, std::move(val)); mFront = index; ++mLength; } /** * @param[in] args Arguments of the new item. * @exception std::length_error Number of values exceed queue capacity. */ template<std::copyable T, typename Allocator> template <class... Args> constexpr void gto::cqueue<T, Allocator>::emplace(Args&&... args) { resizeIfRequired(mLength + 1); size_type index = getUncheckedIndex(mLength); std::allocator_traits<allocator_type>::construct(mAllocator, mData + index, std::forward<Args>(args)...); ++mLength; } /** * @return true = an element was erased, false = no elements in the queue. */ template<std::copyable T, typename Allocator> constexpr bool gto::cqueue<T, Allocator>::pop() { if (mLength == 0) { return false; } std::allocator_traits<allocator_type>::destroy(mAllocator, mData + mFront); mFront = getUncheckedIndex(1); --mLength; return true; } /** * @return true = an element was erased, false = no elements in the queue. */ template<std::copyable T, typename Allocator> constexpr bool gto::cqueue<T, Allocator>::pop_back() { if (mLength == 0) { return false; } size_type index = getUncheckedIndex(mLength - 1); std::allocator_traits<allocator_type>::destroy(mAllocator, mData + index); --mLength; return true; } ```
2022/11/12
[ "https://codereview.stackexchange.com/questions/281152", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/266613/" ]
`findByPrice` in its current implementation uses double lookups; reduce these to single lookups knowing that `get` returns `null` on a missing key. `findBestAsk` and `findBestBid` should be `public`, not `private`. The printing methods should not exist in that class. Even if they did, they should be called "format" and not "print" because they don't print. `marketBuy` and `marketSell` are almost the same function. Make those two thin front-ends to a worker function. The bulk of your code should not exist in `Main`. Write a parser class. There are many ways to further abstract this; the one I propose is somewhat modest in its abstraction and frames the new class as a combined parser, mutation dispatcher and iterator over output strings. Do you really need a `BufferedWriter`? The bare `FileWriter` [does have buffering](https://stackoverflow.com/questions/17899572/is-filewriter-buffered), and you should only opt to add a secondary write wrapper if you prove that your situation really needs it. Even funnier: you `.flush()`, negating the benefit of any buffering; don't do that. `line.split(",")` can be replaced with a `Scanner`. Make better use of `switch` instead of `if`/`else`. Do not apply a default `else` to the `sell` case; you should check for this explicitly and throw if the parsing fails to interpret the string. Don't accept a boxed `Integer` type for `marketBuy` etc. parameters; accept `int` which is guaranteed non-null. Your market trade loop can be simplified by subtracting from the size first and comparing to zero. The program output is the same but you are going to want to test thoroughly to make sure. Suggested --------- **Main.java** ``` import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) throws IOException { LimitBook book = new LimitBook(); try (var writer = new FileWriter("output.csv", StandardCharsets.UTF_8); var parser = new ActionParser("input.csv", book)) { for (String output: parser) writer.write(output); } } } ``` **ActionParser.java** ``` import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.Map; import java.util.Scanner; public class ActionParser implements AutoCloseable, Iterable<String> { private final Scanner scanner; private final LimitBook book; public ActionParser(String filename, LimitBook book) throws IOException { File file = new File(filename); this.book = book; scanner = new Scanner(file, StandardCharsets.UTF_8); scanner.useDelimiter("[,\r\n]"); } @Override public void close() { scanner.close(); } @Override public Iterator<String> iterator() { return new ActionIterator(); } private class ActionIterator implements Iterator<String> { private static String formatPair(Map.Entry<Integer, Integer> pair) { return "%d,%d%n".formatted(pair.getKey(), pair.getValue()); } @Override public boolean hasNext() { return scanner.hasNext(); } private void update() { int price = scanner.nextInt(); int size = scanner.nextInt(); String type = scanner.next(); switch (type) { case "bid" -> book.addToBidTree(price, size); case "ask" -> book.addToAskTree(price, size); default -> throw new IllegalArgumentException(); } } private void order() { String type = scanner.next(); int size = scanner.nextInt(); switch (type) { case "buy" -> book.marketBuy(size); case "sell" -> book.marketSell(size); default -> throw new IllegalArgumentException(); } } private String query() { String type = scanner.next(); return switch (type) { case "best_bid" -> formatPair(book.findBestBid()); case "best_ask" -> formatPair(book.findBestAsk()); case "size" -> { int price = scanner.nextInt(); yield "%d%n".formatted(book.findByPrice(price)); } default -> throw new IllegalArgumentException(); }; } @Override public String next() { String queryType = scanner.next(); String output = switch (queryType) { case "u" -> { update(); yield ""; } case "o" -> { order(); yield ""; } case "q" -> query(); default -> throw new IllegalArgumentException(); }; if (scanner.hasNext()) scanner.nextLine(); return output; } } } ``` **LimitBook.java** ``` import java.util.Map; import java.util.TreeMap; import java.util.function.Function; public class LimitBook { private final TreeMap<Integer, Integer> bidTree = new TreeMap<>(), askTree = new TreeMap<>(); public void addToBidTree(Integer price, Integer size) { if (size == 0) bidTree.remove(price); else bidTree.put(price, size); } public void addToAskTree(Integer price, Integer size) { if (size == 0) askTree.remove(price); else askTree.put(price, size); } public Integer findByPrice(Integer price) { Integer value = bidTree.get(price); if (value != null) return bidTree.get(price); value = askTree.get(price); if (value != null) return value; return 0; } public Map.Entry<Integer, Integer> findBestAsk() { return askTree.firstEntry(); } public Map.Entry<Integer, Integer> findBestBid() { return bidTree.lastEntry(); } public void marketBuy(int size) { marketTrade(size, askTree, TreeMap::firstEntry); } public void marketSell(int size) { marketTrade(size, bidTree, TreeMap::lastEntry); } private void marketTrade( int size, TreeMap<Integer, Integer> tree, Function<TreeMap<Integer, Integer>, Map.Entry<Integer, Integer>> getBound ) { while (size > 0) { Map.Entry<Integer, Integer> best = getBound.apply(tree); size -= best.getValue(); if (size < 0) { tree.put(best.getKey(), -size); break; } tree.remove(best.getKey()); } } } ```
> > > ``` > private final TreeMap<Integer, Integer> bidTree = new TreeMap<>(); > private final TreeMap<Integer,Integer> askTree = new TreeMap<>(); > > ``` > > In general, it is recommended that you code to the interface, not the implementation. `TreeMap` is an implementation. You probably want to code to `SortedMap`. ``` private final SortedMap<Integer, Integer> bidTree = new TreeMap<>(); private final SortedMap<Integer, Integer> askTree = new TreeMap<>(); ``` Incidentally, I would not describe this as a binary search. You binary search an array. This is a [tree](https://en.wikipedia.org/wiki/Binary_search_algorithm#Trees) structure. You could call it a Binary Search Tree (BST) if you want, but it doesn't do a binary search. Most of the cleverness of a BST is in maintaining it. Whereas a binary search array is simply a sorted array. A binary search is just a method to search such a sorted array. One wouldn't typically make a market work like this. Instead of looking for the closest match, a typical market will produce either the lowest price (for a purchase) or the highest price (for a sale). For those, the best data structure would be a `PriorityQueue`. The heap used to implement a `PriorityQueue` will have lower overhead than a tree. But you can still answer the essential question. You cannot answer questions about a particular price, but you can still answer range questions by getting all of the results in sorted order and filtering out the ones that you don't want. I.e. I don't think that `findByPrice` should be a requirement for a market. And if it isn't, a `PriorityQueue` is a better match than a `TreeMap`.
18,213,074
I have just installed the NodeJS plugin on Jenkins 1.526 <https://wiki.jenkins-ci.org/display/JENKINS/NodeJS+Plugin> but on the master configuration the NodeJS auto-installer does not show up, is this plugin outdated?
2013/08/13
[ "https://Stackoverflow.com/questions/18213074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363603/" ]
works for me, but i had to restart the server for the option to appear I see the option here: /jenkins/configure my steps: a) install this as normal ``` https://wiki.jenkins-ci.org/display/JENKINS/NodeJS+Plugin ``` b) then you go to the configure page ``` /jenkins/configure ``` c) NodeJS option should be under maven/git and ant installation options d) Create NodeJS installiation NodeJS- > NodeJS installations -> Add NodeJS -> Name = "NodeJS 0.11.10", tick "Install automatically", select "Install from nodejs.org", add "grunt-cli" to globally installed packages e) Create a job and nodejs shell should be available as a build task "Execute NodeJS script" eg do this for a simple hello world example, with echo hello world onto jenkins job output ``` var sys = require('sys'); sys.puts('NodeJS Test'); sys.puts('***************'); sys.puts('helloworld'); ```
Disable on JENKINS\_HOME/configureSecurity "Cross site request forgery" attack check
17,784
I was driving to work this morning & my engine oil warning light appeared on my dash. I assumed it needed a top up. When Parking up at work I noticed that oily black water was pouring out under neath the car I opened the bonnet & it appears to be overflowing out of a yellow cap located near the coolant chamber, can someone please help as to why this is happening. The car doesn't appear any different when driving sounds & drives as usual? Thanks
2015/06/18
[ "https://mechanics.stackexchange.com/questions/17784", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/10915/" ]
You could be really lucky and it could be that the rubber seal within the cap has deteriorated and is no longer holding the pressure in the expansion tank. \*\* CAUTION \*\* - Do NOT remove this cap whilst the car is warm, you risk scalding from both super heated water and escaping steam. Once the car has cooled, remove this cap. If it appears to be loose then it may just need refitted tightly. If it was tight but the inside of the cap looks like it's deteriorated or checked, order a replacement. Now the bad news; typically this behavior is caused by a failed head gasket where cylinder pressure is escaping into the coolant system. I suspect it is water / coolant you are seeing under the car and it may be black because the route its taken to get to the ground has seen it wash across various grimy, oily bits under the bonnet. Your best bet is to get a compression test done. A garage won't change very much for this and it will tell you for certain if any cylinder pressure is escaping. If it is you have three realistic choices; rebuild the engine, replace the engine or change your car. There are numerous products online which claim you can add them to the coolant and they solve the problem, I have yet to find any which work.
An 'end of its life' head gasket might cause the problem. But before that you be sure about the liquid- is it oil or water or whatever.
15,656,644
I have a PEM Key and I want to get a KeyPair with it and bouncycastle. I found this code which seems good but I have a cast exception. ``` function loadKey() { File privateKeyFile = new File(keyPath); PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile)); PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray()); JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); Object object = pemParser.readObject(); KeyPair kp; if (object instanceof PEMEncryptedKeyPair) { Logger.info("Encrypted key - we will use provided password"); kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv)); } else { Logger.info("Unencrypted key - no password needed"); kp = converter.getKeyPair((PEMKeyPair) object); } return kp; } ``` And it returns me : Unencrypted key - no password needed org.bouncycastle.asn1.x509.SubjectPublicKeyInfo cannot be cast to org.bouncycastle.openssl.PEMKeyPair I tried several methods but i didn't succeed. Thanks to help me :)
2013/03/27
[ "https://Stackoverflow.com/questions/15656644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2119056/" ]
If you have a private key that has passphrase you might get this exception. Try removing the passphrase: ``` openssl rsa -in /path/to/originalkeywithpass.key -out /path/to/newkeywithnopass.key ```
You can use below code ``` PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject(); KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair); pp.close(); ``` For example: ``` public PrivateKey getKeyFromClassPath(String filename) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream stream = loader.getResourceAsStream("certificates/" + filename); if (stream == null) { throw new CertificateException("Could not read private key from classpath:" + "certificates/" + filename); } BufferedReader br = new BufferedReader(new InputStreamReader(stream)); try { Security.addProvider(new BouncyCastleProvider()); PEMParser pp = new PEMParser(br); PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject(); KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair); pp.close(); return kp.getPrivate(); } catch (IOException ex) { throw new CertificateException("Could not read private key from classpath", ex); } } ```
42,116,036
I have the following piece of code: ``` char *str; gets(str); ``` Now it works in turbo c but fails to in devc. I have to add the following in order to make it work in devC++. ``` char *str = malloc(5); ``` Can anyone explain, why is it so? Also, which one is authentic and a more correct form of coding.
2017/02/08
[ "https://Stackoverflow.com/questions/42116036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6541196/" ]
Actually, Your code run very vast, it is about less than a second to set value from 0% to 100% ! But `ProgressBar` has two styles for displaying the current status (`Classic` and `Continues`). In `Continues` mode if the progress value went to 100% from 0% the control will show an animation, which is not display the real and accurate progress. You can set a delay via `Thread.Sleep()` and show your label immediately after the for loop to find out to what i happening ! The Below code will work: ``` private void button1_Click(object sender, EventArgs e) { int i = 0; progressBar1.Minimum = 0; progressBar1.Maximum = 5000; for (i = 0; i <= 5000; i++) { Thread.Sleep(1); progressBar1.Value = i; } label1.Visible = true; } ```
This is an animation problem. A "hack" around it is to actually decrease the progress value by 1: ``` progressBar1.Minimum = 0; progressBar1.Maximum = 5000; for (int i = 0; i < progressBar1.Maximum; i++) { progressBar1.Value = i; progressBar1.Value = Math.Max(i - 1, progressBar1.Minimum); } label1.Visible = true; ```
42,116,036
I have the following piece of code: ``` char *str; gets(str); ``` Now it works in turbo c but fails to in devc. I have to add the following in order to make it work in devC++. ``` char *str = malloc(5); ``` Can anyone explain, why is it so? Also, which one is authentic and a more correct form of coding.
2017/02/08
[ "https://Stackoverflow.com/questions/42116036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6541196/" ]
Actually, Your code run very vast, it is about less than a second to set value from 0% to 100% ! But `ProgressBar` has two styles for displaying the current status (`Classic` and `Continues`). In `Continues` mode if the progress value went to 100% from 0% the control will show an animation, which is not display the real and accurate progress. You can set a delay via `Thread.Sleep()` and show your label immediately after the for loop to find out to what i happening ! The Below code will work: ``` private void button1_Click(object sender, EventArgs e) { int i = 0; progressBar1.Minimum = 0; progressBar1.Maximum = 5000; for (i = 0; i <= 5000; i++) { Thread.Sleep(1); progressBar1.Value = i; } label1.Visible = true; } ```
use `progressBar1.Refresh`: ``` public partial class dload : Form { public dload() { InitializeComponent(); } private void dload_Load(object sender, EventArgs e) { label1.Visible = false; } private void button1_Click(object sender, EventArgs e) { int i = 0; progressBar1.Minimum = 0; progressBar1.Maximum = 5000; for (i = 0; i <= 5000; i++) { progressBar1.Value = i; progressBar1.Refresh(); if (i == 5000) { label1.Visible = true; } } } ```
56,412,036
I'm trying to install flutter on ubuntu 18.04. After downloading the flutter package from [link](https://flutter.dev/docs/get-started/install/linux), I set the PATH variables, after that whenever I try to execute `flutter` on terminal it was giving an error `command not found`. Even I try to execute flutter command inside `flutter/bin` the result remains the same! I tried to restart and check then also result remains the same. This is how my **.bash\_profile** looks like ```sh rajath@rajath-Inspiron:~/Downloads/flutter/bin$ cat ~/.bash_profile export JAVA_HOME=/usr/lib/jvm/default-java export ANDROID_HOME=/opt/Android export PATH=$PATH:$ANDROID_HOME/tools export PATH=$PATH:$ANDROID_HOME/platform-tools export PATH=/Downloads/flutter/bin:$PATH ``` **Error log:** ```sh rajath@rajath-Inspiron:~/Downloads/flutter/bin$ flutter doctor flutter: command not found rajath@rajath-Inspiron:~/Downloads/flutter/bin$ flutter flutter: command not found rajath@rajath-Inspiron:~/Downloads/flutter/bin$ ``` *Any kind of help will much much appreciated!!!*
2019/06/02
[ "https://Stackoverflow.com/questions/56412036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6532133/" ]
You can also add `export PATH=$PATH:~/Downloads/flutter/bin` to your `~/.bashrc`. That will add the flutter path to your path variable everytime you start a new bash. And maybe you should install flutter anywhere near `/usr/`
As worldpotato said, You must add to your .bashrc file (or .bash\_profile) You can run the command `echo 'export PATH="$PATH:~/Downloads/flutter/bin"' >> ~/.bashrc` and `echo 'export PATH="$PATH:~/Downloads/flutter/bin"' >> ~/.bash_profile`
1,472,514
Does anyone know of any formula for converting a light frequency to an RGB value?
2009/09/24
[ "https://Stackoverflow.com/questions/1472514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850/" ]
For lazy guys (like me), here is an implementation in java of the code found in @user151323 's answer (that is, just a simple translation from pascal code found in [Spectra Lab Report](http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm)): ```java static private final double Gamma = 0.80; static private final double IntensityMax = 255; /** * Taken from Earl F. Glynn's web page: * <a href="http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm">Spectra Lab Report</a> */ public static int[] waveLengthToRGB(double Wavelength) { double factor; double Red, Green, Blue; if((Wavelength >= 380) && (Wavelength < 440)) { Red = -(Wavelength - 440) / (440 - 380); Green = 0.0; Blue = 1.0; } else if((Wavelength >= 440) && (Wavelength < 490)) { Red = 0.0; Green = (Wavelength - 440) / (490 - 440); Blue = 1.0; } else if((Wavelength >= 490) && (Wavelength < 510)) { Red = 0.0; Green = 1.0; Blue = -(Wavelength - 510) / (510 - 490); } else if((Wavelength >= 510) && (Wavelength < 580)) { Red = (Wavelength - 510) / (580 - 510); Green = 1.0; Blue = 0.0; } else if((Wavelength >= 580) && (Wavelength < 645)) { Red = 1.0; Green = -(Wavelength - 645) / (645 - 580); Blue = 0.0; } else if((Wavelength >= 645) && (Wavelength < 781)) { Red = 1.0; Green = 0.0; Blue = 0.0; } else { Red = 0.0; Green = 0.0; Blue = 0.0; } // Let the intensity fall off near the vision limits if((Wavelength >= 380) && (Wavelength < 420)) { factor = 0.3 + 0.7 * (Wavelength - 380) / (420 - 380); } else if((Wavelength >= 420) && (Wavelength < 701)) { factor = 1.0; } else if((Wavelength >= 701) && (Wavelength < 781)) { factor = 0.3 + 0.7 * (780 - Wavelength) / (780 - 700); } else { factor = 0.0; } int[] rgb = new int[3]; // Don't want 0^x = 1 for x <> 0 rgb[0] = Red == 0.0 ? 0 : (int)Math.round(IntensityMax * Math.pow(Red * factor, Gamma)); rgb[1] = Green == 0.0 ? 0 : (int)Math.round(IntensityMax * Math.pow(Green * factor, Gamma)); rgb[2] = Blue == 0.0 ? 0 : (int)Math.round(IntensityMax * Math.pow(Blue * factor, Gamma)); return rgb; } ```
I did a linear fit of known hue values and frequencies (dropping out red and violet because they extend so far in frequency values that they skew things a bit) and I got a rough conversion equation. It goes like frequency (in THz)=474+(3/4)(Hue Angle (in degrees)) I've tried to look around and see if anyone has come up with this equation, but I haven't found anything as of May 2010.
1,472,514
Does anyone know of any formula for converting a light frequency to an RGB value?
2009/09/24
[ "https://Stackoverflow.com/questions/1472514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850/" ]
Here's a detailed explanation of the entire conversion process: <http://www.fourmilab.ch/documents/specrend/>. Source code included!
Although this is an old question and already gets a handful good answers, when I tried to implement such conversion functionality in my application I was not satisfied with the algorithms already listed here and did my own research, which gave me some good result. So I'm going to post a new answer. After some researchs I came across this paper, [Simple Analytic Approximations to the CIE XYZ Color Matching Functions](http://jcgt.org/published/0002/02/01/), and tried to adopt the introduced multi-lobe piecewise Gaussian fit algorithm in my application. The paper only described the functions to convert a wavelength to the corresponding [XYZ values](https://en.wikipedia.org/wiki/CIE_1931_color_space), so I implemented a function to convert XYZ to RGB in the sRGB color space and combined them. The result is fantastic and worth sharing: ```java /** * Convert a wavelength in the visible light spectrum to a RGB color value that is suitable to be displayed on a * monitor * * @param wavelength wavelength in nm * @return RGB color encoded in int. each color is represented with 8 bits and has a layout of * 00000000RRRRRRRRGGGGGGGGBBBBBBBB where MSB is at the leftmost */ public static int wavelengthToRGB(double wavelength){ double[] xyz = cie1931WavelengthToXYZFit(wavelength); double[] rgb = srgbXYZ2RGB(xyz); int c = 0; c |= (((int) (rgb[0] * 0xFF)) & 0xFF) << 16; c |= (((int) (rgb[1] * 0xFF)) & 0xFF) << 8; c |= (((int) (rgb[2] * 0xFF)) & 0xFF) << 0; return c; } /** * Convert XYZ to RGB in the sRGB color space * <p> * The conversion matrix and color component transfer function is taken from http://www.color.org/srgb.pdf, which * follows the International Electrotechnical Commission standard IEC 61966-2-1 "Multimedia systems and equipment - * Colour measurement and management - Part 2-1: Colour management - Default RGB colour space - sRGB" * * @param xyz XYZ values in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] * @return RGB values in a double array, in the order of R, G, B. each value in the range of [0.0, 1.0] */ public static double[] srgbXYZ2RGB(double[] xyz) { double x = xyz[0]; double y = xyz[1]; double z = xyz[2]; double rl = 3.2406255 * x + -1.537208 * y + -0.4986286 * z; double gl = -0.9689307 * x + 1.8757561 * y + 0.0415175 * z; double bl = 0.0557101 * x + -0.2040211 * y + 1.0569959 * z; return new double[] { srgbXYZ2RGBPostprocess(rl), srgbXYZ2RGBPostprocess(gl), srgbXYZ2RGBPostprocess(bl) }; } /** * helper function for {@link #srgbXYZ2RGB(double[])} */ private static double srgbXYZ2RGBPostprocess(double c) { // clip if c is out of range c = c > 1 ? 1 : (c < 0 ? 0 : c); // apply the color component transfer function c = c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1. / 2.4) - 0.055; return c; } /** * A multi-lobe, piecewise Gaussian fit of CIE 1931 XYZ Color Matching Functions by Wyman el al. from Nvidia. The * code here is adopted from the Listing 1 of the paper authored by Wyman et al. * <p> * Reference: Chris Wyman, Peter-Pike Sloan, and Peter Shirley, Simple Analytic Approximations to the CIE XYZ Color * Matching Functions, Journal of Computer Graphics Techniques (JCGT), vol. 2, no. 2, 1-11, 2013. * * @param wavelength wavelength in nm * @return XYZ in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] */ public static double[] cie1931WavelengthToXYZFit(double wavelength) { double wave = wavelength; double x; { double t1 = (wave - 442.0) * ((wave < 442.0) ? 0.0624 : 0.0374); double t2 = (wave - 599.8) * ((wave < 599.8) ? 0.0264 : 0.0323); double t3 = (wave - 501.1) * ((wave < 501.1) ? 0.0490 : 0.0382); x = 0.362 * Math.exp(-0.5 * t1 * t1) + 1.056 * Math.exp(-0.5 * t2 * t2) - 0.065 * Math.exp(-0.5 * t3 * t3); } double y; { double t1 = (wave - 568.8) * ((wave < 568.8) ? 0.0213 : 0.0247); double t2 = (wave - 530.9) * ((wave < 530.9) ? 0.0613 : 0.0322); y = 0.821 * Math.exp(-0.5 * t1 * t1) + 0.286 * Math.exp(-0.5 * t2 * t2); } double z; { double t1 = (wave - 437.0) * ((wave < 437.0) ? 0.0845 : 0.0278); double t2 = (wave - 459.0) * ((wave < 459.0) ? 0.0385 : 0.0725); z = 1.217 * Math.exp(-0.5 * t1 * t1) + 0.681 * Math.exp(-0.5 * t2 * t2); } return new double[] { x, y, z }; } ``` my code is written in Java 8, but it shouldn't be hard to port it to lower versions of Java and other languages.
1,472,514
Does anyone know of any formula for converting a light frequency to an RGB value?
2009/09/24
[ "https://Stackoverflow.com/questions/1472514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850/" ]
Although this is an old question and already gets a handful good answers, when I tried to implement such conversion functionality in my application I was not satisfied with the algorithms already listed here and did my own research, which gave me some good result. So I'm going to post a new answer. After some researchs I came across this paper, [Simple Analytic Approximations to the CIE XYZ Color Matching Functions](http://jcgt.org/published/0002/02/01/), and tried to adopt the introduced multi-lobe piecewise Gaussian fit algorithm in my application. The paper only described the functions to convert a wavelength to the corresponding [XYZ values](https://en.wikipedia.org/wiki/CIE_1931_color_space), so I implemented a function to convert XYZ to RGB in the sRGB color space and combined them. The result is fantastic and worth sharing: ```java /** * Convert a wavelength in the visible light spectrum to a RGB color value that is suitable to be displayed on a * monitor * * @param wavelength wavelength in nm * @return RGB color encoded in int. each color is represented with 8 bits and has a layout of * 00000000RRRRRRRRGGGGGGGGBBBBBBBB where MSB is at the leftmost */ public static int wavelengthToRGB(double wavelength){ double[] xyz = cie1931WavelengthToXYZFit(wavelength); double[] rgb = srgbXYZ2RGB(xyz); int c = 0; c |= (((int) (rgb[0] * 0xFF)) & 0xFF) << 16; c |= (((int) (rgb[1] * 0xFF)) & 0xFF) << 8; c |= (((int) (rgb[2] * 0xFF)) & 0xFF) << 0; return c; } /** * Convert XYZ to RGB in the sRGB color space * <p> * The conversion matrix and color component transfer function is taken from http://www.color.org/srgb.pdf, which * follows the International Electrotechnical Commission standard IEC 61966-2-1 "Multimedia systems and equipment - * Colour measurement and management - Part 2-1: Colour management - Default RGB colour space - sRGB" * * @param xyz XYZ values in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] * @return RGB values in a double array, in the order of R, G, B. each value in the range of [0.0, 1.0] */ public static double[] srgbXYZ2RGB(double[] xyz) { double x = xyz[0]; double y = xyz[1]; double z = xyz[2]; double rl = 3.2406255 * x + -1.537208 * y + -0.4986286 * z; double gl = -0.9689307 * x + 1.8757561 * y + 0.0415175 * z; double bl = 0.0557101 * x + -0.2040211 * y + 1.0569959 * z; return new double[] { srgbXYZ2RGBPostprocess(rl), srgbXYZ2RGBPostprocess(gl), srgbXYZ2RGBPostprocess(bl) }; } /** * helper function for {@link #srgbXYZ2RGB(double[])} */ private static double srgbXYZ2RGBPostprocess(double c) { // clip if c is out of range c = c > 1 ? 1 : (c < 0 ? 0 : c); // apply the color component transfer function c = c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1. / 2.4) - 0.055; return c; } /** * A multi-lobe, piecewise Gaussian fit of CIE 1931 XYZ Color Matching Functions by Wyman el al. from Nvidia. The * code here is adopted from the Listing 1 of the paper authored by Wyman et al. * <p> * Reference: Chris Wyman, Peter-Pike Sloan, and Peter Shirley, Simple Analytic Approximations to the CIE XYZ Color * Matching Functions, Journal of Computer Graphics Techniques (JCGT), vol. 2, no. 2, 1-11, 2013. * * @param wavelength wavelength in nm * @return XYZ in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] */ public static double[] cie1931WavelengthToXYZFit(double wavelength) { double wave = wavelength; double x; { double t1 = (wave - 442.0) * ((wave < 442.0) ? 0.0624 : 0.0374); double t2 = (wave - 599.8) * ((wave < 599.8) ? 0.0264 : 0.0323); double t3 = (wave - 501.1) * ((wave < 501.1) ? 0.0490 : 0.0382); x = 0.362 * Math.exp(-0.5 * t1 * t1) + 1.056 * Math.exp(-0.5 * t2 * t2) - 0.065 * Math.exp(-0.5 * t3 * t3); } double y; { double t1 = (wave - 568.8) * ((wave < 568.8) ? 0.0213 : 0.0247); double t2 = (wave - 530.9) * ((wave < 530.9) ? 0.0613 : 0.0322); y = 0.821 * Math.exp(-0.5 * t1 * t1) + 0.286 * Math.exp(-0.5 * t2 * t2); } double z; { double t1 = (wave - 437.0) * ((wave < 437.0) ? 0.0845 : 0.0278); double t2 = (wave - 459.0) * ((wave < 459.0) ? 0.0385 : 0.0725); z = 1.217 * Math.exp(-0.5 * t1 * t1) + 0.681 * Math.exp(-0.5 * t2 * t2); } return new double[] { x, y, z }; } ``` my code is written in Java 8, but it shouldn't be hard to port it to lower versions of Java and other languages.
Project the wavelength's CIExy towards the D65 white onto the sRGB gamut ------------------------------------------------------------------------ ``` #!/usr/bin/ghci ångstrømsfromTHz terahertz = 2997924.58 / terahertz tristimulusXYZfromÅngstrøms å=map(sum.map(stimulus))[ [[1056,5998,379,310],[362,4420,160,267],[-65,5011,204,262]], [[821,5688,469,405],[286,5309,163,311]], [[1217,4370,118,360],[681,4590,260,138]]] where stimulus[ω,μ,ς,σ]=ω/1000*exp(-((å-μ)/if å<μ then ς else σ)^2/2) standardRGBfromTristimulusXYZ xyz= map(gamma.sum.zipWith(*)(gamutConfine xyz))[ [3.2406,-1.5372,-0.4986],[-0.9689,1.8758,0.0415],[0.0557,-0.2040,1.057]] gamma u=if u<=0.0031308 then 12.92*u else (u**(5/12)*211-11)/200 [red,green,blue,black]= [[0.64,0.33],[0.3,0.6],[0.15,0.06],[0.3127,0.3290,0]] ciexyYfromXYZ xyz=if xyz!!1==0 then black else map(/sum xyz)xyz cieXYZfromxyY[x,y,l]=if y==0 then black else[x*l/y,l,(1-x-y)*l/y] gamutConfine xyz=last$xyz:[cieXYZfromxyY[x0+t*(x1-x0),y0+t*(y1-y0),xyz!!1]| x0:y0:_<-[black],x1:y1:_<-[ciexyYfromXYZ xyz],i<-[0..2], [x2,y2]:[x3,y3]:_<-[drop i[red,green,blue,red]], det<-[(x0-x1)*(y2-y3)-(y0-y1)*(x2-x3)], t <-[((x0-x2)*(y2-y3)-(y0-y2)*(x2-x3))/det|det/=0],0<=t,t<=1] sRGBfromÅ=standardRGBfromTristimulusXYZ.tristimulusXYZfromÅngstrøms x s rgb=concat["\ESC[48;2;", intercalate";"$map(show.(17*).round.(15*).max 0.min 1)rgb, "m",s,"\ESC[49m"] spectrum=concatMap(x" ".sRGBfromÅ)$takeWhile(<7000)$iterate(+60)4000 main=putStrLn spectrum ```
1,472,514
Does anyone know of any formula for converting a light frequency to an RGB value?
2009/09/24
[ "https://Stackoverflow.com/questions/1472514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850/" ]
Although this is an old question and already gets a handful good answers, when I tried to implement such conversion functionality in my application I was not satisfied with the algorithms already listed here and did my own research, which gave me some good result. So I'm going to post a new answer. After some researchs I came across this paper, [Simple Analytic Approximations to the CIE XYZ Color Matching Functions](http://jcgt.org/published/0002/02/01/), and tried to adopt the introduced multi-lobe piecewise Gaussian fit algorithm in my application. The paper only described the functions to convert a wavelength to the corresponding [XYZ values](https://en.wikipedia.org/wiki/CIE_1931_color_space), so I implemented a function to convert XYZ to RGB in the sRGB color space and combined them. The result is fantastic and worth sharing: ```java /** * Convert a wavelength in the visible light spectrum to a RGB color value that is suitable to be displayed on a * monitor * * @param wavelength wavelength in nm * @return RGB color encoded in int. each color is represented with 8 bits and has a layout of * 00000000RRRRRRRRGGGGGGGGBBBBBBBB where MSB is at the leftmost */ public static int wavelengthToRGB(double wavelength){ double[] xyz = cie1931WavelengthToXYZFit(wavelength); double[] rgb = srgbXYZ2RGB(xyz); int c = 0; c |= (((int) (rgb[0] * 0xFF)) & 0xFF) << 16; c |= (((int) (rgb[1] * 0xFF)) & 0xFF) << 8; c |= (((int) (rgb[2] * 0xFF)) & 0xFF) << 0; return c; } /** * Convert XYZ to RGB in the sRGB color space * <p> * The conversion matrix and color component transfer function is taken from http://www.color.org/srgb.pdf, which * follows the International Electrotechnical Commission standard IEC 61966-2-1 "Multimedia systems and equipment - * Colour measurement and management - Part 2-1: Colour management - Default RGB colour space - sRGB" * * @param xyz XYZ values in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] * @return RGB values in a double array, in the order of R, G, B. each value in the range of [0.0, 1.0] */ public static double[] srgbXYZ2RGB(double[] xyz) { double x = xyz[0]; double y = xyz[1]; double z = xyz[2]; double rl = 3.2406255 * x + -1.537208 * y + -0.4986286 * z; double gl = -0.9689307 * x + 1.8757561 * y + 0.0415175 * z; double bl = 0.0557101 * x + -0.2040211 * y + 1.0569959 * z; return new double[] { srgbXYZ2RGBPostprocess(rl), srgbXYZ2RGBPostprocess(gl), srgbXYZ2RGBPostprocess(bl) }; } /** * helper function for {@link #srgbXYZ2RGB(double[])} */ private static double srgbXYZ2RGBPostprocess(double c) { // clip if c is out of range c = c > 1 ? 1 : (c < 0 ? 0 : c); // apply the color component transfer function c = c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1. / 2.4) - 0.055; return c; } /** * A multi-lobe, piecewise Gaussian fit of CIE 1931 XYZ Color Matching Functions by Wyman el al. from Nvidia. The * code here is adopted from the Listing 1 of the paper authored by Wyman et al. * <p> * Reference: Chris Wyman, Peter-Pike Sloan, and Peter Shirley, Simple Analytic Approximations to the CIE XYZ Color * Matching Functions, Journal of Computer Graphics Techniques (JCGT), vol. 2, no. 2, 1-11, 2013. * * @param wavelength wavelength in nm * @return XYZ in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] */ public static double[] cie1931WavelengthToXYZFit(double wavelength) { double wave = wavelength; double x; { double t1 = (wave - 442.0) * ((wave < 442.0) ? 0.0624 : 0.0374); double t2 = (wave - 599.8) * ((wave < 599.8) ? 0.0264 : 0.0323); double t3 = (wave - 501.1) * ((wave < 501.1) ? 0.0490 : 0.0382); x = 0.362 * Math.exp(-0.5 * t1 * t1) + 1.056 * Math.exp(-0.5 * t2 * t2) - 0.065 * Math.exp(-0.5 * t3 * t3); } double y; { double t1 = (wave - 568.8) * ((wave < 568.8) ? 0.0213 : 0.0247); double t2 = (wave - 530.9) * ((wave < 530.9) ? 0.0613 : 0.0322); y = 0.821 * Math.exp(-0.5 * t1 * t1) + 0.286 * Math.exp(-0.5 * t2 * t2); } double z; { double t1 = (wave - 437.0) * ((wave < 437.0) ? 0.0845 : 0.0278); double t2 = (wave - 459.0) * ((wave < 459.0) ? 0.0385 : 0.0725); z = 1.217 * Math.exp(-0.5 * t1 * t1) + 0.681 * Math.exp(-0.5 * t2 * t2); } return new double[] { x, y, z }; } ``` my code is written in Java 8, but it shouldn't be hard to port it to lower versions of Java and other languages.
**Method 1** This is bit cleaned up and tested C++11 version of @haochen-xie. I also added a function that converts value 0 to 1 to a wavelength in visible spectrum that is usable with this method. You can just put below in one header file and use it without any dependencies. This version will be maintained [here](https://github.com/Microsoft/AirSim/blob/master/AirLib/include/common/common_utils/ColorUtils.hpp). ``` #ifndef common_utils_OnlineStats_hpp #define common_utils_OnlineStats_hpp namespace common_utils { class ColorUtils { public: static void valToRGB(double val0To1, unsigned char& r, unsigned char& g, unsigned char& b) { //actual visible spectrum is 375 to 725 but outside of 400-700 things become too dark wavelengthToRGB(val0To1 * (700 - 400) + 400, r, g, b); } /** * Convert a wavelength in the visible light spectrum to a RGB color value that is suitable to be displayed on a * monitor * * @param wavelength wavelength in nm * @return RGB color encoded in int. each color is represented with 8 bits and has a layout of * 00000000RRRRRRRRGGGGGGGGBBBBBBBB where MSB is at the leftmost */ static void wavelengthToRGB(double wavelength, unsigned char& r, unsigned char& g, unsigned char& b) { double x, y, z; cie1931WavelengthToXYZFit(wavelength, x, y, z); double dr, dg, db; srgbXYZ2RGB(x, y, z, dr, dg, db); r = static_cast<unsigned char>(static_cast<int>(dr * 0xFF) & 0xFF); g = static_cast<unsigned char>(static_cast<int>(dg * 0xFF) & 0xFF); b = static_cast<unsigned char>(static_cast<int>(db * 0xFF) & 0xFF); } /** * Convert XYZ to RGB in the sRGB color space * <p> * The conversion matrix and color component transfer function is taken from http://www.color.org/srgb.pdf, which * follows the International Electrotechnical Commission standard IEC 61966-2-1 "Multimedia systems and equipment - * Colour measurement and management - Part 2-1: Colour management - Default RGB colour space - sRGB" * * @param xyz XYZ values in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] * @return RGB values in a double array, in the order of R, G, B. each value in the range of [0.0, 1.0] */ static void srgbXYZ2RGB(double x, double y, double z, double& r, double& g, double& b) { double rl = 3.2406255 * x + -1.537208 * y + -0.4986286 * z; double gl = -0.9689307 * x + 1.8757561 * y + 0.0415175 * z; double bl = 0.0557101 * x + -0.2040211 * y + 1.0569959 * z; r = srgbXYZ2RGBPostprocess(rl); g = srgbXYZ2RGBPostprocess(gl); b = srgbXYZ2RGBPostprocess(bl); } /** * helper function for {@link #srgbXYZ2RGB(double[])} */ static double srgbXYZ2RGBPostprocess(double c) { // clip if c is out of range c = c > 1 ? 1 : (c < 0 ? 0 : c); // apply the color component transfer function c = c <= 0.0031308 ? c * 12.92 : 1.055 * std::pow(c, 1. / 2.4) - 0.055; return c; } /** * A multi-lobe, piecewise Gaussian fit of CIE 1931 XYZ Color Matching Functions by Wyman el al. from Nvidia. The * code here is adopted from the Listing 1 of the paper authored by Wyman et al. * <p> * Reference: Chris Wyman, Peter-Pike Sloan, and Peter Shirley, Simple Analytic Approximations to the CIE XYZ Color * Matching Functions, Journal of Computer Graphics Techniques (JCGT), vol. 2, no. 2, 1-11, 2013. * * @param wavelength wavelength in nm * @return XYZ in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] */ static void cie1931WavelengthToXYZFit(double wavelength, double& x, double& y, double& z) { double wave = wavelength; { double t1 = (wave - 442.0) * ((wave < 442.0) ? 0.0624 : 0.0374); double t2 = (wave - 599.8) * ((wave < 599.8) ? 0.0264 : 0.0323); double t3 = (wave - 501.1) * ((wave < 501.1) ? 0.0490 : 0.0382); x = 0.362 * std::exp(-0.5 * t1 * t1) + 1.056 * std::exp(-0.5 * t2 * t2) - 0.065 * std::exp(-0.5 * t3 * t3); } { double t1 = (wave - 568.8) * ((wave < 568.8) ? 0.0213 : 0.0247); double t2 = (wave - 530.9) * ((wave < 530.9) ? 0.0613 : 0.0322); y = 0.821 * std::exp(-0.5 * t1 * t1) + 0.286 * std::exp(-0.5 * t2 * t2); } { double t1 = (wave - 437.0) * ((wave < 437.0) ? 0.0845 : 0.0278); double t2 = (wave - 459.0) * ((wave < 459.0) ? 0.0385 : 0.0725); z = 1.217 * std::exp(-0.5 * t1 * t1) + 0.681 * std::exp(-0.5 * t2 * t2); } } }; } //namespace #endif ``` The plot of colors from 375nm to 725nm looks like below: [![enter image description here](https://i.stack.imgur.com/5xd8h.png)](https://i.stack.imgur.com/5xd8h.png) One issue with this method is the fact that it works only between 400-700nm and outside of that it sharply falls down to black. Another issue is narrower blue. For comparison, below is the colors from Vision FAQ at maxmax.com: [![enter image description here](https://i.stack.imgur.com/bnwoo.png)](https://i.stack.imgur.com/bnwoo.png) I used this to visualize depth map where each pixel represents depth value in meters and this looks like below: [![enter image description here](https://i.stack.imgur.com/W8sJI.png)](https://i.stack.imgur.com/W8sJI.png) **Method 2** This is implemented as part of [bitmap\_image](https://github.com/ArashPartow/bitmap/blob/master/bitmap_image.hpp#L2851) single file header-only library by Aeash Partow: ``` inline rgb_t convert_wave_length_nm_to_rgb(const double wave_length_nm) { // Credits: Dan Bruton http://www.physics.sfasu.edu/astro/color.html double red = 0.0; double green = 0.0; double blue = 0.0; if ((380.0 <= wave_length_nm) && (wave_length_nm <= 439.0)) { red = -(wave_length_nm - 440.0) / (440.0 - 380.0); green = 0.0; blue = 1.0; } else if ((440.0 <= wave_length_nm) && (wave_length_nm <= 489.0)) { red = 0.0; green = (wave_length_nm - 440.0) / (490.0 - 440.0); blue = 1.0; } else if ((490.0 <= wave_length_nm) && (wave_length_nm <= 509.0)) { red = 0.0; green = 1.0; blue = -(wave_length_nm - 510.0) / (510.0 - 490.0); } else if ((510.0 <= wave_length_nm) && (wave_length_nm <= 579.0)) { red = (wave_length_nm - 510.0) / (580.0 - 510.0); green = 1.0; blue = 0.0; } else if ((580.0 <= wave_length_nm) && (wave_length_nm <= 644.0)) { red = 1.0; green = -(wave_length_nm - 645.0) / (645.0 - 580.0); blue = 0.0; } else if ((645.0 <= wave_length_nm) && (wave_length_nm <= 780.0)) { red = 1.0; green = 0.0; blue = 0.0; } double factor = 0.0; if ((380.0 <= wave_length_nm) && (wave_length_nm <= 419.0)) factor = 0.3 + 0.7 * (wave_length_nm - 380.0) / (420.0 - 380.0); else if ((420.0 <= wave_length_nm) && (wave_length_nm <= 700.0)) factor = 1.0; else if ((701.0 <= wave_length_nm) && (wave_length_nm <= 780.0)) factor = 0.3 + 0.7 * (780.0 - wave_length_nm) / (780.0 - 700.0); else factor = 0.0; rgb_t result; const double gamma = 0.8; const double intensity_max = 255.0; #define round(d) std::floor(d + 0.5) result.red = static_cast<unsigned char>((red == 0.0) ? red : round(intensity_max * std::pow(red * factor, gamma))); result.green = static_cast<unsigned char>((green == 0.0) ? green : round(intensity_max * std::pow(green * factor, gamma))); result.blue = static_cast<unsigned char>((blue == 0.0) ? blue : round(intensity_max * std::pow(blue * factor, gamma))); #undef round return result; } ``` Plot of wavelength from 375-725nm looks like below: [![enter image description here](https://i.stack.imgur.com/LNvgq.png)](https://i.stack.imgur.com/LNvgq.png) So this is more usable in 400-725nm. When I visualize same depth map as in method 1, I get below. There is an obvious issue of those black lines which I think indicates minor bug in this code which I haven't looked more deeply. Also violets are bit narrower in this method which causes less contrast for far away objects. [![enter image description here](https://i.stack.imgur.com/GScUM.png)](https://i.stack.imgur.com/GScUM.png)
1,472,514
Does anyone know of any formula for converting a light frequency to an RGB value?
2009/09/24
[ "https://Stackoverflow.com/questions/1472514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850/" ]
Here's a detailed explanation of the entire conversion process: <http://www.fourmilab.ch/documents/specrend/>. Source code included!
**Method 1** This is bit cleaned up and tested C++11 version of @haochen-xie. I also added a function that converts value 0 to 1 to a wavelength in visible spectrum that is usable with this method. You can just put below in one header file and use it without any dependencies. This version will be maintained [here](https://github.com/Microsoft/AirSim/blob/master/AirLib/include/common/common_utils/ColorUtils.hpp). ``` #ifndef common_utils_OnlineStats_hpp #define common_utils_OnlineStats_hpp namespace common_utils { class ColorUtils { public: static void valToRGB(double val0To1, unsigned char& r, unsigned char& g, unsigned char& b) { //actual visible spectrum is 375 to 725 but outside of 400-700 things become too dark wavelengthToRGB(val0To1 * (700 - 400) + 400, r, g, b); } /** * Convert a wavelength in the visible light spectrum to a RGB color value that is suitable to be displayed on a * monitor * * @param wavelength wavelength in nm * @return RGB color encoded in int. each color is represented with 8 bits and has a layout of * 00000000RRRRRRRRGGGGGGGGBBBBBBBB where MSB is at the leftmost */ static void wavelengthToRGB(double wavelength, unsigned char& r, unsigned char& g, unsigned char& b) { double x, y, z; cie1931WavelengthToXYZFit(wavelength, x, y, z); double dr, dg, db; srgbXYZ2RGB(x, y, z, dr, dg, db); r = static_cast<unsigned char>(static_cast<int>(dr * 0xFF) & 0xFF); g = static_cast<unsigned char>(static_cast<int>(dg * 0xFF) & 0xFF); b = static_cast<unsigned char>(static_cast<int>(db * 0xFF) & 0xFF); } /** * Convert XYZ to RGB in the sRGB color space * <p> * The conversion matrix and color component transfer function is taken from http://www.color.org/srgb.pdf, which * follows the International Electrotechnical Commission standard IEC 61966-2-1 "Multimedia systems and equipment - * Colour measurement and management - Part 2-1: Colour management - Default RGB colour space - sRGB" * * @param xyz XYZ values in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] * @return RGB values in a double array, in the order of R, G, B. each value in the range of [0.0, 1.0] */ static void srgbXYZ2RGB(double x, double y, double z, double& r, double& g, double& b) { double rl = 3.2406255 * x + -1.537208 * y + -0.4986286 * z; double gl = -0.9689307 * x + 1.8757561 * y + 0.0415175 * z; double bl = 0.0557101 * x + -0.2040211 * y + 1.0569959 * z; r = srgbXYZ2RGBPostprocess(rl); g = srgbXYZ2RGBPostprocess(gl); b = srgbXYZ2RGBPostprocess(bl); } /** * helper function for {@link #srgbXYZ2RGB(double[])} */ static double srgbXYZ2RGBPostprocess(double c) { // clip if c is out of range c = c > 1 ? 1 : (c < 0 ? 0 : c); // apply the color component transfer function c = c <= 0.0031308 ? c * 12.92 : 1.055 * std::pow(c, 1. / 2.4) - 0.055; return c; } /** * A multi-lobe, piecewise Gaussian fit of CIE 1931 XYZ Color Matching Functions by Wyman el al. from Nvidia. The * code here is adopted from the Listing 1 of the paper authored by Wyman et al. * <p> * Reference: Chris Wyman, Peter-Pike Sloan, and Peter Shirley, Simple Analytic Approximations to the CIE XYZ Color * Matching Functions, Journal of Computer Graphics Techniques (JCGT), vol. 2, no. 2, 1-11, 2013. * * @param wavelength wavelength in nm * @return XYZ in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] */ static void cie1931WavelengthToXYZFit(double wavelength, double& x, double& y, double& z) { double wave = wavelength; { double t1 = (wave - 442.0) * ((wave < 442.0) ? 0.0624 : 0.0374); double t2 = (wave - 599.8) * ((wave < 599.8) ? 0.0264 : 0.0323); double t3 = (wave - 501.1) * ((wave < 501.1) ? 0.0490 : 0.0382); x = 0.362 * std::exp(-0.5 * t1 * t1) + 1.056 * std::exp(-0.5 * t2 * t2) - 0.065 * std::exp(-0.5 * t3 * t3); } { double t1 = (wave - 568.8) * ((wave < 568.8) ? 0.0213 : 0.0247); double t2 = (wave - 530.9) * ((wave < 530.9) ? 0.0613 : 0.0322); y = 0.821 * std::exp(-0.5 * t1 * t1) + 0.286 * std::exp(-0.5 * t2 * t2); } { double t1 = (wave - 437.0) * ((wave < 437.0) ? 0.0845 : 0.0278); double t2 = (wave - 459.0) * ((wave < 459.0) ? 0.0385 : 0.0725); z = 1.217 * std::exp(-0.5 * t1 * t1) + 0.681 * std::exp(-0.5 * t2 * t2); } } }; } //namespace #endif ``` The plot of colors from 375nm to 725nm looks like below: [![enter image description here](https://i.stack.imgur.com/5xd8h.png)](https://i.stack.imgur.com/5xd8h.png) One issue with this method is the fact that it works only between 400-700nm and outside of that it sharply falls down to black. Another issue is narrower blue. For comparison, below is the colors from Vision FAQ at maxmax.com: [![enter image description here](https://i.stack.imgur.com/bnwoo.png)](https://i.stack.imgur.com/bnwoo.png) I used this to visualize depth map where each pixel represents depth value in meters and this looks like below: [![enter image description here](https://i.stack.imgur.com/W8sJI.png)](https://i.stack.imgur.com/W8sJI.png) **Method 2** This is implemented as part of [bitmap\_image](https://github.com/ArashPartow/bitmap/blob/master/bitmap_image.hpp#L2851) single file header-only library by Aeash Partow: ``` inline rgb_t convert_wave_length_nm_to_rgb(const double wave_length_nm) { // Credits: Dan Bruton http://www.physics.sfasu.edu/astro/color.html double red = 0.0; double green = 0.0; double blue = 0.0; if ((380.0 <= wave_length_nm) && (wave_length_nm <= 439.0)) { red = -(wave_length_nm - 440.0) / (440.0 - 380.0); green = 0.0; blue = 1.0; } else if ((440.0 <= wave_length_nm) && (wave_length_nm <= 489.0)) { red = 0.0; green = (wave_length_nm - 440.0) / (490.0 - 440.0); blue = 1.0; } else if ((490.0 <= wave_length_nm) && (wave_length_nm <= 509.0)) { red = 0.0; green = 1.0; blue = -(wave_length_nm - 510.0) / (510.0 - 490.0); } else if ((510.0 <= wave_length_nm) && (wave_length_nm <= 579.0)) { red = (wave_length_nm - 510.0) / (580.0 - 510.0); green = 1.0; blue = 0.0; } else if ((580.0 <= wave_length_nm) && (wave_length_nm <= 644.0)) { red = 1.0; green = -(wave_length_nm - 645.0) / (645.0 - 580.0); blue = 0.0; } else if ((645.0 <= wave_length_nm) && (wave_length_nm <= 780.0)) { red = 1.0; green = 0.0; blue = 0.0; } double factor = 0.0; if ((380.0 <= wave_length_nm) && (wave_length_nm <= 419.0)) factor = 0.3 + 0.7 * (wave_length_nm - 380.0) / (420.0 - 380.0); else if ((420.0 <= wave_length_nm) && (wave_length_nm <= 700.0)) factor = 1.0; else if ((701.0 <= wave_length_nm) && (wave_length_nm <= 780.0)) factor = 0.3 + 0.7 * (780.0 - wave_length_nm) / (780.0 - 700.0); else factor = 0.0; rgb_t result; const double gamma = 0.8; const double intensity_max = 255.0; #define round(d) std::floor(d + 0.5) result.red = static_cast<unsigned char>((red == 0.0) ? red : round(intensity_max * std::pow(red * factor, gamma))); result.green = static_cast<unsigned char>((green == 0.0) ? green : round(intensity_max * std::pow(green * factor, gamma))); result.blue = static_cast<unsigned char>((blue == 0.0) ? blue : round(intensity_max * std::pow(blue * factor, gamma))); #undef round return result; } ``` Plot of wavelength from 375-725nm looks like below: [![enter image description here](https://i.stack.imgur.com/LNvgq.png)](https://i.stack.imgur.com/LNvgq.png) So this is more usable in 400-725nm. When I visualize same depth map as in method 1, I get below. There is an obvious issue of those black lines which I think indicates minor bug in this code which I haven't looked more deeply. Also violets are bit narrower in this method which causes less contrast for far away objects. [![enter image description here](https://i.stack.imgur.com/GScUM.png)](https://i.stack.imgur.com/GScUM.png)
1,472,514
Does anyone know of any formula for converting a light frequency to an RGB value?
2009/09/24
[ "https://Stackoverflow.com/questions/1472514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850/" ]
Here's a detailed explanation of the entire conversion process: <http://www.fourmilab.ch/documents/specrend/>. Source code included!
General idea: 1. Use [CEI color matching functions](https://en.wikipedia.org/wiki/CIE_1931_color_space#Color_matching_functions) to convert wavelength to [XYZ color](https://en.wikipedia.org/wiki/CIE_1931_color_space#Definition_of_the_CIE_XYZ_color_space). 2. Convert XYZ to RGB 3. Clip components to [0..1] and multiply by 255 to fit in the unsigned byte range. Steps 1 and 2 may vary. There are several color matching functions, available as [tables](http://files.cie.co.at/204.xls) or as analytic approximations (suggested by @Tarc and @Haochen Xie). Tables are best if you need a smooth preсise result. There is no single RGB color space. [Multiple transformation matrices](http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html) and different kinds of gamma correction may be used. Below is the C# code I came up with recently. It uses linear interpolation over the "CIE 1964 standard observer" table and [sRGB matrix + gamma correction](https://en.wikipedia.org/wiki/SRGB#The_forward_transformation_.28CIE_xyY_or_CIE_XYZ_to_sRGB.29). ``` static class RgbCalculator { const int LEN_MIN = 380, LEN_MAX = 780, LEN_STEP = 5; static readonly double[] X = { 0.000160, 0.000662, 0.002362, 0.007242, 0.019110, 0.043400, 0.084736, 0.140638, 0.204492, 0.264737, 0.314679, 0.357719, 0.383734, 0.386726, 0.370702, 0.342957, 0.302273, 0.254085, 0.195618, 0.132349, 0.080507, 0.041072, 0.016172, 0.005132, 0.003816, 0.015444, 0.037465, 0.071358, 0.117749, 0.172953, 0.236491, 0.304213, 0.376772, 0.451584, 0.529826, 0.616053, 0.705224, 0.793832, 0.878655, 0.951162, 1.014160, 1.074300, 1.118520, 1.134300, 1.123990, 1.089100, 1.030480, 0.950740, 0.856297, 0.754930, 0.647467, 0.535110, 0.431567, 0.343690, 0.268329, 0.204300, 0.152568, 0.112210, 0.081261, 0.057930, 0.040851, 0.028623, 0.019941, 0.013842, 0.009577, 0.006605, 0.004553, 0.003145, 0.002175, 0.001506, 0.001045, 0.000727, 0.000508, 0.000356, 0.000251, 0.000178, 0.000126, 0.000090, 0.000065, 0.000046, 0.000033 }, Y = { 0.000017, 0.000072, 0.000253, 0.000769, 0.002004, 0.004509, 0.008756, 0.014456, 0.021391, 0.029497, 0.038676, 0.049602, 0.062077, 0.074704, 0.089456, 0.106256, 0.128201, 0.152761, 0.185190, 0.219940, 0.253589, 0.297665, 0.339133, 0.395379, 0.460777, 0.531360, 0.606741, 0.685660, 0.761757, 0.823330, 0.875211, 0.923810, 0.961988, 0.982200, 0.991761, 0.999110, 0.997340, 0.982380, 0.955552, 0.915175, 0.868934, 0.825623, 0.777405, 0.720353, 0.658341, 0.593878, 0.527963, 0.461834, 0.398057, 0.339554, 0.283493, 0.228254, 0.179828, 0.140211, 0.107633, 0.081187, 0.060281, 0.044096, 0.031800, 0.022602, 0.015905, 0.011130, 0.007749, 0.005375, 0.003718, 0.002565, 0.001768, 0.001222, 0.000846, 0.000586, 0.000407, 0.000284, 0.000199, 0.000140, 0.000098, 0.000070, 0.000050, 0.000036, 0.000025, 0.000018, 0.000013 }, Z = { 0.000705, 0.002928, 0.010482, 0.032344, 0.086011, 0.197120, 0.389366, 0.656760, 0.972542, 1.282500, 1.553480, 1.798500, 1.967280, 2.027300, 1.994800, 1.900700, 1.745370, 1.554900, 1.317560, 1.030200, 0.772125, 0.570060, 0.415254, 0.302356, 0.218502, 0.159249, 0.112044, 0.082248, 0.060709, 0.043050, 0.030451, 0.020584, 0.013676, 0.007918, 0.003988, 0.001091, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000 }; static readonly double[] MATRIX_SRGB_D65 = { 3.2404542, -1.5371385, -0.4985314, -0.9692660, 1.8760108, 0.0415560, 0.0556434, -0.2040259, 1.0572252 }; public static byte[] Calc(double len) { if(len < LEN_MIN || len > LEN_MAX) return new byte[3]; len -= LEN_MIN; var index = (int)Math.Floor(len / LEN_STEP); var offset = len - LEN_STEP * index; var x = Interpolate(X, index, offset); var y = Interpolate(Y, index, offset); var z = Interpolate(Z, index, offset); var m = MATRIX_SRGB_D65; var r = m[0] * x + m[1] * y + m[2] * z; var g = m[3] * x + m[4] * y + m[5] * z; var b = m[6] * x + m[7] * y + m[8] * z; r = Clip(GammaCorrect_sRGB(r)); g = Clip(GammaCorrect_sRGB(g)); b = Clip(GammaCorrect_sRGB(b)); return new[] { (byte)(255 * r), (byte)(255 * g), (byte)(255 * b) }; } static double Interpolate(double[] values, int index, double offset) { if(offset == 0) return values[index]; var x0 = index * LEN_STEP; var x1 = x0 + LEN_STEP; var y0 = values[index]; var y1 = values[1 + index]; return y0 + offset * (y1 - y0) / (x1 - x0); } static double GammaCorrect_sRGB(double c) { if(c <= 0.0031308) return 12.92 * c; var a = 0.055; return (1 + a) * Math.Pow(c, 1 / 2.4) - a; } static double Clip(double c) { if(c < 0) return 0; if(c > 1) return 1; return c; } } ``` Result for the 400-700 nm range: [![enter image description here](https://i.stack.imgur.com/Qudmq.png)](https://i.stack.imgur.com/Qudmq.png)
1,472,514
Does anyone know of any formula for converting a light frequency to an RGB value?
2009/09/24
[ "https://Stackoverflow.com/questions/1472514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850/" ]
For lazy guys (like me), here is an implementation in java of the code found in @user151323 's answer (that is, just a simple translation from pascal code found in [Spectra Lab Report](http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm)): ```java static private final double Gamma = 0.80; static private final double IntensityMax = 255; /** * Taken from Earl F. Glynn's web page: * <a href="http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm">Spectra Lab Report</a> */ public static int[] waveLengthToRGB(double Wavelength) { double factor; double Red, Green, Blue; if((Wavelength >= 380) && (Wavelength < 440)) { Red = -(Wavelength - 440) / (440 - 380); Green = 0.0; Blue = 1.0; } else if((Wavelength >= 440) && (Wavelength < 490)) { Red = 0.0; Green = (Wavelength - 440) / (490 - 440); Blue = 1.0; } else if((Wavelength >= 490) && (Wavelength < 510)) { Red = 0.0; Green = 1.0; Blue = -(Wavelength - 510) / (510 - 490); } else if((Wavelength >= 510) && (Wavelength < 580)) { Red = (Wavelength - 510) / (580 - 510); Green = 1.0; Blue = 0.0; } else if((Wavelength >= 580) && (Wavelength < 645)) { Red = 1.0; Green = -(Wavelength - 645) / (645 - 580); Blue = 0.0; } else if((Wavelength >= 645) && (Wavelength < 781)) { Red = 1.0; Green = 0.0; Blue = 0.0; } else { Red = 0.0; Green = 0.0; Blue = 0.0; } // Let the intensity fall off near the vision limits if((Wavelength >= 380) && (Wavelength < 420)) { factor = 0.3 + 0.7 * (Wavelength - 380) / (420 - 380); } else if((Wavelength >= 420) && (Wavelength < 701)) { factor = 1.0; } else if((Wavelength >= 701) && (Wavelength < 781)) { factor = 0.3 + 0.7 * (780 - Wavelength) / (780 - 700); } else { factor = 0.0; } int[] rgb = new int[3]; // Don't want 0^x = 1 for x <> 0 rgb[0] = Red == 0.0 ? 0 : (int)Math.round(IntensityMax * Math.pow(Red * factor, Gamma)); rgb[1] = Green == 0.0 ? 0 : (int)Math.round(IntensityMax * Math.pow(Green * factor, Gamma)); rgb[2] = Blue == 0.0 ? 0 : (int)Math.round(IntensityMax * Math.pow(Blue * factor, Gamma)); return rgb; } ```
General idea: 1. Use [CEI color matching functions](https://en.wikipedia.org/wiki/CIE_1931_color_space#Color_matching_functions) to convert wavelength to [XYZ color](https://en.wikipedia.org/wiki/CIE_1931_color_space#Definition_of_the_CIE_XYZ_color_space). 2. Convert XYZ to RGB 3. Clip components to [0..1] and multiply by 255 to fit in the unsigned byte range. Steps 1 and 2 may vary. There are several color matching functions, available as [tables](http://files.cie.co.at/204.xls) or as analytic approximations (suggested by @Tarc and @Haochen Xie). Tables are best if you need a smooth preсise result. There is no single RGB color space. [Multiple transformation matrices](http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html) and different kinds of gamma correction may be used. Below is the C# code I came up with recently. It uses linear interpolation over the "CIE 1964 standard observer" table and [sRGB matrix + gamma correction](https://en.wikipedia.org/wiki/SRGB#The_forward_transformation_.28CIE_xyY_or_CIE_XYZ_to_sRGB.29). ``` static class RgbCalculator { const int LEN_MIN = 380, LEN_MAX = 780, LEN_STEP = 5; static readonly double[] X = { 0.000160, 0.000662, 0.002362, 0.007242, 0.019110, 0.043400, 0.084736, 0.140638, 0.204492, 0.264737, 0.314679, 0.357719, 0.383734, 0.386726, 0.370702, 0.342957, 0.302273, 0.254085, 0.195618, 0.132349, 0.080507, 0.041072, 0.016172, 0.005132, 0.003816, 0.015444, 0.037465, 0.071358, 0.117749, 0.172953, 0.236491, 0.304213, 0.376772, 0.451584, 0.529826, 0.616053, 0.705224, 0.793832, 0.878655, 0.951162, 1.014160, 1.074300, 1.118520, 1.134300, 1.123990, 1.089100, 1.030480, 0.950740, 0.856297, 0.754930, 0.647467, 0.535110, 0.431567, 0.343690, 0.268329, 0.204300, 0.152568, 0.112210, 0.081261, 0.057930, 0.040851, 0.028623, 0.019941, 0.013842, 0.009577, 0.006605, 0.004553, 0.003145, 0.002175, 0.001506, 0.001045, 0.000727, 0.000508, 0.000356, 0.000251, 0.000178, 0.000126, 0.000090, 0.000065, 0.000046, 0.000033 }, Y = { 0.000017, 0.000072, 0.000253, 0.000769, 0.002004, 0.004509, 0.008756, 0.014456, 0.021391, 0.029497, 0.038676, 0.049602, 0.062077, 0.074704, 0.089456, 0.106256, 0.128201, 0.152761, 0.185190, 0.219940, 0.253589, 0.297665, 0.339133, 0.395379, 0.460777, 0.531360, 0.606741, 0.685660, 0.761757, 0.823330, 0.875211, 0.923810, 0.961988, 0.982200, 0.991761, 0.999110, 0.997340, 0.982380, 0.955552, 0.915175, 0.868934, 0.825623, 0.777405, 0.720353, 0.658341, 0.593878, 0.527963, 0.461834, 0.398057, 0.339554, 0.283493, 0.228254, 0.179828, 0.140211, 0.107633, 0.081187, 0.060281, 0.044096, 0.031800, 0.022602, 0.015905, 0.011130, 0.007749, 0.005375, 0.003718, 0.002565, 0.001768, 0.001222, 0.000846, 0.000586, 0.000407, 0.000284, 0.000199, 0.000140, 0.000098, 0.000070, 0.000050, 0.000036, 0.000025, 0.000018, 0.000013 }, Z = { 0.000705, 0.002928, 0.010482, 0.032344, 0.086011, 0.197120, 0.389366, 0.656760, 0.972542, 1.282500, 1.553480, 1.798500, 1.967280, 2.027300, 1.994800, 1.900700, 1.745370, 1.554900, 1.317560, 1.030200, 0.772125, 0.570060, 0.415254, 0.302356, 0.218502, 0.159249, 0.112044, 0.082248, 0.060709, 0.043050, 0.030451, 0.020584, 0.013676, 0.007918, 0.003988, 0.001091, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000 }; static readonly double[] MATRIX_SRGB_D65 = { 3.2404542, -1.5371385, -0.4985314, -0.9692660, 1.8760108, 0.0415560, 0.0556434, -0.2040259, 1.0572252 }; public static byte[] Calc(double len) { if(len < LEN_MIN || len > LEN_MAX) return new byte[3]; len -= LEN_MIN; var index = (int)Math.Floor(len / LEN_STEP); var offset = len - LEN_STEP * index; var x = Interpolate(X, index, offset); var y = Interpolate(Y, index, offset); var z = Interpolate(Z, index, offset); var m = MATRIX_SRGB_D65; var r = m[0] * x + m[1] * y + m[2] * z; var g = m[3] * x + m[4] * y + m[5] * z; var b = m[6] * x + m[7] * y + m[8] * z; r = Clip(GammaCorrect_sRGB(r)); g = Clip(GammaCorrect_sRGB(g)); b = Clip(GammaCorrect_sRGB(b)); return new[] { (byte)(255 * r), (byte)(255 * g), (byte)(255 * b) }; } static double Interpolate(double[] values, int index, double offset) { if(offset == 0) return values[index]; var x0 = index * LEN_STEP; var x1 = x0 + LEN_STEP; var y0 = values[index]; var y1 = values[1 + index]; return y0 + offset * (y1 - y0) / (x1 - x0); } static double GammaCorrect_sRGB(double c) { if(c <= 0.0031308) return 12.92 * c; var a = 0.055; return (1 + a) * Math.Pow(c, 1 / 2.4) - a; } static double Clip(double c) { if(c < 0) return 0; if(c > 1) return 1; return c; } } ``` Result for the 400-700 nm range: [![enter image description here](https://i.stack.imgur.com/Qudmq.png)](https://i.stack.imgur.com/Qudmq.png)
1,472,514
Does anyone know of any formula for converting a light frequency to an RGB value?
2009/09/24
[ "https://Stackoverflow.com/questions/1472514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850/" ]
You're talking about converting from *wave length* to an RGB value. Look here, will probably answer your question. Thy have an utility for doing this with the source code as well as some explanation. [WaveLengthToRGB](http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm)
Project the wavelength's CIExy towards the D65 white onto the sRGB gamut ------------------------------------------------------------------------ ``` #!/usr/bin/ghci ångstrømsfromTHz terahertz = 2997924.58 / terahertz tristimulusXYZfromÅngstrøms å=map(sum.map(stimulus))[ [[1056,5998,379,310],[362,4420,160,267],[-65,5011,204,262]], [[821,5688,469,405],[286,5309,163,311]], [[1217,4370,118,360],[681,4590,260,138]]] where stimulus[ω,μ,ς,σ]=ω/1000*exp(-((å-μ)/if å<μ then ς else σ)^2/2) standardRGBfromTristimulusXYZ xyz= map(gamma.sum.zipWith(*)(gamutConfine xyz))[ [3.2406,-1.5372,-0.4986],[-0.9689,1.8758,0.0415],[0.0557,-0.2040,1.057]] gamma u=if u<=0.0031308 then 12.92*u else (u**(5/12)*211-11)/200 [red,green,blue,black]= [[0.64,0.33],[0.3,0.6],[0.15,0.06],[0.3127,0.3290,0]] ciexyYfromXYZ xyz=if xyz!!1==0 then black else map(/sum xyz)xyz cieXYZfromxyY[x,y,l]=if y==0 then black else[x*l/y,l,(1-x-y)*l/y] gamutConfine xyz=last$xyz:[cieXYZfromxyY[x0+t*(x1-x0),y0+t*(y1-y0),xyz!!1]| x0:y0:_<-[black],x1:y1:_<-[ciexyYfromXYZ xyz],i<-[0..2], [x2,y2]:[x3,y3]:_<-[drop i[red,green,blue,red]], det<-[(x0-x1)*(y2-y3)-(y0-y1)*(x2-x3)], t <-[((x0-x2)*(y2-y3)-(y0-y2)*(x2-x3))/det|det/=0],0<=t,t<=1] sRGBfromÅ=standardRGBfromTristimulusXYZ.tristimulusXYZfromÅngstrøms x s rgb=concat["\ESC[48;2;", intercalate";"$map(show.(17*).round.(15*).max 0.min 1)rgb, "m",s,"\ESC[49m"] spectrum=concatMap(x" ".sRGBfromÅ)$takeWhile(<7000)$iterate(+60)4000 main=putStrLn spectrum ```
1,472,514
Does anyone know of any formula for converting a light frequency to an RGB value?
2009/09/24
[ "https://Stackoverflow.com/questions/1472514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850/" ]
Here's a detailed explanation of the entire conversion process: <http://www.fourmilab.ch/documents/specrend/>. Source code included!
Project the wavelength's CIExy towards the D65 white onto the sRGB gamut ------------------------------------------------------------------------ ``` #!/usr/bin/ghci ångstrømsfromTHz terahertz = 2997924.58 / terahertz tristimulusXYZfromÅngstrøms å=map(sum.map(stimulus))[ [[1056,5998,379,310],[362,4420,160,267],[-65,5011,204,262]], [[821,5688,469,405],[286,5309,163,311]], [[1217,4370,118,360],[681,4590,260,138]]] where stimulus[ω,μ,ς,σ]=ω/1000*exp(-((å-μ)/if å<μ then ς else σ)^2/2) standardRGBfromTristimulusXYZ xyz= map(gamma.sum.zipWith(*)(gamutConfine xyz))[ [3.2406,-1.5372,-0.4986],[-0.9689,1.8758,0.0415],[0.0557,-0.2040,1.057]] gamma u=if u<=0.0031308 then 12.92*u else (u**(5/12)*211-11)/200 [red,green,blue,black]= [[0.64,0.33],[0.3,0.6],[0.15,0.06],[0.3127,0.3290,0]] ciexyYfromXYZ xyz=if xyz!!1==0 then black else map(/sum xyz)xyz cieXYZfromxyY[x,y,l]=if y==0 then black else[x*l/y,l,(1-x-y)*l/y] gamutConfine xyz=last$xyz:[cieXYZfromxyY[x0+t*(x1-x0),y0+t*(y1-y0),xyz!!1]| x0:y0:_<-[black],x1:y1:_<-[ciexyYfromXYZ xyz],i<-[0..2], [x2,y2]:[x3,y3]:_<-[drop i[red,green,blue,red]], det<-[(x0-x1)*(y2-y3)-(y0-y1)*(x2-x3)], t <-[((x0-x2)*(y2-y3)-(y0-y2)*(x2-x3))/det|det/=0],0<=t,t<=1] sRGBfromÅ=standardRGBfromTristimulusXYZ.tristimulusXYZfromÅngstrøms x s rgb=concat["\ESC[48;2;", intercalate";"$map(show.(17*).round.(15*).max 0.min 1)rgb, "m",s,"\ESC[49m"] spectrum=concatMap(x" ".sRGBfromÅ)$takeWhile(<7000)$iterate(+60)4000 main=putStrLn spectrum ```