qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
24,687,238
I am using a Picker View to allow the user to choose the colour theme for the entire app. I am planning on changing the colour of the navigation bar, background and possibly the tab bar (if that is possible). I've been researching how to do this but can't find any Swift examples. Could anyone please give me an example of the code I would need to use to change the navigation bar colour and navigation bar text colour? The Picker View is set up, I'm just looking for the code to change the UI colours.
2014/07/10
[ "https://Stackoverflow.com/questions/24687238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3746428/" ]
Navigation Bar: ``` navigationController?.navigationBar.barTintColor = UIColor.green ``` Replace greenColor with whatever UIColor you want, you can use an RGB too if you prefer. Navigation Bar Text: ``` navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange] ``` Replace orangeColor with whatever color you like. Tab Bar: ``` tabBarController?.tabBar.barTintColor = UIColor.brown ``` Tab Bar Text: ``` tabBarController?.tabBar.tintColor = UIColor.yellow ``` On the last two, replace brownColor and yellowColor with the color of your choice.
This version also **removes the 1px shadow line under the navigation bar**: **Swift 5**: Put this in your **AppDelegate** didFinishLaunchingWithOptions ``` UINavigationBar.appearance().barTintColor = UIColor.black UINavigationBar.appearance().tintColor = UIColor.white UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] UINavigationBar.appearance().isTranslucent = false UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .any, barMetrics: .default) UINavigationBar.appearance().shadowImage = UIImage() ```
38,556
I have Skyrim for the computer and really love playing it, but recently I've been wanting to play it while reclining in my lazyboy and playing the game on a 51in high def. My computer is right next to my amp so making the HDMI connect wouldn't be hard. This isn't a question regarding whether or not its possible to use the controller. My question is, for those of you who have played Skyrim with both a controller and mouse/keyboard, which one did you like better, and what were the ups and downs of each? Would the best option be to recline with mouse and keyboard?
2011/11/26
[ "https://gaming.stackexchange.com/questions/38556", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/15323/" ]
I have the [XBox Wireless Controller for Windows](http://rads.stackoverflow.com/amzn/click/B004QRKWKQ), and I much prefer the keyboard WASD experience. But I prefer it for exactly 1 reason: I'm playing a sneaky, bow-oriented character. Moving around is just as easy with the controller. Melee fighting is just as easy with the controller. But, making those long range stealth shots with the mouse is **so** much easier than with the controller. I think if I were not so stealth+bow oriented, I'd be using the controller more. Also, the game just feels right with a controller. The menus, which seem to be a pain with keyboard and mouse are so much more natural with a controller. So I'm sticking to the keyboard, but only because of my current character's play style.
**Controller pros:** * You can recline on the couch while playing on the TV. (Which you can also do when using a keyboard, but I've never managed to control the mouse properly that way.) * As Jarret Meyer says, the menus are faster, simpler and more natural to navigate with a controller. * Possibly subjective, but I find it more natural to control the character with two joysticks. **Controller cons:** * You lose the keyboard shortcuts, e.g. switching between several sets of weapons or spells at a single key press. (Although the game pauses while you scroll through the quick-list of favorites, so it's not critical.) * Aiming with a bow, especially at long range, is dramatically faster and more precise when using a mouse. * *Situation dependent: I'm using a [PS3 controller](https://gaming.stackexchange.com/questions/37013/how-do-you-use-a-pc-ps3-controller-when-playing-skyrim-on-a-pc), installation was somewhat fiddly and I couldn't get it to work over Bluetooth. So no wireless controller for me; but it works fine over USB.* I'm using the controller for now, I prefer the more relaxed play style. But it would be hard to defend picking the controller for a sneaking-and-archery oriented character.
45,501,673
I am facing below issue in my entire installations of M2. ``` [InvalidArgumentException] There are no commands defined in the "setup" namespace. ``` weird thing is I installed fresh Xampp and set up new M2 instance, then also same issue persists. It started coming suddenly and I have tried all available solutions like setting permissions to folders and trying -vvv option and list command to find exact issue. till now no success. My whole day wasted in debugging this only and now I am running out of thoughts. If anyone have ideas? I am using PHP 5.6 and Magento EE 2.1.7
2017/08/04
[ "https://Stackoverflow.com/questions/45501673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3784529/" ]
**In Function traverse** ``` void traverse(struct node *head) { ...... ...... } ``` Traverse function has a parameter `head` which is of type struct node pointer. Hence to call `traverse` function you must pass an argument of type struct node pointer. In main function you defined head as `struct node *head = NULL;` that's why you are making call to the function like `traverse(head)`. **In Function append** ``` void append(struct node **headRef, int data) { .... .... } ``` The argument `headref` is of type 'pointer to pointer'. > > Pointer to Pointer variable stores the address of pointer > > > Hence, you must pass address of pointer as argument and you make call to append function as `append(&head,data)` To use pointer as a parameter in append function Change the return type of you function from void to `struct node*` and return the headRef pointer. ``` struct node* append(struct node *headRef, int data) { struct node *newNode = makeNode(data); struct node *ptr = headRef, *temp; if( ptr == NULL ) { headRef = newNode; return headRef; } while(ptr != NULL) { temp = ptr; ptr = ptr->next; } temp->next = newNode; return headref; } ``` Inside the main function, you should call append function like this. ``` head = append(head,data); //since append function is now returning a pointer ``` **Complete code to append nodes using single pointer** ``` #include<stdio.h> struct node { int data; struct node * next; }; struct node * makeNode(int item) { struct node * newNode = (struct node * ) malloc(sizeof(struct node)); newNode -> data = item; newNode -> next = NULL; return newNode; } void traverse(struct node * head) { struct node * ptr = head; while (ptr != NULL) { printf("%d ", ptr -> data); ptr = ptr -> next; } printf("\n"); } struct node * append(struct node * headRef, int data) { struct node * newNode = makeNode(data); struct node * ptr = headRef, * temp; if (ptr == NULL) { headRef = newNode; return headRef; } while (ptr != NULL) { temp = ptr; ptr = ptr -> next; } temp -> next = newNode; return headRef; } int main() { struct node * head = NULL; int data; printf("Enter Positive Data:\n"); scanf("%d", & data); while (data >= 0) { head = append(head, data); scanf("%d", & data); } printf("\nTraversing...\n"); traverse(head); return 0; } ```
Function `append` may alter the value of head (which is a pointer). The signature is therefore `void append(struct node **headRef, int data)`; note the `**`, which denotes a pointer to a pointer. So you have to pass the address of the pointer in order to allow `append` to change the pointer, i.e. call `append(&head,data)`. Function `traverse`, in contrast, needs not to alter the value of head, so it consumes the pointer directly (and not a pointer to that pointer). The signature is therefore `void traverse(struct node *head)`; note the single `*`. Hence, call it like `traverse(head)`.
45,501,673
I am facing below issue in my entire installations of M2. ``` [InvalidArgumentException] There are no commands defined in the "setup" namespace. ``` weird thing is I installed fresh Xampp and set up new M2 instance, then also same issue persists. It started coming suddenly and I have tried all available solutions like setting permissions to folders and trying -vvv option and list command to find exact issue. till now no success. My whole day wasted in debugging this only and now I am running out of thoughts. If anyone have ideas? I am using PHP 5.6 and Magento EE 2.1.7
2017/08/04
[ "https://Stackoverflow.com/questions/45501673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3784529/" ]
**In Function traverse** ``` void traverse(struct node *head) { ...... ...... } ``` Traverse function has a parameter `head` which is of type struct node pointer. Hence to call `traverse` function you must pass an argument of type struct node pointer. In main function you defined head as `struct node *head = NULL;` that's why you are making call to the function like `traverse(head)`. **In Function append** ``` void append(struct node **headRef, int data) { .... .... } ``` The argument `headref` is of type 'pointer to pointer'. > > Pointer to Pointer variable stores the address of pointer > > > Hence, you must pass address of pointer as argument and you make call to append function as `append(&head,data)` To use pointer as a parameter in append function Change the return type of you function from void to `struct node*` and return the headRef pointer. ``` struct node* append(struct node *headRef, int data) { struct node *newNode = makeNode(data); struct node *ptr = headRef, *temp; if( ptr == NULL ) { headRef = newNode; return headRef; } while(ptr != NULL) { temp = ptr; ptr = ptr->next; } temp->next = newNode; return headref; } ``` Inside the main function, you should call append function like this. ``` head = append(head,data); //since append function is now returning a pointer ``` **Complete code to append nodes using single pointer** ``` #include<stdio.h> struct node { int data; struct node * next; }; struct node * makeNode(int item) { struct node * newNode = (struct node * ) malloc(sizeof(struct node)); newNode -> data = item; newNode -> next = NULL; return newNode; } void traverse(struct node * head) { struct node * ptr = head; while (ptr != NULL) { printf("%d ", ptr -> data); ptr = ptr -> next; } printf("\n"); } struct node * append(struct node * headRef, int data) { struct node * newNode = makeNode(data); struct node * ptr = headRef, * temp; if (ptr == NULL) { headRef = newNode; return headRef; } while (ptr != NULL) { temp = ptr; ptr = ptr -> next; } temp -> next = newNode; return headRef; } int main() { struct node * head = NULL; int data; printf("Enter Positive Data:\n"); scanf("%d", & data); while (data >= 0) { head = append(head, data); scanf("%d", & data); } printf("\nTraversing...\n"); traverse(head); return 0; } ```
include ======= struct node { ``` int data; struct node *next; ``` }; struct node \*makeNode(int item) { ``` struct node *newNode = (struct node *)malloc(sizeof(struct node)); newNode->data = item; newNode->next = NULL; return newNode; ``` } i got bug in the above line void traverse(struct node \*head) { ``` struct node *ptr = head; while(ptr != NULL) { printf("%d ",ptr->data); ptr = ptr->next; } printf("\n"); ``` } i know that there is no need to return the pointer .is it true? if it is true why need to give a return type in the following function? struct node\* append(struct node \*headRef, int data) { ``` struct node *newNode = makeNode(data); struct node *ptr = headRef, *temp; if( ptr == NULL ) { headRef = newNode; return headRef; } while(ptr != NULL) { temp = ptr; ptr = ptr->next; } temp->next = newNode; return headref; ``` } int main() { ``` struct node *head = NULL; int data; printf("Enter Positive Data:\n"); scanf("%d",&data); while( data>=0 ) { head=append(head,data); scanf("%d",&data); } printf("\nTraversing...\n"); traverse(head); ``` }
53,460,983
i am new with java script how can i make it, if is checked from user to redirect after 30s, i tried with some javascript from others website but didn't help ```html <input type="checkbox" id="redirect30sid" name="redirect30sname" value="Redirectvalue">Redirect me after 30s<br> ```
2018/11/24
[ "https://Stackoverflow.com/questions/53460983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9963490/" ]
By selecting the checkbox and adding an event listener on it that activates on changing the state of the checkbox. ``` var checkbox = document.querySelector("#redirect30sid"); checkbox.addEventListener( 'change', function() { if(this.checked) { // Checkbox is checked.. setTimeout(function(){ window.location.href = "https://www.example.com";//put your url here }, 30000);//Time in ms } else { // Checkbox is not checked.. //Do other stuff } }) ```
``` <input type="checkbox" id="redirect30sid" name="redirect30sname" value="Redirectvalue">Redirect me after 30s <script> const checkboxElement = document.getElementById('redirect30sid') checkboxElement.addEventListener('change', (event) => { if (event.target.checked) { setTimeout(function () { // Double check if the check box is still checked if (event.target.checked) window.location = checkboxElement.value; }, 30 * 1000); } }) </script> ``` Pure Javascript
53,460,983
i am new with java script how can i make it, if is checked from user to redirect after 30s, i tried with some javascript from others website but didn't help ```html <input type="checkbox" id="redirect30sid" name="redirect30sname" value="Redirectvalue">Redirect me after 30s<br> ```
2018/11/24
[ "https://Stackoverflow.com/questions/53460983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9963490/" ]
```html <input type="checkbox" onclick="handleClick(this)">Redirect me after 30s<br> <script> let handleClick = (ele) => { if (ele.checked) { redirectTime = setTimeout(() => { window.location = "/" }, 30000) } else if (!ele.checked && typeof redirectTime !== 'undefined') { clearTimeout(redirectTime); } } </script> ``` much cleaner, simpler. edit: if the checkbox is unchecked within 30s redirect doesn't fire.
``` <input type="checkbox" id="redirect30sid" name="redirect30sname" value="Redirectvalue">Redirect me after 30s <script> const checkboxElement = document.getElementById('redirect30sid') checkboxElement.addEventListener('change', (event) => { if (event.target.checked) { setTimeout(function () { // Double check if the check box is still checked if (event.target.checked) window.location = checkboxElement.value; }, 30 * 1000); } }) </script> ``` Pure Javascript
58,541
There is a service called [ProtonMail](http://protonmail.ch). It encrypts email on the client side, stores encrypted message on their servers, and then the recipient decrypts it, also on the client side and the system "doesn't store keys". My question is this: How does the decryption work? I'm a bit confused. Do I have to send my decryption key to each recipient before he can read my messages?
2014/05/22
[ "https://security.stackexchange.com/questions/58541", "https://security.stackexchange.com", "https://security.stackexchange.com/users/47094/" ]
I am Jason, one of the ProtonMail developers. Decryption uses a combination of asymmetric (RSA) and symmetric (AES) encryption. For PM to PM emails, we use an implementation of PGP where we handle the key exchange. So we have all the public keys. As for the private keys, when you create an account, it is generated on your browser, then encrypted with your mailbox password (which we do not have access to). Then the encrypted private key is pushed to the server so we can push it back to you whenever you login. So do we store your private key, yes, but since it is the encrypted private key, we don't actually have access to your key. For PM to Outside emails, encryption is optional. If you select to encrypt, we use symmetric encryption with a password that you set for that message. This password can be ANYTHING. It should NOT be your Mailbox password. You need to somehow communicate this password to the recipient. We have a couple other tricks as well for getting around the horrible performance of RSA. We will eventually write a whitepaper with full details that anybody can understand. But something like that is a week long project in itself. I apologize in advance if my answer only makes sense to crypto people.
Under the "Security" tab of their page they state: > > We support sending encrypted communication to non-ProtonMail users via symmetric encryption. When you send an encrypted message to a non-ProtonMail user, they receive a link which loads the encrypted message onto their browser which they can decrypt using a decryption passphrase that you have shared with them. > > > Looks like you have to share the decryption passphrase with the receiver first.
58,541
There is a service called [ProtonMail](http://protonmail.ch). It encrypts email on the client side, stores encrypted message on their servers, and then the recipient decrypts it, also on the client side and the system "doesn't store keys". My question is this: How does the decryption work? I'm a bit confused. Do I have to send my decryption key to each recipient before he can read my messages?
2014/05/22
[ "https://security.stackexchange.com/questions/58541", "https://security.stackexchange.com", "https://security.stackexchange.com/users/47094/" ]
I am Jason, one of the ProtonMail developers. Decryption uses a combination of asymmetric (RSA) and symmetric (AES) encryption. For PM to PM emails, we use an implementation of PGP where we handle the key exchange. So we have all the public keys. As for the private keys, when you create an account, it is generated on your browser, then encrypted with your mailbox password (which we do not have access to). Then the encrypted private key is pushed to the server so we can push it back to you whenever you login. So do we store your private key, yes, but since it is the encrypted private key, we don't actually have access to your key. For PM to Outside emails, encryption is optional. If you select to encrypt, we use symmetric encryption with a password that you set for that message. This password can be ANYTHING. It should NOT be your Mailbox password. You need to somehow communicate this password to the recipient. We have a couple other tricks as well for getting around the horrible performance of RSA. We will eventually write a whitepaper with full details that anybody can understand. But something like that is a week long project in itself. I apologize in advance if my answer only makes sense to crypto people.
> > ProtonMail's segregated authentication and decryption system means logging into a ProtonMail account that requires two passwords. The first password is used to authenticate the user and retrieve the correct account. After that, encrypted data is sent to the user. The second password is a decryption password which is never sent to us. It is used to decrypt the user’s data in the browser so we never have access to the decrypted data, or the decryption password. For this reason, we are also unable to do password recovery. If you forget your decryption password, we cannot recover your data. > > > [Source](https://protonmail.ch/pages/security_details.php) So it appears that a password is used to authenticate you, and a second password (which is the decryption key) is used to recover your data and display it in your browser (through HTTPS). Your second password/decryption key isn't stored in their servers, and all decryption is done locally in your system. They can't decrypt what they don't have keys to. That doesn't mean a keylogger on your system can't get the info necessary to decrypt your data, though. As for sending secure email to non-Proton users: > > Even your communication with non-ProtonMail users is secure. > > > We support sending encrypted communication to non-ProtonMail users via symmetric encryption. When you send an encrypted message to a non-ProtonMail user, they receive a link which loads the encrypted message onto their browser which they can decrypt using a decryption passphrase that you have shared with them. You can also send unencrypted messages to Gmail, Yahoo, Outlook and others, just like regular email. > > > As a personal opinion, it does look very secure. If their servers were ever seized, it appears that they wouldn't be able to do anything to unlock the data. The weakest link is the end-users, the passwords they use, and whether their passwords get compromised or not (though it looks like even if ProtonMail's password database for the first password was hacked, all the attackers would have is encrypted data, as no database is used to store the second password).
58,541
There is a service called [ProtonMail](http://protonmail.ch). It encrypts email on the client side, stores encrypted message on their servers, and then the recipient decrypts it, also on the client side and the system "doesn't store keys". My question is this: How does the decryption work? I'm a bit confused. Do I have to send my decryption key to each recipient before he can read my messages?
2014/05/22
[ "https://security.stackexchange.com/questions/58541", "https://security.stackexchange.com", "https://security.stackexchange.com/users/47094/" ]
"ProtonMail's segregated authentication and decryption system means logging into a ProtonMail account that requires two passwords. The **first password is used to authenticate the user** and retrieve the correct account. After that, encrypted data is sent to the user. The **second password is a decryption password** which is never sent to us. [**The second password is] used to decrypt the user’s data in the browser** so we never have access to the decrypted data, or the decryption password. For this reason, we are also unable to do password recovery. If you forget your decryption password, we cannot recover your data." As a commentary to this, I would say that this would still be vulnerable to a NSA-vs-Lavabit style SSL key compromise. If you can get their SSL key, you an impersonate ProtonMail and use javascript to steal both the first and second pasword of all users. This can break the entire encryption protocol. So this way it won't be the "The Only Email System The NSA Can't Access": <http://www.forbes.com/sites/hollieslade/2014/05/19/the-only-email-system-the-nsa-cant-access/>
> > ProtonMail's segregated authentication and decryption system means logging into a ProtonMail account that requires two passwords. The first password is used to authenticate the user and retrieve the correct account. After that, encrypted data is sent to the user. The second password is a decryption password which is never sent to us. It is used to decrypt the user’s data in the browser so we never have access to the decrypted data, or the decryption password. For this reason, we are also unable to do password recovery. If you forget your decryption password, we cannot recover your data. > > > [Source](https://protonmail.ch/pages/security_details.php) So it appears that a password is used to authenticate you, and a second password (which is the decryption key) is used to recover your data and display it in your browser (through HTTPS). Your second password/decryption key isn't stored in their servers, and all decryption is done locally in your system. They can't decrypt what they don't have keys to. That doesn't mean a keylogger on your system can't get the info necessary to decrypt your data, though. As for sending secure email to non-Proton users: > > Even your communication with non-ProtonMail users is secure. > > > We support sending encrypted communication to non-ProtonMail users via symmetric encryption. When you send an encrypted message to a non-ProtonMail user, they receive a link which loads the encrypted message onto their browser which they can decrypt using a decryption passphrase that you have shared with them. You can also send unencrypted messages to Gmail, Yahoo, Outlook and others, just like regular email. > > > As a personal opinion, it does look very secure. If their servers were ever seized, it appears that they wouldn't be able to do anything to unlock the data. The weakest link is the end-users, the passwords they use, and whether their passwords get compromised or not (though it looks like even if ProtonMail's password database for the first password was hacked, all the attackers would have is encrypted data, as no database is used to store the second password).
58,541
There is a service called [ProtonMail](http://protonmail.ch). It encrypts email on the client side, stores encrypted message on their servers, and then the recipient decrypts it, also on the client side and the system "doesn't store keys". My question is this: How does the decryption work? I'm a bit confused. Do I have to send my decryption key to each recipient before he can read my messages?
2014/05/22
[ "https://security.stackexchange.com/questions/58541", "https://security.stackexchange.com", "https://security.stackexchange.com/users/47094/" ]
**I have substantially altered this answer after the answer from Jason and an email conversation. The original is still available in the edit history.** There are two different cases here: ProtonMail-to-ProtonMail and ProtonMail-to-Other mails. For PM-to-PM emails, the system is in a position to handle public-key/private-key distribution. Since they wrote the code that generates the private keys and sends the public keys to the server and they know the recipient of the email before encrypting, they can encrypt with the recipient's public key and the recipient can decrypt with their private key. This can be transparent to the users of the system. They don't mention signing emails with your private key but this should also be equally possible and transparent. PM-to-Other emails do not use asymmetric encryption. When creating an email to a recipient who is not using ProtonMail, you generate a new password that is used to derive a symmetric key that is used to encrypt the message. You then must convey this password to your recipient using different using a different, independently secure method. Emailing your recipient the decryption key and then the encrypted email is the same as not using encryption if your threat model includes an attacker that can intercept your email. (If your threat model *doesn't* include this ability, why do you even need encrypted mail?) The mail your recipient actually receives in their mail client is not encrypted and is not your original message. It is simply a link to the ProtonMail website where they can use the password you already communicated to them to decrypt your message. In both cases, the claim is that the encryption and decryption is done using Javascript in your browser and the centralised servers only ever see encrypted data. If you have an independent, secure method of communication for the decryption password, why not just use that instead of ProtonMail? One reason might be that your independent method is not as convenient. It might be visiting the recipient in person or phoning them up. Another potential reason is for advertising or promotional purposes. If you like ProtonMail and would like your contacts to use it, emailing them from ProtonMail would promote that. But if you have a method you consider secure *and* convenient (OTR, Cryptocat, Skype, whatever you trust) then why not just use that? --- I am cautious by nature and have reservations about this service, at least until it has had its trial by fire. 1. There is no way of revoking or changing a mailbox password. [If your mailbox password ever does leak, your only recourse is to close your account an create a new one](https://protonmail.ch/pages/faq.php#faq3). Presumably, this will be much like getting a new email address is now, meaning lots of email will be delivered to your old address after you have closed it and nobody will know your new address. I expect you would also lose access all of your old email. There's no cryptographic reason why your recipients would lose access to the email you have sent them but the system may delete all email when the sender is deleted since it's all stored on their servers. 2. For non-ProtonMail users who receive lots of encrypted email from ProtonMail users, they will have to store the decryption password for every email somewhere and a mapping between them. Every individual email will require looking up and typing in a new password. I would assert this is not *usable*. 3. Making claims is easy. [Ladar Levison said that Lavabit stored no keys](http://www.thoughtcrime.org/blog/lavabit-critique/) so he could not be compelled to disclose them. [This turned out to be false](http://safegov.org/2014/1/2/lessons-from-lavabit-%E2%80%93-who-holds-the-keys). The design of ProtonMail looks significantly better but claims of "Even we can't read your mail" are still suspect until proven. 4. They omit important details from [their FAQ/instructions](https://protonmail.ch/pages/security_details.php). For instance, when claiming to be able to delete emails at a certain time, they don't mention that a user can copy that email into another program before it is deleted and the copy won't be deleted. They also omit the detail that you must find your own secure method of distributing the decryption password for PM-to-Other emails. 5. The expiry time feature references SnapChat [which infamously doesn't actually delete the images but rather just stops listing them within the app](http://www.theguardian.com/media-network/partner-zone-infosecurity/snapchat-photos-not-deleted-hidden). 6. [Some smart people also have reservations about it](https://twitter.com/hdmoore/status/467398089267871744). 7. The only metadata mentioned are IP addresses and access times. Metadata such as To: and From: addresses must be stored on their servers in an accessible format (i.e. plain text or with encryption keys available) to enable the email to be delivered to the right person. IP addresses and access times can obviously still be captured and stored by attackers. 8. The system cannot be used if you are offline. No catching up on your email during a flight or on the Underground. You don't have a copy of your email if the service shuts down. 9. Your private key is stored on the ProtonMail servers, [encrypted with AES256](https://twitter.com/ProtonMail/status/470352918600634368) using your mailbox password. This is likely so that you can use ProtonMail on a different computer and they can just push your private key to that computer for you to decrypt with your mailbox password. This is a compromise of security for usability/convenience. It's also in contradiction to the security page on the website which says that they are not sent to the server. 10. Jason's answer mentions "tricks" for improving the performance of RSA. Seemingly benign changes have been made before to crypto code that have completely compromised its security. It's definitely not NSA-proof but all the buzz about it uses that exact phrase to claim it is. Their own blog post on threat models says that it's not NSA-proof. It may be useful for you, but not if you're trying to organise a revolution.
i'm guessing they use PGP key, with one public key and one private key. They store your public key, and your private key encrypted using your password (you have to trust them to store only the encrypted private key). They have your public key, so they can encrypt any incoming mail. If you want to read your mail, once you are identified, they send you (this is transparent) the private key encrypted using your password that is decripted with your password, and you can then use this private key to decipher your emails. If this is it, seems pretty good to me.
58,541
There is a service called [ProtonMail](http://protonmail.ch). It encrypts email on the client side, stores encrypted message on their servers, and then the recipient decrypts it, also on the client side and the system "doesn't store keys". My question is this: How does the decryption work? I'm a bit confused. Do I have to send my decryption key to each recipient before he can read my messages?
2014/05/22
[ "https://security.stackexchange.com/questions/58541", "https://security.stackexchange.com", "https://security.stackexchange.com/users/47094/" ]
**I have substantially altered this answer after the answer from Jason and an email conversation. The original is still available in the edit history.** There are two different cases here: ProtonMail-to-ProtonMail and ProtonMail-to-Other mails. For PM-to-PM emails, the system is in a position to handle public-key/private-key distribution. Since they wrote the code that generates the private keys and sends the public keys to the server and they know the recipient of the email before encrypting, they can encrypt with the recipient's public key and the recipient can decrypt with their private key. This can be transparent to the users of the system. They don't mention signing emails with your private key but this should also be equally possible and transparent. PM-to-Other emails do not use asymmetric encryption. When creating an email to a recipient who is not using ProtonMail, you generate a new password that is used to derive a symmetric key that is used to encrypt the message. You then must convey this password to your recipient using different using a different, independently secure method. Emailing your recipient the decryption key and then the encrypted email is the same as not using encryption if your threat model includes an attacker that can intercept your email. (If your threat model *doesn't* include this ability, why do you even need encrypted mail?) The mail your recipient actually receives in their mail client is not encrypted and is not your original message. It is simply a link to the ProtonMail website where they can use the password you already communicated to them to decrypt your message. In both cases, the claim is that the encryption and decryption is done using Javascript in your browser and the centralised servers only ever see encrypted data. If you have an independent, secure method of communication for the decryption password, why not just use that instead of ProtonMail? One reason might be that your independent method is not as convenient. It might be visiting the recipient in person or phoning them up. Another potential reason is for advertising or promotional purposes. If you like ProtonMail and would like your contacts to use it, emailing them from ProtonMail would promote that. But if you have a method you consider secure *and* convenient (OTR, Cryptocat, Skype, whatever you trust) then why not just use that? --- I am cautious by nature and have reservations about this service, at least until it has had its trial by fire. 1. There is no way of revoking or changing a mailbox password. [If your mailbox password ever does leak, your only recourse is to close your account an create a new one](https://protonmail.ch/pages/faq.php#faq3). Presumably, this will be much like getting a new email address is now, meaning lots of email will be delivered to your old address after you have closed it and nobody will know your new address. I expect you would also lose access all of your old email. There's no cryptographic reason why your recipients would lose access to the email you have sent them but the system may delete all email when the sender is deleted since it's all stored on their servers. 2. For non-ProtonMail users who receive lots of encrypted email from ProtonMail users, they will have to store the decryption password for every email somewhere and a mapping between them. Every individual email will require looking up and typing in a new password. I would assert this is not *usable*. 3. Making claims is easy. [Ladar Levison said that Lavabit stored no keys](http://www.thoughtcrime.org/blog/lavabit-critique/) so he could not be compelled to disclose them. [This turned out to be false](http://safegov.org/2014/1/2/lessons-from-lavabit-%E2%80%93-who-holds-the-keys). The design of ProtonMail looks significantly better but claims of "Even we can't read your mail" are still suspect until proven. 4. They omit important details from [their FAQ/instructions](https://protonmail.ch/pages/security_details.php). For instance, when claiming to be able to delete emails at a certain time, they don't mention that a user can copy that email into another program before it is deleted and the copy won't be deleted. They also omit the detail that you must find your own secure method of distributing the decryption password for PM-to-Other emails. 5. The expiry time feature references SnapChat [which infamously doesn't actually delete the images but rather just stops listing them within the app](http://www.theguardian.com/media-network/partner-zone-infosecurity/snapchat-photos-not-deleted-hidden). 6. [Some smart people also have reservations about it](https://twitter.com/hdmoore/status/467398089267871744). 7. The only metadata mentioned are IP addresses and access times. Metadata such as To: and From: addresses must be stored on their servers in an accessible format (i.e. plain text or with encryption keys available) to enable the email to be delivered to the right person. IP addresses and access times can obviously still be captured and stored by attackers. 8. The system cannot be used if you are offline. No catching up on your email during a flight or on the Underground. You don't have a copy of your email if the service shuts down. 9. Your private key is stored on the ProtonMail servers, [encrypted with AES256](https://twitter.com/ProtonMail/status/470352918600634368) using your mailbox password. This is likely so that you can use ProtonMail on a different computer and they can just push your private key to that computer for you to decrypt with your mailbox password. This is a compromise of security for usability/convenience. It's also in contradiction to the security page on the website which says that they are not sent to the server. 10. Jason's answer mentions "tricks" for improving the performance of RSA. Seemingly benign changes have been made before to crypto code that have completely compromised its security. It's definitely not NSA-proof but all the buzz about it uses that exact phrase to claim it is. Their own blog post on threat models says that it's not NSA-proof. It may be useful for you, but not if you're trying to organise a revolution.
> > ProtonMail's segregated authentication and decryption system means logging into a ProtonMail account that requires two passwords. The first password is used to authenticate the user and retrieve the correct account. After that, encrypted data is sent to the user. The second password is a decryption password which is never sent to us. It is used to decrypt the user’s data in the browser so we never have access to the decrypted data, or the decryption password. For this reason, we are also unable to do password recovery. If you forget your decryption password, we cannot recover your data. > > > [Source](https://protonmail.ch/pages/security_details.php) So it appears that a password is used to authenticate you, and a second password (which is the decryption key) is used to recover your data and display it in your browser (through HTTPS). Your second password/decryption key isn't stored in their servers, and all decryption is done locally in your system. They can't decrypt what they don't have keys to. That doesn't mean a keylogger on your system can't get the info necessary to decrypt your data, though. As for sending secure email to non-Proton users: > > Even your communication with non-ProtonMail users is secure. > > > We support sending encrypted communication to non-ProtonMail users via symmetric encryption. When you send an encrypted message to a non-ProtonMail user, they receive a link which loads the encrypted message onto their browser which they can decrypt using a decryption passphrase that you have shared with them. You can also send unencrypted messages to Gmail, Yahoo, Outlook and others, just like regular email. > > > As a personal opinion, it does look very secure. If their servers were ever seized, it appears that they wouldn't be able to do anything to unlock the data. The weakest link is the end-users, the passwords they use, and whether their passwords get compromised or not (though it looks like even if ProtonMail's password database for the first password was hacked, all the attackers would have is encrypted data, as no database is used to store the second password).
58,541
There is a service called [ProtonMail](http://protonmail.ch). It encrypts email on the client side, stores encrypted message on their servers, and then the recipient decrypts it, also on the client side and the system "doesn't store keys". My question is this: How does the decryption work? I'm a bit confused. Do I have to send my decryption key to each recipient before he can read my messages?
2014/05/22
[ "https://security.stackexchange.com/questions/58541", "https://security.stackexchange.com", "https://security.stackexchange.com/users/47094/" ]
I am Jason, one of the ProtonMail developers. Decryption uses a combination of asymmetric (RSA) and symmetric (AES) encryption. For PM to PM emails, we use an implementation of PGP where we handle the key exchange. So we have all the public keys. As for the private keys, when you create an account, it is generated on your browser, then encrypted with your mailbox password (which we do not have access to). Then the encrypted private key is pushed to the server so we can push it back to you whenever you login. So do we store your private key, yes, but since it is the encrypted private key, we don't actually have access to your key. For PM to Outside emails, encryption is optional. If you select to encrypt, we use symmetric encryption with a password that you set for that message. This password can be ANYTHING. It should NOT be your Mailbox password. You need to somehow communicate this password to the recipient. We have a couple other tricks as well for getting around the horrible performance of RSA. We will eventually write a whitepaper with full details that anybody can understand. But something like that is a week long project in itself. I apologize in advance if my answer only makes sense to crypto people.
i'm guessing they use PGP key, with one public key and one private key. They store your public key, and your private key encrypted using your password (you have to trust them to store only the encrypted private key). They have your public key, so they can encrypt any incoming mail. If you want to read your mail, once you are identified, they send you (this is transparent) the private key encrypted using your password that is decripted with your password, and you can then use this private key to decipher your emails. If this is it, seems pretty good to me.
58,541
There is a service called [ProtonMail](http://protonmail.ch). It encrypts email on the client side, stores encrypted message on their servers, and then the recipient decrypts it, also on the client side and the system "doesn't store keys". My question is this: How does the decryption work? I'm a bit confused. Do I have to send my decryption key to each recipient before he can read my messages?
2014/05/22
[ "https://security.stackexchange.com/questions/58541", "https://security.stackexchange.com", "https://security.stackexchange.com/users/47094/" ]
"ProtonMail's segregated authentication and decryption system means logging into a ProtonMail account that requires two passwords. The **first password is used to authenticate the user** and retrieve the correct account. After that, encrypted data is sent to the user. The **second password is a decryption password** which is never sent to us. [**The second password is] used to decrypt the user’s data in the browser** so we never have access to the decrypted data, or the decryption password. For this reason, we are also unable to do password recovery. If you forget your decryption password, we cannot recover your data." As a commentary to this, I would say that this would still be vulnerable to a NSA-vs-Lavabit style SSL key compromise. If you can get their SSL key, you an impersonate ProtonMail and use javascript to steal both the first and second pasword of all users. This can break the entire encryption protocol. So this way it won't be the "The Only Email System The NSA Can't Access": <http://www.forbes.com/sites/hollieslade/2014/05/19/the-only-email-system-the-nsa-cant-access/>
i'm guessing they use PGP key, with one public key and one private key. They store your public key, and your private key encrypted using your password (you have to trust them to store only the encrypted private key). They have your public key, so they can encrypt any incoming mail. If you want to read your mail, once you are identified, they send you (this is transparent) the private key encrypted using your password that is decripted with your password, and you can then use this private key to decipher your emails. If this is it, seems pretty good to me.
58,541
There is a service called [ProtonMail](http://protonmail.ch). It encrypts email on the client side, stores encrypted message on their servers, and then the recipient decrypts it, also on the client side and the system "doesn't store keys". My question is this: How does the decryption work? I'm a bit confused. Do I have to send my decryption key to each recipient before he can read my messages?
2014/05/22
[ "https://security.stackexchange.com/questions/58541", "https://security.stackexchange.com", "https://security.stackexchange.com/users/47094/" ]
**I have substantially altered this answer after the answer from Jason and an email conversation. The original is still available in the edit history.** There are two different cases here: ProtonMail-to-ProtonMail and ProtonMail-to-Other mails. For PM-to-PM emails, the system is in a position to handle public-key/private-key distribution. Since they wrote the code that generates the private keys and sends the public keys to the server and they know the recipient of the email before encrypting, they can encrypt with the recipient's public key and the recipient can decrypt with their private key. This can be transparent to the users of the system. They don't mention signing emails with your private key but this should also be equally possible and transparent. PM-to-Other emails do not use asymmetric encryption. When creating an email to a recipient who is not using ProtonMail, you generate a new password that is used to derive a symmetric key that is used to encrypt the message. You then must convey this password to your recipient using different using a different, independently secure method. Emailing your recipient the decryption key and then the encrypted email is the same as not using encryption if your threat model includes an attacker that can intercept your email. (If your threat model *doesn't* include this ability, why do you even need encrypted mail?) The mail your recipient actually receives in their mail client is not encrypted and is not your original message. It is simply a link to the ProtonMail website where they can use the password you already communicated to them to decrypt your message. In both cases, the claim is that the encryption and decryption is done using Javascript in your browser and the centralised servers only ever see encrypted data. If you have an independent, secure method of communication for the decryption password, why not just use that instead of ProtonMail? One reason might be that your independent method is not as convenient. It might be visiting the recipient in person or phoning them up. Another potential reason is for advertising or promotional purposes. If you like ProtonMail and would like your contacts to use it, emailing them from ProtonMail would promote that. But if you have a method you consider secure *and* convenient (OTR, Cryptocat, Skype, whatever you trust) then why not just use that? --- I am cautious by nature and have reservations about this service, at least until it has had its trial by fire. 1. There is no way of revoking or changing a mailbox password. [If your mailbox password ever does leak, your only recourse is to close your account an create a new one](https://protonmail.ch/pages/faq.php#faq3). Presumably, this will be much like getting a new email address is now, meaning lots of email will be delivered to your old address after you have closed it and nobody will know your new address. I expect you would also lose access all of your old email. There's no cryptographic reason why your recipients would lose access to the email you have sent them but the system may delete all email when the sender is deleted since it's all stored on their servers. 2. For non-ProtonMail users who receive lots of encrypted email from ProtonMail users, they will have to store the decryption password for every email somewhere and a mapping between them. Every individual email will require looking up and typing in a new password. I would assert this is not *usable*. 3. Making claims is easy. [Ladar Levison said that Lavabit stored no keys](http://www.thoughtcrime.org/blog/lavabit-critique/) so he could not be compelled to disclose them. [This turned out to be false](http://safegov.org/2014/1/2/lessons-from-lavabit-%E2%80%93-who-holds-the-keys). The design of ProtonMail looks significantly better but claims of "Even we can't read your mail" are still suspect until proven. 4. They omit important details from [their FAQ/instructions](https://protonmail.ch/pages/security_details.php). For instance, when claiming to be able to delete emails at a certain time, they don't mention that a user can copy that email into another program before it is deleted and the copy won't be deleted. They also omit the detail that you must find your own secure method of distributing the decryption password for PM-to-Other emails. 5. The expiry time feature references SnapChat [which infamously doesn't actually delete the images but rather just stops listing them within the app](http://www.theguardian.com/media-network/partner-zone-infosecurity/snapchat-photos-not-deleted-hidden). 6. [Some smart people also have reservations about it](https://twitter.com/hdmoore/status/467398089267871744). 7. The only metadata mentioned are IP addresses and access times. Metadata such as To: and From: addresses must be stored on their servers in an accessible format (i.e. plain text or with encryption keys available) to enable the email to be delivered to the right person. IP addresses and access times can obviously still be captured and stored by attackers. 8. The system cannot be used if you are offline. No catching up on your email during a flight or on the Underground. You don't have a copy of your email if the service shuts down. 9. Your private key is stored on the ProtonMail servers, [encrypted with AES256](https://twitter.com/ProtonMail/status/470352918600634368) using your mailbox password. This is likely so that you can use ProtonMail on a different computer and they can just push your private key to that computer for you to decrypt with your mailbox password. This is a compromise of security for usability/convenience. It's also in contradiction to the security page on the website which says that they are not sent to the server. 10. Jason's answer mentions "tricks" for improving the performance of RSA. Seemingly benign changes have been made before to crypto code that have completely compromised its security. It's definitely not NSA-proof but all the buzz about it uses that exact phrase to claim it is. Their own blog post on threat models says that it's not NSA-proof. It may be useful for you, but not if you're trying to organise a revolution.
Under the "Security" tab of their page they state: > > We support sending encrypted communication to non-ProtonMail users via symmetric encryption. When you send an encrypted message to a non-ProtonMail user, they receive a link which loads the encrypted message onto their browser which they can decrypt using a decryption passphrase that you have shared with them. > > > Looks like you have to share the decryption passphrase with the receiver first.
58,541
There is a service called [ProtonMail](http://protonmail.ch). It encrypts email on the client side, stores encrypted message on their servers, and then the recipient decrypts it, also on the client side and the system "doesn't store keys". My question is this: How does the decryption work? I'm a bit confused. Do I have to send my decryption key to each recipient before he can read my messages?
2014/05/22
[ "https://security.stackexchange.com/questions/58541", "https://security.stackexchange.com", "https://security.stackexchange.com/users/47094/" ]
I am Jason, one of the ProtonMail developers. Decryption uses a combination of asymmetric (RSA) and symmetric (AES) encryption. For PM to PM emails, we use an implementation of PGP where we handle the key exchange. So we have all the public keys. As for the private keys, when you create an account, it is generated on your browser, then encrypted with your mailbox password (which we do not have access to). Then the encrypted private key is pushed to the server so we can push it back to you whenever you login. So do we store your private key, yes, but since it is the encrypted private key, we don't actually have access to your key. For PM to Outside emails, encryption is optional. If you select to encrypt, we use symmetric encryption with a password that you set for that message. This password can be ANYTHING. It should NOT be your Mailbox password. You need to somehow communicate this password to the recipient. We have a couple other tricks as well for getting around the horrible performance of RSA. We will eventually write a whitepaper with full details that anybody can understand. But something like that is a week long project in itself. I apologize in advance if my answer only makes sense to crypto people.
"ProtonMail's segregated authentication and decryption system means logging into a ProtonMail account that requires two passwords. The **first password is used to authenticate the user** and retrieve the correct account. After that, encrypted data is sent to the user. The **second password is a decryption password** which is never sent to us. [**The second password is] used to decrypt the user’s data in the browser** so we never have access to the decrypted data, or the decryption password. For this reason, we are also unable to do password recovery. If you forget your decryption password, we cannot recover your data." As a commentary to this, I would say that this would still be vulnerable to a NSA-vs-Lavabit style SSL key compromise. If you can get their SSL key, you an impersonate ProtonMail and use javascript to steal both the first and second pasword of all users. This can break the entire encryption protocol. So this way it won't be the "The Only Email System The NSA Can't Access": <http://www.forbes.com/sites/hollieslade/2014/05/19/the-only-email-system-the-nsa-cant-access/>
58,541
There is a service called [ProtonMail](http://protonmail.ch). It encrypts email on the client side, stores encrypted message on their servers, and then the recipient decrypts it, also on the client side and the system "doesn't store keys". My question is this: How does the decryption work? I'm a bit confused. Do I have to send my decryption key to each recipient before he can read my messages?
2014/05/22
[ "https://security.stackexchange.com/questions/58541", "https://security.stackexchange.com", "https://security.stackexchange.com/users/47094/" ]
"ProtonMail's segregated authentication and decryption system means logging into a ProtonMail account that requires two passwords. The **first password is used to authenticate the user** and retrieve the correct account. After that, encrypted data is sent to the user. The **second password is a decryption password** which is never sent to us. [**The second password is] used to decrypt the user’s data in the browser** so we never have access to the decrypted data, or the decryption password. For this reason, we are also unable to do password recovery. If you forget your decryption password, we cannot recover your data." As a commentary to this, I would say that this would still be vulnerable to a NSA-vs-Lavabit style SSL key compromise. If you can get their SSL key, you an impersonate ProtonMail and use javascript to steal both the first and second pasword of all users. This can break the entire encryption protocol. So this way it won't be the "The Only Email System The NSA Can't Access": <http://www.forbes.com/sites/hollieslade/2014/05/19/the-only-email-system-the-nsa-cant-access/>
Under the "Security" tab of their page they state: > > We support sending encrypted communication to non-ProtonMail users via symmetric encryption. When you send an encrypted message to a non-ProtonMail user, they receive a link which loads the encrypted message onto their browser which they can decrypt using a decryption passphrase that you have shared with them. > > > Looks like you have to share the decryption passphrase with the receiver first.
42,185,208
Configure the text of the system : ``` func prepareTextSystem() { textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textContainer) layoutManager.delegate = self textContainer.lineFragmentPadding = 0 textContainer.lineBreakMode = lineBreakMode textContainer.maximumNumberOfLines = numberOfLines } ``` Obtained paths: ``` let glyphaRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer!) let glyphPosition = layoutManager.location(forGlyphAt: index) let lineUsedRect = layoutManager.lineFragmentUsedRect(forGlyphAt: index, effectiveRange: nil) let pointY = lineUsedRect.origin.y + glyphPosition.y if index == 0 { firstCharPath = UIBezierPath(rect: glyphaRect)//the first char Rect lineUsedRectPath = UIBezierPath(rect: lineUsedRect)//the whole lineUsedRect baseLinePath = UIBezierPath()//Baseline baseLinePath?.move(to: CGPoint.init(x: 0, y: pointY)) baseLinePath?.addLine(to: CGPoint.init(x: Screen_W, y: pointY)) setNeedsDisplay() } ``` Draw: ``` override func draw(_ rect: CGRect) { if let path = firstCharPath { path.stroke() } if let path = lineUsedRectPath { path.stroke() } if let path = baseLinePath{ path.stroke() } } ``` If the textStorage store string "Ye" ,represent like this : [![enter image description here](https://i.stack.imgur.com/COEF1.jpg)](https://i.stack.imgur.com/COEF1.jpg) If the textStorage store string "有y"(the first char is Chinese character) ,represent like this : [![enter image description here](https://i.stack.imgur.com/qvvCj.jpg)](https://i.stack.imgur.com/qvvCj.jpg) Question: 1. Why english character's top is not aligned with the line,But Chinese character's top is aligned well? 2.How can I get English character's top position?
2017/02/12
[ "https://Stackoverflow.com/questions/42185208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5773289/" ]
Have your app register to handle a URL in your manifest. Then put a link to that URL in the email. Tapping the link will then launch your app.
This is called deeplinking. You register for a URL (or many of them) in your Manifest to declare that your app will handle them. Your app will then open if the user clicks a link matching that URL.
42,185,208
Configure the text of the system : ``` func prepareTextSystem() { textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textContainer) layoutManager.delegate = self textContainer.lineFragmentPadding = 0 textContainer.lineBreakMode = lineBreakMode textContainer.maximumNumberOfLines = numberOfLines } ``` Obtained paths: ``` let glyphaRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer!) let glyphPosition = layoutManager.location(forGlyphAt: index) let lineUsedRect = layoutManager.lineFragmentUsedRect(forGlyphAt: index, effectiveRange: nil) let pointY = lineUsedRect.origin.y + glyphPosition.y if index == 0 { firstCharPath = UIBezierPath(rect: glyphaRect)//the first char Rect lineUsedRectPath = UIBezierPath(rect: lineUsedRect)//the whole lineUsedRect baseLinePath = UIBezierPath()//Baseline baseLinePath?.move(to: CGPoint.init(x: 0, y: pointY)) baseLinePath?.addLine(to: CGPoint.init(x: Screen_W, y: pointY)) setNeedsDisplay() } ``` Draw: ``` override func draw(_ rect: CGRect) { if let path = firstCharPath { path.stroke() } if let path = lineUsedRectPath { path.stroke() } if let path = baseLinePath{ path.stroke() } } ``` If the textStorage store string "Ye" ,represent like this : [![enter image description here](https://i.stack.imgur.com/COEF1.jpg)](https://i.stack.imgur.com/COEF1.jpg) If the textStorage store string "有y"(the first char is Chinese character) ,represent like this : [![enter image description here](https://i.stack.imgur.com/qvvCj.jpg)](https://i.stack.imgur.com/qvvCj.jpg) Question: 1. Why english character's top is not aligned with the line,But Chinese character's top is aligned well? 2.How can I get English character's top position?
2017/02/12
[ "https://Stackoverflow.com/questions/42185208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5773289/" ]
Have your app register to handle a URL in your manifest. Then put a link to that URL in the email. Tapping the link will then launch your app.
You have to add an Intent Filter to your activity tag in manifest to define your deep link. Look at this link: <https://developer.android.com/training/app-indexing/deep-linking.html#adding-filters> When you are done with the deep link, clicking on any link that follows host://scheme pattern, opens your app.
42,185,208
Configure the text of the system : ``` func prepareTextSystem() { textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textContainer) layoutManager.delegate = self textContainer.lineFragmentPadding = 0 textContainer.lineBreakMode = lineBreakMode textContainer.maximumNumberOfLines = numberOfLines } ``` Obtained paths: ``` let glyphaRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer!) let glyphPosition = layoutManager.location(forGlyphAt: index) let lineUsedRect = layoutManager.lineFragmentUsedRect(forGlyphAt: index, effectiveRange: nil) let pointY = lineUsedRect.origin.y + glyphPosition.y if index == 0 { firstCharPath = UIBezierPath(rect: glyphaRect)//the first char Rect lineUsedRectPath = UIBezierPath(rect: lineUsedRect)//the whole lineUsedRect baseLinePath = UIBezierPath()//Baseline baseLinePath?.move(to: CGPoint.init(x: 0, y: pointY)) baseLinePath?.addLine(to: CGPoint.init(x: Screen_W, y: pointY)) setNeedsDisplay() } ``` Draw: ``` override func draw(_ rect: CGRect) { if let path = firstCharPath { path.stroke() } if let path = lineUsedRectPath { path.stroke() } if let path = baseLinePath{ path.stroke() } } ``` If the textStorage store string "Ye" ,represent like this : [![enter image description here](https://i.stack.imgur.com/COEF1.jpg)](https://i.stack.imgur.com/COEF1.jpg) If the textStorage store string "有y"(the first char is Chinese character) ,represent like this : [![enter image description here](https://i.stack.imgur.com/qvvCj.jpg)](https://i.stack.imgur.com/qvvCj.jpg) Question: 1. Why english character's top is not aligned with the line,But Chinese character's top is aligned well? 2.How can I get English character's top position?
2017/02/12
[ "https://Stackoverflow.com/questions/42185208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5773289/" ]
This is called deeplinking. You register for a URL (or many of them) in your Manifest to declare that your app will handle them. Your app will then open if the user clicks a link matching that URL.
You have to add an Intent Filter to your activity tag in manifest to define your deep link. Look at this link: <https://developer.android.com/training/app-indexing/deep-linking.html#adding-filters> When you are done with the deep link, clicking on any link that follows host://scheme pattern, opens your app.
49,154
I am trying to build something similar to planning poker and am very new to Knockout and was wondering if anyone could help me improve on my very crude start? This is what I have so far: HTML Selected Card CSS ``` .profile { width: 50px; height: 80px; color: #FFF; background: black; border: 1px solid #FFF; float: left; line-height:80px } .highlight { background: yellow !important; border:1px solid #000; color: black; } ``` JavaScript/Knockout ``` function Step(number) { this.active = ko.observable(false); this.name = ko.observable( number); } var model = function () { var items = ko.observableArray([new Step(1), new Step(2), new Step(3), new Step(5),new Step(8),new Step(13),new Step(20),new Step(40),new Step(100)]); var selectedItems = ko.computed(function () { return _.filter(items(), function (item) { return item.active(); }); }) var clicked = function (item) { items().forEach(function(item){ item.active(false) }); item.active(!this.active()); }; var save = function () { alert("sending items \n" + ko.toJSON(selectedItems())); } return { items: items, selectedItems: selectedItems, save: save, clicked: clicked } } ko.applyBindings(model); ``` <http://jsfiddle.net/grahamwalsh/63yeD/>
2014/05/07
[ "https://codereview.stackexchange.com/questions/49154", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/42051/" ]
You are using function as definition for model and inside that function you are defined an interface to have access to those properties/methods. In complicated cases you would have inflexible usage between definition and public interface. Better solution would be to create definition for the class like this ``` var Model = function () { var self = this; self.selectedItems = ko.computed(function () { return _.filter(items(), function (item) { return item.active(); }); }) } ``` and then create an instance of it ``` var model = new Model(); ``` because a **new** operator you will create new JS object and this object will be send as scope for current **this** content. This is commonly used patterns in order to follow OOJ see link here <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript>
A surprisingly good start, most knockout code looks terrible to me, but I can follow this, it's well laid out, JsHint has nothing to complain about. Only this bothered me: ``` var items = ko.observableArray([new Step(1), new Step(2), new Step(3), new Step(5),new Step(8),new Step(13),new Step(20),new Step(40),new Step(100)]); ``` I would have approached that a little differently: ``` var steps = [1,2,3,5,8,13,20,40,100]; for ( var i = 0 ; i < steps.length ; i++ ) steps[i] = new Step( steps[i] ); var items = ko.observableArray( steps ) ``` What this does is more clearly show the different steps from 1-> 100, and take out the repetition in your code of calling `new Step` for every single step.
49,154
I am trying to build something similar to planning poker and am very new to Knockout and was wondering if anyone could help me improve on my very crude start? This is what I have so far: HTML Selected Card CSS ``` .profile { width: 50px; height: 80px; color: #FFF; background: black; border: 1px solid #FFF; float: left; line-height:80px } .highlight { background: yellow !important; border:1px solid #000; color: black; } ``` JavaScript/Knockout ``` function Step(number) { this.active = ko.observable(false); this.name = ko.observable( number); } var model = function () { var items = ko.observableArray([new Step(1), new Step(2), new Step(3), new Step(5),new Step(8),new Step(13),new Step(20),new Step(40),new Step(100)]); var selectedItems = ko.computed(function () { return _.filter(items(), function (item) { return item.active(); }); }) var clicked = function (item) { items().forEach(function(item){ item.active(false) }); item.active(!this.active()); }; var save = function () { alert("sending items \n" + ko.toJSON(selectedItems())); } return { items: items, selectedItems: selectedItems, save: save, clicked: clicked } } ko.applyBindings(model); ``` <http://jsfiddle.net/grahamwalsh/63yeD/>
2014/05/07
[ "https://codereview.stackexchange.com/questions/49154", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/42051/" ]
You are using function as definition for model and inside that function you are defined an interface to have access to those properties/methods. In complicated cases you would have inflexible usage between definition and public interface. Better solution would be to create definition for the class like this ``` var Model = function () { var self = this; self.selectedItems = ko.computed(function () { return _.filter(items(), function (item) { return item.active(); }); }) } ``` and then create an instance of it ``` var model = new Model(); ``` because a **new** operator you will create new JS object and this object will be send as scope for current **this** content. This is commonly used patterns in order to follow OOJ see link here <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript>
I'm only going to focus on this piece of code since I'm not a knockout expert: ``` var selectedItems = ko.computed(function () { return _.filter(items(), function (item) { return item.active(); }); }) ``` First of all I would call this variable `selectedItem` since you can only have one and not multiple selected items. Secondly `UnderscoreJS` provides you a function called `find`. It's in my opinion more clear to use this function instead of filter because `filter` can return multiple results. ``` var selectedItem = ko.computed(function () { return _.find(items(), function (item) { return item.active(); }); }) ``` Another small remark, add semicolons after your statements. Consider the following: ``` var save = function() { } // Another developer adds an anonymous function after your save function. // This will break your code (function() { })(); ``` It won't break your code if you add semicolons: ``` var save = function() { }; (function() { // This will work })(); ``` This is not necessary if you define a function as follows: ``` function save() { } (function() { // This will also work })(); ```
25,449,594
I have a odd error happening when I upgraded spring-data-mongo from 1.3.2.RELEASE to 1.5.2.RELEASE I have an object that looks something like this: ``` @Document(collection = "foos") public class Foo { @Id private String id; private GeoPoint[] tracks; } public class GeoPoint { GeoPointValue[] points; } public class GeoPointValue { @Field(value = "0") double lon; @Field(value = "1") double lat; @Field(value = "2") double value; } ``` I have a test tat creates one of these objects, saves it, then reloads it. When it saves it looks like this: ``` { "_class" : "com.Foo", "_id" : ObjectId("53f6630df91f68368b17da91"), "tracks" : [ { "points" : [ [ 0, 0, 999.9000244140625 ], [ 1.8605, -7.6815, 1 ], [ 1.0885, -0.0001, 1 ] ] }, { "points" : [ [ -0.0001581075944187447, -0.003384031509668049, 999.9000244140625 ], [ -0.0003763519887295627, -0.003578620265780311, 1 ], [ -0.0006024558351500737, -0.003581886877337006, 1 ] ] } ], "version" : 0 } ``` but when it reloads I get the following exception which I have traced to the points array: ``` java.lang.IllegalArgumentException: Given DBObject must be a BasicDBObject! Object of class [com.mongodb.BasicDBList] must be an instance of class com.mongodb.BasicDBObject at org.springframework.util.Assert.isInstanceOf(Assert.java:337) at org.springframework.data.mongodb.core.convert.DBObjectAccessor.<init>(DBObjectAccessor.java:47) at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.<init>(MappingMongoConverter.java:1046) at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getParameterProvider(MappingMongoConverter.java:230) at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:242) ```
2014/08/22
[ "https://Stackoverflow.com/questions/25449594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/154477/" ]
For `spring-data-mongodb`, `GeoPointValue` is a Map structure, so what it expects is `BasicDBObject` type - `BasicDBList` is for List structure, this is the reason for the exception, I think. You can try to change values of @Field in `GeoPointValue` from **"0", "1", "2"** to **"a", "b", "c"**, maybe the exception will disappear. I feel weird that `"points"` value is **[ [ ],[ ],[ ] ]**, it should be **[ { }, { }, { } ]**. You can revert the `mongo-java-driver` from 2.12.3 to 2.11.3, if the `points` value is **[ { }, { }, { } ]** after saving, then maybe the driver make some special treatment for **Number Key** but `spring-data-mongodb` hasn't caught it up yet.
I had The Same Problem and I Solved it By Adding @DBRef to the field
24,109,930
I have a UICollectionView that has elements that can be dragged and dropped around the screen. I use a UILongPressGestureRecognizer to handle the dragging. I attach this recognizer to the collection view cells in my `collectionView:cellForItemAtIndexPath:` method. However, the recognizer's view property occasionally returns a `UIView` instead of a `UICollectionViewCell`. I require some of the methods/properties that are only on UICollectionViewCell and my app crashes when a UIView is returned instead. Why would the recognizer that is attached to a cell return a plain UIView? ### Attaching the recognizer ``` - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { EXSupplyCollectionViewCell *cell = (EXSupplyCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:cell action:nil]; longPressRecognizer.delegate = self; [cell addGestureRecognizer:longPressRecognizer]; return cell; } ``` ### Handling the gesture I use a method with a switch statement to dispatch the different states of the long press. ``` - (void)longGestureAction:(UILongPressGestureRecognizer *)gesture { UICollectionViewCell *cell = (UICollectionViewCell *)[gesture view]; switch ([gesture state]) { case UIGestureRecognizerStateBegan: [self longGestureActionBeganOn:cell withGesture:gesture]; break; //snip default: break; } } ``` When `longGestureActionBeganOn:withGesture` is called if `cell` is actually a `UICollectionViewCell` the rest of the gesture executes perfectly. If it isn't then it breaks when it attempts to determine the index path for what should be a cell. ### First occurrence of break ``` - (void)longGestureActionBeganOn:(UICollectionViewCell *)cell withGesture:(UILongPressGestureRecognizer *)gesture { NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell]; // unrecognized selector is sent to the cell here if it is a UIView [self.collectionView setScrollEnabled:NO]; if (indexPath != nil) { // snip } } ``` I also use other properties specific to UICollectionViewCell for other states of the gesture. Is there some way to guarantee that the recognizer will always give me back the view that I assigned it to?
2014/06/08
[ "https://Stackoverflow.com/questions/24109930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1457603/" ]
Views like UICollectionView and UITableView will reuse their cells. If you blindly add a gestureRecognizer in `collectionView:cellForItemAtIndexPath:` you will add a new one each time the cell is reloaded. If you scroll around a bit you will end up with dozens of gestureRecognizers on each cell. In theory this should not cause any problems besides that the action of the gestureRecognizer is called multiple times. But Apple uses heavy performance optimization on cell reuse, so it might be possible that something messes up something. The preferred way to solve the problem is to [add the gestureRecognizer to the collectionView](https://stackoverflow.com/questions/18848725/long-press-gesture-on-uicollectionviewcell/18848817#18848817) instead. Another way would be to check if there is already a gestureRecognizer on the cell and only add a new one if there is none. Or you use the solution you found and remove the gestureRecognizer in `prepareForReuse` of the cell. When you use the latter methods you should check that you remove (or test for) the right one. You don't want to remove gestureRecognizers the system added for you. (I'm not sure if iOS currently uses this, but to make your app proof for the future you might want to stick to this best practice.)
I had a similar problem related to Long-Touch. What I ended up doing is override the UICollectionViewCell.PrepareForReuse and cancel the UIGestureRecognizers attached to my view. So everytime my cell got recycled a long press event would be canceled. [See this answer](https://stackoverflow.com/questions/3937831/how-can-i-tell-a-uigesturerecognizer-to-cancel-an-existing-touch)
61,274,195
How to use an `onClick` event to stop a recurring function call? The function call is recurring due to using `useEffect`, `setInterval` and `clearInterval`. An example shown in [this article](https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks), the below code will run forever. How to stop the function from being called once the `<header></header>` is clicked? ``` import React, { useState, useEffect } from 'react'; const IntervalExample = () => { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => { setSeconds(seconds => seconds + 1); }, 1000); return () => clearInterval(interval); }, []); return ( <div className="App"> <header className="App-header"> {seconds} seconds have elapsed since mounting. </header> </div> ); }; export default IntervalExample; ```
2020/04/17
[ "https://Stackoverflow.com/questions/61274195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4605629/" ]
the question is - what you want to test. is it a unit test or an e2e test? if it's a unit test - mock reactive forms, cover only your logic, then you don't have an issue with `valueChanges`, because it's mocked and you control it. if it's an e2e test - you shouldn't reassign `valueChanges`. Nothing should be mocked / replaced, because it's an e2e test. Nevertheless if you want to change `valueChanges` - use <https://github.com/krzkaczor/ts-essentials#writable> ```js (Writable<typeof component.formField>component.formField).valueChanges = fakeInputs; ``` It will make the property type writable. If it's a unit test, personally, I would vote to mock the reactive form, because in a unit test we need to test only our unit, its dependencies should be mocked / stubbed. **Injection of parts we want to mock** As an option you can move the form as a dependency of your component to providers in the component declarations. ```js @Component({ selector: 'app-component', templateUrl: './app-component.html', styleUrls: ['./app-component.scss'], providers: [ { provide: 'form', useFactory: () => new FormControl(), }, ], }) export class AppComponent { public formFieldChanged$: Observable<unknown>; constructor(@Inject('form') public readonly formField: FormControl) { } public setupObservables(): void { this.formFieldChanged$ = this.formField .valueChanges .pipe( debounceTime(100), distinctUntilChanged((a, b) => a === b), ); } } ``` Then you can simply inject a mock instead of it in a test. ```js it('should update value on debounced formField change', marbles(m => { const values = { a: "1", b: "2", c: "3" }; const fakeInputs = m.cold('a 200ms b 50ms c', values); const expected = m.cold('100ms a 250ms c', values); const formInput = { valueChanges: fakeInputs, }; const component = new AppComponent(formInput as any as FormControl); component.setupObservables(); m.expect(component.formFieldChanged$).toBeObservable(expected); })); ```
Using properties instead of fields is a much cleaner solution. ``` get formFieldChanged$() { return this._formFieldChanged$; } private _formFieldChanged$: Observable<string>; ... public setupObservables() { this._formFieldChanged$ = this.formField .valueChanges .pipe( debounceTime(100), distinctUntilChanged((a, b) => a === b), ) } ``` `spyOnProperty` does the magic here, `setupObservables()` is no longer needed: ``` it('should update value on debounced formField change', marbles(m => { const values = { a: "1", b: "2", c: "3" }; const fakeInputs = m.cold('a 200ms b 50ms c', values); const expected = m.cold('100ms a 250ms c', values); spyOnProperty(component, 'formFieldChanged$').and.returnValue(fakeInputs); m.expect(component.formFieldChanged$).toBeObservable(expected); })); ```
60,017,424
I am implementing linked list in java, but my code neither gives any error nor produces any output. ``` class LinkedList25 { Node head; class Node { int data; Node next; Node(int value) { data = value; next = null; } } public static void main(String args[]) { LinkedList25 list = new LinkedList25(); boolean choice = true; list.insertNode(1,list.head); list.insertNode(2,list.head); list.insertNode(3,list.head); list.printList(list.head); } public void insertNode(int value,Node move) { Node temp = new Node(value); temp.next = move; move = temp; } public void printList(Node move) { while(move!=null) { System.out.print(move.data+"->"); } } } ```
2020/02/01
[ "https://Stackoverflow.com/questions/60017424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8530270/" ]
The problem is in the view. In class based view you need to defined each method individually. In your code is only the GET method. You need another function for the POST method.
The problem is in your urls pattern **urls.py** ``` from django.conf.urls import url urlpatterns = [ url(r'^profile/(?P<your_variable_name>\d+)/$', login_required(UserUpdateView.as_view()), name='profile'), ] ``` Note: You may get arguments error in your view, so you may use ``` def your_view(request, your_argument): ```
60,017,424
I am implementing linked list in java, but my code neither gives any error nor produces any output. ``` class LinkedList25 { Node head; class Node { int data; Node next; Node(int value) { data = value; next = null; } } public static void main(String args[]) { LinkedList25 list = new LinkedList25(); boolean choice = true; list.insertNode(1,list.head); list.insertNode(2,list.head); list.insertNode(3,list.head); list.printList(list.head); } public void insertNode(int value,Node move) { Node temp = new Node(value); temp.next = move; move = temp; } public void printList(Node move) { while(move!=null) { System.out.print(move.data+"->"); } } } ```
2020/02/01
[ "https://Stackoverflow.com/questions/60017424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8530270/" ]
I assume your urls.py is not in the Django project directory but rather in one of your app directory thereby including the app\_name before the url\_patterns. Can you please share your directory structure?
The problem is in your urls pattern **urls.py** ``` from django.conf.urls import url urlpatterns = [ url(r'^profile/(?P<your_variable_name>\d+)/$', login_required(UserUpdateView.as_view()), name='profile'), ] ``` Note: You may get arguments error in your view, so you may use ``` def your_view(request, your_argument): ```
60,017,424
I am implementing linked list in java, but my code neither gives any error nor produces any output. ``` class LinkedList25 { Node head; class Node { int data; Node next; Node(int value) { data = value; next = null; } } public static void main(String args[]) { LinkedList25 list = new LinkedList25(); boolean choice = true; list.insertNode(1,list.head); list.insertNode(2,list.head); list.insertNode(3,list.head); list.printList(list.head); } public void insertNode(int value,Node move) { Node temp = new Node(value); temp.next = move; move = temp; } public void printList(Node move) { while(move!=null) { System.out.print(move.data+"->"); } } } ```
2020/02/01
[ "https://Stackoverflow.com/questions/60017424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8530270/" ]
For post request in UpdateView, you need to create `post` method. Something like this will work: ``` class UserUpdateView(UpdateView): model = user_content template_name = 'users/profile.html' model_words = single_words_cards # Get Method def get(self, request, *args, **kwargs): model = user_content model_words = single_words_cards template_name = 'users/profile.html' user_id_fk = request.user.id #Querysets user_sentances = model.objects.filter(show_sentance = True).values('sentance_eng', 'sentance_esp', 'id', 'username_id', 'show_sentance').filter(username_id = user_id_fk) zip_flash_sentances = model.objects.filter(show_sentance=True).order_by("?").filter(username_id = user_id_fk).values_list('sentance_eng', 'sentance_esp', 'id').first() number_sentances_today = model.objects.filter(show_sentance=True).values_list('sentance_eng').filter(username_id = user_id_fk).count() word_cards_esp = list(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk)) word_cards_eng = list(model_words.objects.filter(show_word=True).values_list('word_eng').filter(username_id = user_id_fk)) number_of_cards = len(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk)) value = random.randint(0,number_of_cards)-1 words_esp = word_cards_esp[value] words_eng = word_cards_eng[value] return render(request, template_name, {'sentances_list': user_sentances, 'zip_flash_sentances':zip_flash_sentances, 'words_esp':words_esp, 'words_eng':words_eng, 'number_sentances_today':number_sentances_today, 'number_of_cards':number_of_cards, 'user_id_fk': user_id_fk, }) # Post Method def post(self, request, *args, **kwargs): model = user_content model_words = single_words_cards template_name = 'users/profile.html' user_id_fk = request.user.id if request.GET.get('hard') == 'hard': print('hard was found') else: print('nothing') hide = model.objects.filter(show_sentance = True).values('sentance_eng').filter(id=query) model.objects.filter(id=retire).update(show_sentance='False') print(retire ) # Process your request ```
The problem is in your urls pattern **urls.py** ``` from django.conf.urls import url urlpatterns = [ url(r'^profile/(?P<your_variable_name>\d+)/$', login_required(UserUpdateView.as_view()), name='profile'), ] ``` Note: You may get arguments error in your view, so you may use ``` def your_view(request, your_argument): ```
60,017,424
I am implementing linked list in java, but my code neither gives any error nor produces any output. ``` class LinkedList25 { Node head; class Node { int data; Node next; Node(int value) { data = value; next = null; } } public static void main(String args[]) { LinkedList25 list = new LinkedList25(); boolean choice = true; list.insertNode(1,list.head); list.insertNode(2,list.head); list.insertNode(3,list.head); list.printList(list.head); } public void insertNode(int value,Node move) { Node temp = new Node(value); temp.next = move; move = temp; } public void printList(Node move) { while(move!=null) { System.out.print(move.data+"->"); } } } ```
2020/02/01
[ "https://Stackoverflow.com/questions/60017424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8530270/" ]
For post request in UpdateView, you need to create `post` method. Something like this will work: ``` class UserUpdateView(UpdateView): model = user_content template_name = 'users/profile.html' model_words = single_words_cards # Get Method def get(self, request, *args, **kwargs): model = user_content model_words = single_words_cards template_name = 'users/profile.html' user_id_fk = request.user.id #Querysets user_sentances = model.objects.filter(show_sentance = True).values('sentance_eng', 'sentance_esp', 'id', 'username_id', 'show_sentance').filter(username_id = user_id_fk) zip_flash_sentances = model.objects.filter(show_sentance=True).order_by("?").filter(username_id = user_id_fk).values_list('sentance_eng', 'sentance_esp', 'id').first() number_sentances_today = model.objects.filter(show_sentance=True).values_list('sentance_eng').filter(username_id = user_id_fk).count() word_cards_esp = list(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk)) word_cards_eng = list(model_words.objects.filter(show_word=True).values_list('word_eng').filter(username_id = user_id_fk)) number_of_cards = len(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk)) value = random.randint(0,number_of_cards)-1 words_esp = word_cards_esp[value] words_eng = word_cards_eng[value] return render(request, template_name, {'sentances_list': user_sentances, 'zip_flash_sentances':zip_flash_sentances, 'words_esp':words_esp, 'words_eng':words_eng, 'number_sentances_today':number_sentances_today, 'number_of_cards':number_of_cards, 'user_id_fk': user_id_fk, }) # Post Method def post(self, request, *args, **kwargs): model = user_content model_words = single_words_cards template_name = 'users/profile.html' user_id_fk = request.user.id if request.GET.get('hard') == 'hard': print('hard was found') else: print('nothing') hide = model.objects.filter(show_sentance = True).values('sentance_eng').filter(id=query) model.objects.filter(id=retire).update(show_sentance='False') print(retire ) # Process your request ```
The problem is in the view. In class based view you need to defined each method individually. In your code is only the GET method. You need another function for the POST method.
60,017,424
I am implementing linked list in java, but my code neither gives any error nor produces any output. ``` class LinkedList25 { Node head; class Node { int data; Node next; Node(int value) { data = value; next = null; } } public static void main(String args[]) { LinkedList25 list = new LinkedList25(); boolean choice = true; list.insertNode(1,list.head); list.insertNode(2,list.head); list.insertNode(3,list.head); list.printList(list.head); } public void insertNode(int value,Node move) { Node temp = new Node(value); temp.next = move; move = temp; } public void printList(Node move) { while(move!=null) { System.out.print(move.data+"->"); } } } ```
2020/02/01
[ "https://Stackoverflow.com/questions/60017424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8530270/" ]
For post request in UpdateView, you need to create `post` method. Something like this will work: ``` class UserUpdateView(UpdateView): model = user_content template_name = 'users/profile.html' model_words = single_words_cards # Get Method def get(self, request, *args, **kwargs): model = user_content model_words = single_words_cards template_name = 'users/profile.html' user_id_fk = request.user.id #Querysets user_sentances = model.objects.filter(show_sentance = True).values('sentance_eng', 'sentance_esp', 'id', 'username_id', 'show_sentance').filter(username_id = user_id_fk) zip_flash_sentances = model.objects.filter(show_sentance=True).order_by("?").filter(username_id = user_id_fk).values_list('sentance_eng', 'sentance_esp', 'id').first() number_sentances_today = model.objects.filter(show_sentance=True).values_list('sentance_eng').filter(username_id = user_id_fk).count() word_cards_esp = list(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk)) word_cards_eng = list(model_words.objects.filter(show_word=True).values_list('word_eng').filter(username_id = user_id_fk)) number_of_cards = len(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk)) value = random.randint(0,number_of_cards)-1 words_esp = word_cards_esp[value] words_eng = word_cards_eng[value] return render(request, template_name, {'sentances_list': user_sentances, 'zip_flash_sentances':zip_flash_sentances, 'words_esp':words_esp, 'words_eng':words_eng, 'number_sentances_today':number_sentances_today, 'number_of_cards':number_of_cards, 'user_id_fk': user_id_fk, }) # Post Method def post(self, request, *args, **kwargs): model = user_content model_words = single_words_cards template_name = 'users/profile.html' user_id_fk = request.user.id if request.GET.get('hard') == 'hard': print('hard was found') else: print('nothing') hide = model.objects.filter(show_sentance = True).values('sentance_eng').filter(id=query) model.objects.filter(id=retire).update(show_sentance='False') print(retire ) # Process your request ```
I assume your urls.py is not in the Django project directory but rather in one of your app directory thereby including the app\_name before the url\_patterns. Can you please share your directory structure?
51,221
I am a complete newbie in **Selenium** and test automation. What is a general structure of `Java` **Automation Test**, using a Behavior-Driven Development (BDD) framework in `Cucumber`. Additionally, could you explain the **Automation Framework** (AF)'s components ? Could you also share an overview *example* of implementing a test class (and its utilities), which is used in the Tech. industry? Your help is greatly appreciated. Hope that helps
2023/02/07
[ "https://sqa.stackexchange.com/questions/51221", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/55423/" ]
There is no such thing as "general structure for any framework". Frameworks are meant to be custom made as per the type/or need of the project. Having said that, I think I understand what you are looking for. Follow the you-tube tutorial series in link below for the framework implementation using selenium(java binding) and BDD(cucumber) framework. This guy has explained it really well. I suggest, after watching the video, download the source code from git and try to implement in your local setup. Good luck. [Link here](https://www.youtube.com/watch?v=vHzMJuc9Zuk)
When creating a Test Automation Framework, we should consider the following main points: * To be able to create automated tests quickly by using appropriate abstraction layers * The framework should have meaningful logging and reporting structure Should be easily maintainable and extendable * Should be simple enough for testers to write automated tests A retry mechanism to rerun failed tests * This is especially useful for WebDriver UI tests * Framework structure could be like below: [![enter image description here](https://i.stack.imgur.com/nRbI5.png)](https://i.stack.imgur.com/nRbI5.png) I borrow details from [here](https://artoftesting.com/selenium-java-automation-framework)
98,085
I'm trying to wrap my head around making shaders but I have no real coding experience. I've tried looking for a solution to my problem but I haven't found anything. Maybe I'm not phrasing it right? The problem is this: I have a script that looks like this, which takes a texture with values in a certain range and then changes the range of the values while keeping their relative positions. ``` shader Exp_Shader( float tex = 0, float OldMax = 1, float OldMin = 0, float NewMax = 1, float NewMin = 0, output float Result = 0, ) { Result = (((tex - OldMin)*(NewMax-NewMin))/(OldMax-OldMin)) + NewMin; } ``` The problem is, that this works on greyscale textures but not on color. How can I add a color input and output to make this work?
2018/01/08
[ "https://blender.stackexchange.com/questions/98085", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/35383/" ]
In OSL, you can use color as type of parameter. For example see here your script. I changed the tex parameter and the Result parameter ``` shader Exp_Shader( color tex = 0, float OldMax = 1, float OldMin = 0, float NewMax = 1, float NewMin = 0, output color Result = 0, ) { Result = (((tex - OldMin)*(NewMax-NewMin))/(OldMax-OldMin)) + NewMin; } ``` After doing this and pressing the refresh button the Script node will look like this: [![enter image description here](https://i.stack.imgur.com/8mk9i.png)](https://i.stack.imgur.com/8mk9i.png) Hope this answers your question.
@J.Bakker's answer is perfectly good .. but just for completeness.. There are a number of ways of constructing a `color` in OSL, including these examples given in the [Language Specification](https://github.com/imageworks/OpenShadingLanguage/blob/master/src/doc/osl-languagespec.pdf): ``` color (0, 0, 0) // black color ("rgb", .75, .5, .5) // pinkish color ("hsv", .2, .5, .63) // specify in "hsv" space color (0.5) // same as color (0.5, 0.5, 0.5) ``` (see the rest of the `color` section for the complete list)
4,419,761
How to find the probability density function of the random variable $\frac{1}{X}$? Let $X$ be a random variable with pdf $f\_X(x)= \begin{cases} 0 ; x \le 0 \\ \frac{1}{2} ; 0 < x \le 1 \\ \frac{1}{2x^2} ; 1 < x < \infty \end{cases}$ I was trying to avoid using formula. So we see that $P(Y \le y) = 1 - P(X \le y)$ Case$1$: if $y \le 0$ Then $F(y) = 1 - P[X \le y] = 1$ Case $2:$ if $0 < y \le 1$ Then $F(y) = 1 - P(X \le y) = 1 - (0 + \int\_{0}^{y}\frac{1}{2}dy) = 1-\frac{y}{2}$ Case $3:$ if $1 < y < \infty$ Then $F(y) = 1 - P(X \le y) = 1 - (\frac{1}{2} + \int\_{1}^{y}\frac{1}{y^2}dy) = \frac{1}{2}+\frac{1}{y}-1$ Then on differentiating we can get the probability density function. I thibk that the distribution function that i got is not correct . Can someone help me out please
2022/04/04
[ "https://math.stackexchange.com/questions/4419761", "https://math.stackexchange.com", "https://math.stackexchange.com/users/919818/" ]
The PDF of $X$ is given by $$ f\_X(x) = \left\{ \begin{array}{ccc} 0 & \mbox{if} & x \leq 0 \\[2mm] {1 \over 2} & \mbox{if} & 0 < x < 1 \\[2mm] {1 \over 2 x^2} & \mbox{if} & 1 < x < \infty \\[2mm] \end{array} \right. \tag{1} $$ Thus, $X$ is a positive random variable. Since $Y = {1 \over X}$, it is immediate that $Y$ is also a positive random variable. Hence, $$ F\_Y(y)= P(Y \leq y) = 0 \ \ \mbox{for} \ \ y < 0. \tag{2} $$ Fix $y$ in the interval $0 < y < 1$. Then ${1 \over y} > 1$. Now, we find that $$ F\_Y(y) = P(Y \leq y) = P\left( {1 \over X} \leq y \right) = P\left( X \geq {1 \over y} \right) $$ which can be evaluated using (1) as $$ F\_Y(y) = \int\limits\_{1 \over y}^\infty \ {1 \over 2 x^2} \ dx = {1 \over 2} \ \left[ - {1 \over x} \right]\_{1 \over y}^\infty $$ or $$ F\_Y(y) = {1 \over 2} \ \left[ 0 + y \right] = {y \over 2} $$ Thus, $$ F\_Y(y) = {y \over 2} \ \ \mbox{for} \ \ 0 < y < 1. \tag{3} $$ Next, we fix in the interval $y > 1$. Then it follows that $0 < {1 \over y} < 1$. Now, $$ F\_Y(y) = P(Y \leq y) = P\left( {1 \over X} \leq y \right) = P\left( X \geq {1 \over y} \right) = 1 - P\left( X \leq {1 \over y} \right) $$ which can be evaluated using (1) as $$ F\_Y(y) = 1 - \int\limits\_{0}^{1 \over y} \ {1 \over 2} \ dx = 1 - {1 \over 2} \left[ {1 \over y} - 0 \right] = 1 - {1 \over 2 y}. $$ Thus, $$ F\_Y(y) = 1 - {1 \over 2 y} \ \ \mbox{for} \ \ y > 1 \tag{4} $$ Combining the three cases, we find that $$ F\_Y(y) = \left\{ \begin{array}{ccc} 0 & \mbox{if} & y \leq 0 \\[2mm] {y \over 2} & \mbox{if} & 0 < y < 1 \\[2mm] 1 - {1 \over 2 y} & \mbox{if} & y > 1 \\[2mm] \end{array} \right. \tag{5} $$ From (5), we find the PDF of $Y = {1 \over X}$ as $$ f\_Y(y) = F\_Y'(y) = \left\{ \begin{array}{ccc} 0 & \mbox{if} & y \leq 0 \\[2mm] {1 \over 2} & \mbox{if} & 0 < y < 1 \\[2mm] {1 \over 2 y^2} & \mbox{if} & y > 1 \\[2mm] \end{array} \right. \tag{6} $$
$X$ is a positive r.v. and so is $Y$. Hence, $P(Y\leq y)=0$ for $y \leq 0$. Also, $P(Y \leq y)=\frac y 2$ for $0<y \leq 1$ and $P(Y \leq y)=1-\frac 1 {2y}$ for $y >1$. [For $0<y\leq 1$ we have $P(Y \leq y)=P(\frac 1 X \leq y)=P(X\geq \frac 1 y)=\int\_{1/y}^{\infty} \frac 1 {2x^{2}}dx=\frac y 2$. I will leave the case $y>1$ to you].
15,557,739
``` Private Sub cmdAdd_Click() 'add data to table CurrentDb.Execute = "INSERT INTO jscbb_dir2(ID,Lastname,FirstName, PrimA, Artea,LubNum,OfficeNum,OfficePhone,Email,LabPhone,stats)" & _ " VALUES(" & Me.Textid & ",'" & Me.TextLast & "','" & Me.TextFirst & "','" & Me.Textprima & "','" & Me.Textarea & "','" & Me.Textlabnum & _ "','" & Me.Textofficenum & "','" & Me.Textofficephone & "','" & Me.Textemail & "','" & Me.Textlabphone & "','" & Me.Textstatus & "')" 'refresh data is list on focus jscbb_dirsub.Form.Requery End Sub ``` Why am I getting an error on the last (Me.Textstatus)? I know this is a low-level question, but I need another pair of eyes, I've been looking at this for over an hour. The error is "Compile Error: Argument Not Optional"
2013/03/21
[ "https://Stackoverflow.com/questions/15557739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2027275/" ]
Consider parameters, they will be easier to debug. ``` Dim qdf As QueryDef ssql = "INSERT INTO jscbb_dir2(ID,Lastname,FirstName,PrimA,Artea," _ & "LubNum,OfficeNum,OfficePhone,Email,LabPhone,stats) " _ & "VALUES([id],[last],[first],[prima],[area],[lab]," _ & "[office],[phone],[email],[stat])" Set qdf = CurrentDb.CreateQueryDef("", ssql) qdf.Parameters("id") = Me.TextID qdf.Parameters("last") = Me.Textlast qdf.Parameters("first") = Me.Textfirst qdf.Parameters("prima") = Me.Textprima qdf.Parameters("area") = Me.Textarea qdf.Parameters("lab") = Me.Textlabnum qdf.Parameters("office") = Me.Textofficenumbet qdf.Parameters("phone") = Me.Textofficephone qdf.Parameters("email") = Me.Textemail qdf.Parameters("stat") = Me.Textstatus qdf.Execute dbFailOnError ```
[`Execute`](http://msdn.microsoft.com/en-us/library/bb243015%28v=office.12%29.aspx) is a method, not a property. You don't use `=` between a method and its arguments, so ``` CurrentDb.Execute = "..." ``` should be ``` CurrentDb.Execute "..." ```
1,510,575
Is there a RSS library for .NET?
2009/10/02
[ "https://Stackoverflow.com/questions/1510575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183229/" ]
You might start with the [System.ServiceModel.Syndication Namespace](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx). It includes classes for RSS and Atom.
According to [Google](http://www.google.nl/search?q=rss+library+.net), there are a few options: * [RSS.NET](http://www.rssdotnet.com/) - with an updated version [over here](http://www.web20tools.net/) * [FeedDotNet](http://www.codeplex.com/FeedDotNet/) Also, many commercial networking toolkits for .NET (e.g. /n Software's [IP\*Works!](http://nsoftware.com/portal/dotnet/)) support RSS. In addition to that, the [RSS protocol](http://www.rssboard.org/rss-specification) itself isn't too involved: using .NET's native [HttpClient](http://msdn.microsoft.com/en-us/library/f3wxbf3f%28VS.80%29.aspx) and some LINQ to XML magic, it [should not be too difficult](http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx) to implement a RSS client yourself...
1,510,575
Is there a RSS library for .NET?
2009/10/02
[ "https://Stackoverflow.com/questions/1510575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183229/" ]
According to [Google](http://www.google.nl/search?q=rss+library+.net), there are a few options: * [RSS.NET](http://www.rssdotnet.com/) - with an updated version [over here](http://www.web20tools.net/) * [FeedDotNet](http://www.codeplex.com/FeedDotNet/) Also, many commercial networking toolkits for .NET (e.g. /n Software's [IP\*Works!](http://nsoftware.com/portal/dotnet/)) support RSS. In addition to that, the [RSS protocol](http://www.rssboard.org/rss-specification) itself isn't too involved: using .NET's native [HttpClient](http://msdn.microsoft.com/en-us/library/f3wxbf3f%28VS.80%29.aspx) and some LINQ to XML magic, it [should not be too difficult](http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx) to implement a RSS client yourself...
There are many of them, e.g. [rss.net](http://www.rssdotnet.com/). And it's easy to [implement reading](http://geekswithblogs.net/willemf/archive/2005/10/30/58562.aspx) without any lib
1,510,575
Is there a RSS library for .NET?
2009/10/02
[ "https://Stackoverflow.com/questions/1510575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183229/" ]
According to [Google](http://www.google.nl/search?q=rss+library+.net), there are a few options: * [RSS.NET](http://www.rssdotnet.com/) - with an updated version [over here](http://www.web20tools.net/) * [FeedDotNet](http://www.codeplex.com/FeedDotNet/) Also, many commercial networking toolkits for .NET (e.g. /n Software's [IP\*Works!](http://nsoftware.com/portal/dotnet/)) support RSS. In addition to that, the [RSS protocol](http://www.rssboard.org/rss-specification) itself isn't too involved: using .NET's native [HttpClient](http://msdn.microsoft.com/en-us/library/f3wxbf3f%28VS.80%29.aspx) and some LINQ to XML magic, it [should not be too difficult](http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx) to implement a RSS client yourself...
I have answered a similar question 2 times ;- ) Check this out : [rss parser in .net](https://stackoverflow.com/questions/684507/rss-parser-in-net/684518#684518) > > <http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx> > <http://msdn.microsoft.com/en-us/magazine/cc135976.aspx> > > > .net has a class to parse ATOM and RSS > feeds. Check out the links. What are > you trying to do? Can you give more > information? > > > Alternatively You can just remove the > "Feed version" from the XML file and > parse it as a normal XML file using > xmlDocument class. > > >
1,510,575
Is there a RSS library for .NET?
2009/10/02
[ "https://Stackoverflow.com/questions/1510575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183229/" ]
According to [Google](http://www.google.nl/search?q=rss+library+.net), there are a few options: * [RSS.NET](http://www.rssdotnet.com/) - with an updated version [over here](http://www.web20tools.net/) * [FeedDotNet](http://www.codeplex.com/FeedDotNet/) Also, many commercial networking toolkits for .NET (e.g. /n Software's [IP\*Works!](http://nsoftware.com/portal/dotnet/)) support RSS. In addition to that, the [RSS protocol](http://www.rssboard.org/rss-specification) itself isn't too involved: using .NET's native [HttpClient](http://msdn.microsoft.com/en-us/library/f3wxbf3f%28VS.80%29.aspx) and some LINQ to XML magic, it [should not be too difficult](http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx) to implement a RSS client yourself...
There are tons, including using LinqToXML, however, IMHO, the Argotic framework is the most robust. <http://argotic.codeplex.com/>
1,510,575
Is there a RSS library for .NET?
2009/10/02
[ "https://Stackoverflow.com/questions/1510575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183229/" ]
You might start with the [System.ServiceModel.Syndication Namespace](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx). It includes classes for RSS and Atom.
There are many of them, e.g. [rss.net](http://www.rssdotnet.com/). And it's easy to [implement reading](http://geekswithblogs.net/willemf/archive/2005/10/30/58562.aspx) without any lib
1,510,575
Is there a RSS library for .NET?
2009/10/02
[ "https://Stackoverflow.com/questions/1510575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183229/" ]
You might start with the [System.ServiceModel.Syndication Namespace](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx). It includes classes for RSS and Atom.
I have answered a similar question 2 times ;- ) Check this out : [rss parser in .net](https://stackoverflow.com/questions/684507/rss-parser-in-net/684518#684518) > > <http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx> > <http://msdn.microsoft.com/en-us/magazine/cc135976.aspx> > > > .net has a class to parse ATOM and RSS > feeds. Check out the links. What are > you trying to do? Can you give more > information? > > > Alternatively You can just remove the > "Feed version" from the XML file and > parse it as a normal XML file using > xmlDocument class. > > >
1,510,575
Is there a RSS library for .NET?
2009/10/02
[ "https://Stackoverflow.com/questions/1510575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183229/" ]
You might start with the [System.ServiceModel.Syndication Namespace](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx). It includes classes for RSS and Atom.
There are tons, including using LinqToXML, however, IMHO, the Argotic framework is the most robust. <http://argotic.codeplex.com/>
1,510,575
Is there a RSS library for .NET?
2009/10/02
[ "https://Stackoverflow.com/questions/1510575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183229/" ]
I have answered a similar question 2 times ;- ) Check this out : [rss parser in .net](https://stackoverflow.com/questions/684507/rss-parser-in-net/684518#684518) > > <http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx> > <http://msdn.microsoft.com/en-us/magazine/cc135976.aspx> > > > .net has a class to parse ATOM and RSS > feeds. Check out the links. What are > you trying to do? Can you give more > information? > > > Alternatively You can just remove the > "Feed version" from the XML file and > parse it as a normal XML file using > xmlDocument class. > > >
There are many of them, e.g. [rss.net](http://www.rssdotnet.com/). And it's easy to [implement reading](http://geekswithblogs.net/willemf/archive/2005/10/30/58562.aspx) without any lib
1,510,575
Is there a RSS library for .NET?
2009/10/02
[ "https://Stackoverflow.com/questions/1510575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183229/" ]
There are tons, including using LinqToXML, however, IMHO, the Argotic framework is the most robust. <http://argotic.codeplex.com/>
There are many of them, e.g. [rss.net](http://www.rssdotnet.com/). And it's easy to [implement reading](http://geekswithblogs.net/willemf/archive/2005/10/30/58562.aspx) without any lib
1,510,575
Is there a RSS library for .NET?
2009/10/02
[ "https://Stackoverflow.com/questions/1510575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183229/" ]
I have answered a similar question 2 times ;- ) Check this out : [rss parser in .net](https://stackoverflow.com/questions/684507/rss-parser-in-net/684518#684518) > > <http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx> > <http://msdn.microsoft.com/en-us/magazine/cc135976.aspx> > > > .net has a class to parse ATOM and RSS > feeds. Check out the links. What are > you trying to do? Can you give more > information? > > > Alternatively You can just remove the > "Feed version" from the XML file and > parse it as a normal XML file using > xmlDocument class. > > >
There are tons, including using LinqToXML, however, IMHO, the Argotic framework is the most robust. <http://argotic.codeplex.com/>
24,570,725
I have just started to read up on networking and I don't get this DHCP stuff... For past few hours I have been trying to find out how my computer talks to DHCP in order to get its IPs and all I understood is that my router is some sort of DHCP that gives private IPs. I am wondering if there is a way to contact DHCP server manually from my computer in order to bypass the router, but few of things that I already said made me believe that my router is DHCP server (for 255.255.255.0 at least). So what is it? Is my plan feasible, and how about doing it?
2014/07/04
[ "https://Stackoverflow.com/questions/24570725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3804802/" ]
Cells should not "remember" their state; collection view or table view **data source** should. In the respective `cellForIndexPath` method, you should set the **current state** of the cell and let it configure itself as needed.
``` - (void)prepareForReuse { [super prepareForReuse]; self.isBookable = nil; [self.book removeFromSuperview]; [self setNeedsLayout]; } ``` Try setting `isBookable` to nil. I'm assuming that the cell is setting its layout with the previous cell's `isBookable` value.
24,570,725
I have just started to read up on networking and I don't get this DHCP stuff... For past few hours I have been trying to find out how my computer talks to DHCP in order to get its IPs and all I understood is that my router is some sort of DHCP that gives private IPs. I am wondering if there is a way to contact DHCP server manually from my computer in order to bypass the router, but few of things that I already said made me believe that my router is DHCP server (for 255.255.255.0 at least). So what is it? Is my plan feasible, and how about doing it?
2014/07/04
[ "https://Stackoverflow.com/questions/24570725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3804802/" ]
As @iphonic said, the `isBookable` property should be (re)moved from the cell completely. Cells in a UICollectionView are being reused most of the time, so even though your saleImage.isBookable is in the correct state your cell.isBookable is probably not. I would do the following: ``` if(saleImage.isBookable){ self.bgImageView.frame = CGRectMake(0, 0, 140, self.bounds.size.height - self.book.bounds.size.height); cell.bgImageView.image = [UIImage imageNamed:saleImage.imageName]; cell.book.hidden = NO; } else{ self.bgImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height); cell.bgImageView.image = nil; cell.book.hidden = YES; } [cell layoutIfNeeded]; ``` inside `collectionView: cellForItemAtIndexPath:`. I would also have finished setting up the book `UILabel` inside initWithFrame and have it initially hidden. Something like: ``` - (id)initWithFrame:(CGRect)frame{ self.layer.cornerRadius = 6.0; self.bgImageView = [[UIImageView alloc] init]; [self.contentView insertSubview:self.bgImageView atIndex:0]; self.book = [[UILabel alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 41, 140, 41)]; self.book.text = @"Book this Item"; self.book.textColor = [UIColor whiteColor]; self.book.adjustsFontSizeToFitWidth=YES; self.book.textAlignment = NSTextAlignmentCenter; self.book.backgroundColor= [UIColor darkGrayColor]; self.book.font = [UIFont fontWithName:kAppFont size:17.0]; self.book.hidden = YES; [self.contentView insertSubview:self.book atIndex:2]; } ``` Then you would not need to override `layoutSubviews`. Hope that helps.
You need to create two types of cells with different identifiers: ``` static NSString *Bookable = @"Bookable"; static NSString *NonBookable = @"NonBookable"; NSString *currentIdentifier; if(saleImage.isBookable)//isBookable property must be set in SaleImage class { currentIdentifier = Bookable; } else{ currentIdentifier = NonBookable; } SalesCollectionViewCell *cell = (SalesCollectionViewCell*)[collectionView dequeueReusableCellWithIdentifier:currentIdentifier]; ```
24,570,725
I have just started to read up on networking and I don't get this DHCP stuff... For past few hours I have been trying to find out how my computer talks to DHCP in order to get its IPs and all I understood is that my router is some sort of DHCP that gives private IPs. I am wondering if there is a way to contact DHCP server manually from my computer in order to bypass the router, but few of things that I already said made me believe that my router is DHCP server (for 255.255.255.0 at least). So what is it? Is my plan feasible, and how about doing it?
2014/07/04
[ "https://Stackoverflow.com/questions/24570725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3804802/" ]
``` - (void)prepareForReuse { [super prepareForReuse]; self.isBookable = nil; [self.book removeFromSuperview]; [self setNeedsLayout]; } ``` Try setting `isBookable` to nil. I'm assuming that the cell is setting its layout with the previous cell's `isBookable` value.
1st - Save/keep the indexPath of the cell that is changed. 2nd - ``` - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath SalesCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; if (indexPath == self.changedIndexPath) [cell trueImage]; else [cell falseImage]; return cell; } ``` Inside the cell, you just implement the `-(void) trueImage` and the `- (void) falseImage` which changes the image inside the cell. I hope I helped :)
24,570,725
I have just started to read up on networking and I don't get this DHCP stuff... For past few hours I have been trying to find out how my computer talks to DHCP in order to get its IPs and all I understood is that my router is some sort of DHCP that gives private IPs. I am wondering if there is a way to contact DHCP server manually from my computer in order to bypass the router, but few of things that I already said made me believe that my router is DHCP server (for 255.255.255.0 at least). So what is it? Is my plan feasible, and how about doing it?
2014/07/04
[ "https://Stackoverflow.com/questions/24570725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3804802/" ]
``` - (void)prepareForReuse { [super prepareForReuse]; self.isBookable = nil; [self.book removeFromSuperview]; [self setNeedsLayout]; } ``` Try setting `isBookable` to nil. I'm assuming that the cell is setting its layout with the previous cell's `isBookable` value.
I'd override `isBookable` setter in the cell class: ``` - (void) setIsBookable:(BOOL)isBookable { BOOL needsLayout = isBookable != _isBookable; _isBookable = isBookable; if(needsLayout) { [self.book removeFromSuperview]; [self setNeedsLayout]; } } ``` Also I'd recommend change `@property (nonatomic) BOOL isBookable;` with `@property (nonatomic, getter = isBookable) BOOL bookable;` in order to follow Apple Code Convention.
24,570,725
I have just started to read up on networking and I don't get this DHCP stuff... For past few hours I have been trying to find out how my computer talks to DHCP in order to get its IPs and all I understood is that my router is some sort of DHCP that gives private IPs. I am wondering if there is a way to contact DHCP server manually from my computer in order to bypass the router, but few of things that I already said made me believe that my router is DHCP server (for 255.255.255.0 at least). So what is it? Is my plan feasible, and how about doing it?
2014/07/04
[ "https://Stackoverflow.com/questions/24570725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3804802/" ]
I'd override `isBookable` setter in the cell class: ``` - (void) setIsBookable:(BOOL)isBookable { BOOL needsLayout = isBookable != _isBookable; _isBookable = isBookable; if(needsLayout) { [self.book removeFromSuperview]; [self setNeedsLayout]; } } ``` Also I'd recommend change `@property (nonatomic) BOOL isBookable;` with `@property (nonatomic, getter = isBookable) BOOL bookable;` in order to follow Apple Code Convention.
1st - Save/keep the indexPath of the cell that is changed. 2nd - ``` - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath SalesCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; if (indexPath == self.changedIndexPath) [cell trueImage]; else [cell falseImage]; return cell; } ``` Inside the cell, you just implement the `-(void) trueImage` and the `- (void) falseImage` which changes the image inside the cell. I hope I helped :)
24,570,725
I have just started to read up on networking and I don't get this DHCP stuff... For past few hours I have been trying to find out how my computer talks to DHCP in order to get its IPs and all I understood is that my router is some sort of DHCP that gives private IPs. I am wondering if there is a way to contact DHCP server manually from my computer in order to bypass the router, but few of things that I already said made me believe that my router is DHCP server (for 255.255.255.0 at least). So what is it? Is my plan feasible, and how about doing it?
2014/07/04
[ "https://Stackoverflow.com/questions/24570725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3804802/" ]
As @iphonic said, the `isBookable` property should be (re)moved from the cell completely. Cells in a UICollectionView are being reused most of the time, so even though your saleImage.isBookable is in the correct state your cell.isBookable is probably not. I would do the following: ``` if(saleImage.isBookable){ self.bgImageView.frame = CGRectMake(0, 0, 140, self.bounds.size.height - self.book.bounds.size.height); cell.bgImageView.image = [UIImage imageNamed:saleImage.imageName]; cell.book.hidden = NO; } else{ self.bgImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height); cell.bgImageView.image = nil; cell.book.hidden = YES; } [cell layoutIfNeeded]; ``` inside `collectionView: cellForItemAtIndexPath:`. I would also have finished setting up the book `UILabel` inside initWithFrame and have it initially hidden. Something like: ``` - (id)initWithFrame:(CGRect)frame{ self.layer.cornerRadius = 6.0; self.bgImageView = [[UIImageView alloc] init]; [self.contentView insertSubview:self.bgImageView atIndex:0]; self.book = [[UILabel alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 41, 140, 41)]; self.book.text = @"Book this Item"; self.book.textColor = [UIColor whiteColor]; self.book.adjustsFontSizeToFitWidth=YES; self.book.textAlignment = NSTextAlignmentCenter; self.book.backgroundColor= [UIColor darkGrayColor]; self.book.font = [UIFont fontWithName:kAppFont size:17.0]; self.book.hidden = YES; [self.contentView insertSubview:self.book atIndex:2]; } ``` Then you would not need to override `layoutSubviews`. Hope that helps.
1st - Save/keep the indexPath of the cell that is changed. 2nd - ``` - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath SalesCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; if (indexPath == self.changedIndexPath) [cell trueImage]; else [cell falseImage]; return cell; } ``` Inside the cell, you just implement the `-(void) trueImage` and the `- (void) falseImage` which changes the image inside the cell. I hope I helped :)
24,570,725
I have just started to read up on networking and I don't get this DHCP stuff... For past few hours I have been trying to find out how my computer talks to DHCP in order to get its IPs and all I understood is that my router is some sort of DHCP that gives private IPs. I am wondering if there is a way to contact DHCP server manually from my computer in order to bypass the router, but few of things that I already said made me believe that my router is DHCP server (for 255.255.255.0 at least). So what is it? Is my plan feasible, and how about doing it?
2014/07/04
[ "https://Stackoverflow.com/questions/24570725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3804802/" ]
As @iphonic said, the `isBookable` property should be (re)moved from the cell completely. Cells in a UICollectionView are being reused most of the time, so even though your saleImage.isBookable is in the correct state your cell.isBookable is probably not. I would do the following: ``` if(saleImage.isBookable){ self.bgImageView.frame = CGRectMake(0, 0, 140, self.bounds.size.height - self.book.bounds.size.height); cell.bgImageView.image = [UIImage imageNamed:saleImage.imageName]; cell.book.hidden = NO; } else{ self.bgImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height); cell.bgImageView.image = nil; cell.book.hidden = YES; } [cell layoutIfNeeded]; ``` inside `collectionView: cellForItemAtIndexPath:`. I would also have finished setting up the book `UILabel` inside initWithFrame and have it initially hidden. Something like: ``` - (id)initWithFrame:(CGRect)frame{ self.layer.cornerRadius = 6.0; self.bgImageView = [[UIImageView alloc] init]; [self.contentView insertSubview:self.bgImageView atIndex:0]; self.book = [[UILabel alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 41, 140, 41)]; self.book.text = @"Book this Item"; self.book.textColor = [UIColor whiteColor]; self.book.adjustsFontSizeToFitWidth=YES; self.book.textAlignment = NSTextAlignmentCenter; self.book.backgroundColor= [UIColor darkGrayColor]; self.book.font = [UIFont fontWithName:kAppFont size:17.0]; self.book.hidden = YES; [self.contentView insertSubview:self.book atIndex:2]; } ``` Then you would not need to override `layoutSubviews`. Hope that helps.
``` - (void)prepareForReuse { [super prepareForReuse]; self.isBookable = nil; [self.book removeFromSuperview]; [self setNeedsLayout]; } ``` Try setting `isBookable` to nil. I'm assuming that the cell is setting its layout with the previous cell's `isBookable` value.
24,570,725
I have just started to read up on networking and I don't get this DHCP stuff... For past few hours I have been trying to find out how my computer talks to DHCP in order to get its IPs and all I understood is that my router is some sort of DHCP that gives private IPs. I am wondering if there is a way to contact DHCP server manually from my computer in order to bypass the router, but few of things that I already said made me believe that my router is DHCP server (for 255.255.255.0 at least). So what is it? Is my plan feasible, and how about doing it?
2014/07/04
[ "https://Stackoverflow.com/questions/24570725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3804802/" ]
Cells should not "remember" their state; collection view or table view **data source** should. In the respective `cellForIndexPath` method, you should set the **current state** of the cell and let it configure itself as needed.
1st - Save/keep the indexPath of the cell that is changed. 2nd - ``` - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath SalesCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; if (indexPath == self.changedIndexPath) [cell trueImage]; else [cell falseImage]; return cell; } ``` Inside the cell, you just implement the `-(void) trueImage` and the `- (void) falseImage` which changes the image inside the cell. I hope I helped :)
24,570,725
I have just started to read up on networking and I don't get this DHCP stuff... For past few hours I have been trying to find out how my computer talks to DHCP in order to get its IPs and all I understood is that my router is some sort of DHCP that gives private IPs. I am wondering if there is a way to contact DHCP server manually from my computer in order to bypass the router, but few of things that I already said made me believe that my router is DHCP server (for 255.255.255.0 at least). So what is it? Is my plan feasible, and how about doing it?
2014/07/04
[ "https://Stackoverflow.com/questions/24570725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3804802/" ]
Cells should not "remember" their state; collection view or table view **data source** should. In the respective `cellForIndexPath` method, you should set the **current state** of the cell and let it configure itself as needed.
I'd override `isBookable` setter in the cell class: ``` - (void) setIsBookable:(BOOL)isBookable { BOOL needsLayout = isBookable != _isBookable; _isBookable = isBookable; if(needsLayout) { [self.book removeFromSuperview]; [self setNeedsLayout]; } } ``` Also I'd recommend change `@property (nonatomic) BOOL isBookable;` with `@property (nonatomic, getter = isBookable) BOOL bookable;` in order to follow Apple Code Convention.
24,570,725
I have just started to read up on networking and I don't get this DHCP stuff... For past few hours I have been trying to find out how my computer talks to DHCP in order to get its IPs and all I understood is that my router is some sort of DHCP that gives private IPs. I am wondering if there is a way to contact DHCP server manually from my computer in order to bypass the router, but few of things that I already said made me believe that my router is DHCP server (for 255.255.255.0 at least). So what is it? Is my plan feasible, and how about doing it?
2014/07/04
[ "https://Stackoverflow.com/questions/24570725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3804802/" ]
Cells should not "remember" their state; collection view or table view **data source** should. In the respective `cellForIndexPath` method, you should set the **current state** of the cell and let it configure itself as needed.
You need to create two types of cells with different identifiers: ``` static NSString *Bookable = @"Bookable"; static NSString *NonBookable = @"NonBookable"; NSString *currentIdentifier; if(saleImage.isBookable)//isBookable property must be set in SaleImage class { currentIdentifier = Bookable; } else{ currentIdentifier = NonBookable; } SalesCollectionViewCell *cell = (SalesCollectionViewCell*)[collectionView dequeueReusableCellWithIdentifier:currentIdentifier]; ```
3,296,030
I need to run a linux command such as "df" from my linux daemon to know free space,used space, total size of the parition and other info. I have options like calling system,exec,popen etc.. 1. But as this each command spawn a new process , is this not possible to run the commands in the same process from which it is invoked? 2. And at the same time as I need to run this command from a linux daemon, as my daemon should not hold any terminal. Will it effect my daemon behavior? Or is their any C or C++ standard API for getting the mounted paritions information
2010/07/21
[ "https://Stackoverflow.com/questions/3296030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7965/" ]
There is no *standard* API, as this is an OS-specific concept. However, 1. You can parse `/proc/mounts` (or `/etc/mtab`) with (non-portable) [`getmntent`/`getmntent_r`](http://linux.die.net/man/3/getmntent) helper functions. 2. Using information about mounted filesystems, you can get its statistics with [`statfs`](http://linux.die.net/man/2/statfs).
You may find it useful to explore the `i3status` program source code: <http://code.stapelberg.de/git/i3status/tree/src/print_disk_info.c> To answer your other questions: > > But as this each command spawn a new process , is this not possible to run the commands in the same process from which it is invoked? > > > No; entire 'commands' are self-contained programs that must run in their own process. Depending upon how often you wish to execute your programs, `fork();exec()` is not so bad. There's no hard limits beyond which it would be better to gather data yourself vs executing a helper program. Once a minute, you're probably fine executing the commands. Once a second, you're probably better off gathering the data yourself. I'm not sure where the dividing line is. > > And at the same time as I need to run this command from a linux daemon, as my daemon should not hold any terminal. Will it effect my daemon behavior? > > > If the command calls `setsid(2)`, then `open(2)` on a terminal without including `O_NOCTTY`, that terminal [might](http://www.win.tue.nl/~aeb/linux/lk/lk-10.html) become the controlling terminal for that process. But that wouldn't influence your program, because your program already disowned the terminal when becoming a daemon, and as the child process is a session leader, it cannot change your process's controlling terminal.
13,010,051
I am trying out the phpunit in the Zf2 album module. I encountered an error which states about routing. Below is the debug information. It says 'Route with name "album" not found', but when I checked module.config.php in the album module folder, I see that is correctly set and in the browser the redirection to that route is working fine. ``` Album\Controller\AlbumControllerTest::testDeleteActionCanBeAccessed Zend\Mvc\Router\Exception\RuntimeException: Route with name "album" not found D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Router\SimpleRouteStack.php:292 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\Plugin\Url.php:88 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\Plugin\Redirect.php:54 D:\www\zend2\module\Album\src\Album\Controller\AlbumController.php:80 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractActionController.php:87 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php:468 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php:208 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractController.php:108 D:\www\zend2\tests\module\Album\src\Album\Controller\AlbumControllerTest.php:35 C:\wamp\bin\php\php5.4.3\phpunit:46 ``` I understand that the issue in AlbumController.php line 80 is ``` return $this->redirect()->toRoute('album'); ``` But not sure why it is not working. Any one has encountered and overcome such issues?
2012/10/22
[ "https://Stackoverflow.com/questions/13010051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/602988/" ]
I hope it will save approx. 30 minutes of searching in the zend framework 2 code: ``` class AlbumControllerTest extends PHPUnit_Framework_TestCase { //... protected function setUp() { $bootstrap = \Zend\Mvc\Application::init(include 'config/application.config.php'); $this->controller = new AlbumController(); $this->request = new Request(); $this->routeMatch = new RouteMatch(array('controller' => 'index')); $this->event = $bootstrap->getMvcEvent(); $router = new \Zend\Mvc\Router\SimpleRouteStack(); $options = array( 'route' => '/album[/:action][/:id]', 'constraints' => array( 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'id' => '[0-9]+', ), 'defaults' => array( 'controller' => 'Album\Controller\Album', 'action' => 'index', ), ); $route = \Zend\Mvc\Router\Http\Segment::factory($options); $router->addRoute('album', $route); $this->event->setRouter($router); $this->event->setRouteMatch($this->routeMatch); $this->controller->setEvent($this->event); $this->controller->setEventManager($bootstrap->getEventManager()); $this->controller->setServiceLocator($bootstrap->getServiceManager()); } } ```
Actually the easy way is to get the config data from the service manager: ``` $config = $serviceManager->get('Config'); ``` Full code for the function `setUp()`: ``` protected function setUp() { $serviceManager = Bootstrap::getServiceManager(); $this -> controller = new AlbumController(); $this -> request = new Request(); $this -> routeMatch = new RouteMatch( array( 'controller' => 'index', ) ); $this -> event = new MvcEvent(); $config = $serviceManager->get('Config'); $routerConfig = isset($config['router']) ? $config['router'] : array(); $router = HttpRouter::factory($routerConfig); $this -> event -> setRouter($router); $this -> event -> setRouteMatch($this -> routeMatch); $this -> controller -> setEvent($this -> event); $this -> controller -> setServiceLocator($serviceManager); } ```
13,010,051
I am trying out the phpunit in the Zf2 album module. I encountered an error which states about routing. Below is the debug information. It says 'Route with name "album" not found', but when I checked module.config.php in the album module folder, I see that is correctly set and in the browser the redirection to that route is working fine. ``` Album\Controller\AlbumControllerTest::testDeleteActionCanBeAccessed Zend\Mvc\Router\Exception\RuntimeException: Route with name "album" not found D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Router\SimpleRouteStack.php:292 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\Plugin\Url.php:88 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\Plugin\Redirect.php:54 D:\www\zend2\module\Album\src\Album\Controller\AlbumController.php:80 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractActionController.php:87 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php:468 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php:208 D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractController.php:108 D:\www\zend2\tests\module\Album\src\Album\Controller\AlbumControllerTest.php:35 C:\wamp\bin\php\php5.4.3\phpunit:46 ``` I understand that the issue in AlbumController.php line 80 is ``` return $this->redirect()->toRoute('album'); ``` But not sure why it is not working. Any one has encountered and overcome such issues?
2012/10/22
[ "https://Stackoverflow.com/questions/13010051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/602988/" ]
To avoid duplicate Code, you can load your Routes from Module Config: ``` $module = new \YourNameSpace\Module(); $config = $module->getConfig(); $route = \Zend\Mvc\Router\Http\Segment::factory($config['router']['routes']['Home']['options']); $router = new \Zend\Mvc\Router\SimpleRouteStack(); $router->addRoute('Home', $route); ```
Actually the easy way is to get the config data from the service manager: ``` $config = $serviceManager->get('Config'); ``` Full code for the function `setUp()`: ``` protected function setUp() { $serviceManager = Bootstrap::getServiceManager(); $this -> controller = new AlbumController(); $this -> request = new Request(); $this -> routeMatch = new RouteMatch( array( 'controller' => 'index', ) ); $this -> event = new MvcEvent(); $config = $serviceManager->get('Config'); $routerConfig = isset($config['router']) ? $config['router'] : array(); $router = HttpRouter::factory($routerConfig); $this -> event -> setRouter($router); $this -> event -> setRouteMatch($this -> routeMatch); $this -> controller -> setEvent($this -> event); $this -> controller -> setServiceLocator($serviceManager); } ```
33,159,169
I am getting the following errors for HDFS client installation on Ambari. Have reset the server several times but still cannot get it resolved. Any idea how to fix that? stderr: ``` Traceback (most recent call last): File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 120, in <module> HdfsClient().execute() File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 219, in execute method(env) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 36, in install self.configure(env) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 41, in configure hdfs() File "/usr/lib/python2.6/site-packages/ambari_commons/os_family_impl.py", line 89, in thunk return fn(*args, **kwargs) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs.py", line 61, in hdfs group=params.user_group File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 154, in __init__ self.env.run() File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 152, in run self.run_action(resource, action) File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 118, in run_action provider_action() File "/usr/lib/python2.6/site-packages/resource_management/libraries/providers/xml_config.py", line 67, in action_create encoding = self.resource.encoding File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 154, in __init__ self.env.run() File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 152, in run self.run_action(resource, action) File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 118, in run_action provider_action() File "/usr/lib/python2.6/site-packages/resource_management/core/providers/system.py", line 87, in action_create raise Fail("Applying %s failed, parent directory %s doesn't exist" % (self.resource, dirname)) resource_management.core.exceptions.Fail: Applying File['/usr/hdp/current/hadoop-client/conf/hadoop-policy.xml'] failed, parent directory /usr/hdp/current/hadoop-client/conf doesn't exist ```
2015/10/15
[ "https://Stackoverflow.com/questions/33159169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369921/" ]
This is a soft link that link to **/etc/hadoop/conf** I run ``` python /usr/lib/python2.6/site-packages/ambari_agent/HostCleanup.py --silent --skip=users ``` After run it, it removes `/etc/hadoop/conf` However, reinstall does not recreate it. So you may have to create all conf files by yourself. Hope someone can patch it.
Creating `/usr/hdp/current/hadoop-client/conf` on failing host should solve the problem.
33,159,169
I am getting the following errors for HDFS client installation on Ambari. Have reset the server several times but still cannot get it resolved. Any idea how to fix that? stderr: ``` Traceback (most recent call last): File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 120, in <module> HdfsClient().execute() File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 219, in execute method(env) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 36, in install self.configure(env) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 41, in configure hdfs() File "/usr/lib/python2.6/site-packages/ambari_commons/os_family_impl.py", line 89, in thunk return fn(*args, **kwargs) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs.py", line 61, in hdfs group=params.user_group File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 154, in __init__ self.env.run() File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 152, in run self.run_action(resource, action) File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 118, in run_action provider_action() File "/usr/lib/python2.6/site-packages/resource_management/libraries/providers/xml_config.py", line 67, in action_create encoding = self.resource.encoding File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 154, in __init__ self.env.run() File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 152, in run self.run_action(resource, action) File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 118, in run_action provider_action() File "/usr/lib/python2.6/site-packages/resource_management/core/providers/system.py", line 87, in action_create raise Fail("Applying %s failed, parent directory %s doesn't exist" % (self.resource, dirname)) resource_management.core.exceptions.Fail: Applying File['/usr/hdp/current/hadoop-client/conf/hadoop-policy.xml'] failed, parent directory /usr/hdp/current/hadoop-client/conf doesn't exist ```
2015/10/15
[ "https://Stackoverflow.com/questions/33159169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369921/" ]
I ran into the same problem: I was using HDP 2.3.2 on Centos 7. **The first problem:** Some conf files point to the /etc//conf directory (same as they are supposed to) However, /etc//conf points back to the other conf directory which leads to an endless loop. I was able to fix this problem by removing the /etc//conf symbolic links and creating directories **The second problem** If you run the python scripts to clean up the installation and start over however, several directories do not get recreated, such as the hadoop-client directory. This leads to exact your error message. Also this cleanup script does not work out well as it does not clean several users and directories. You have to userdel and groupdel. UPDATE: It seems it was a problem of HDP 2.3.2. In HDP 2.3.4, I did not run into that problem any more.
Creating `/usr/hdp/current/hadoop-client/conf` on failing host should solve the problem.
33,159,169
I am getting the following errors for HDFS client installation on Ambari. Have reset the server several times but still cannot get it resolved. Any idea how to fix that? stderr: ``` Traceback (most recent call last): File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 120, in <module> HdfsClient().execute() File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 219, in execute method(env) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 36, in install self.configure(env) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 41, in configure hdfs() File "/usr/lib/python2.6/site-packages/ambari_commons/os_family_impl.py", line 89, in thunk return fn(*args, **kwargs) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs.py", line 61, in hdfs group=params.user_group File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 154, in __init__ self.env.run() File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 152, in run self.run_action(resource, action) File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 118, in run_action provider_action() File "/usr/lib/python2.6/site-packages/resource_management/libraries/providers/xml_config.py", line 67, in action_create encoding = self.resource.encoding File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 154, in __init__ self.env.run() File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 152, in run self.run_action(resource, action) File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 118, in run_action provider_action() File "/usr/lib/python2.6/site-packages/resource_management/core/providers/system.py", line 87, in action_create raise Fail("Applying %s failed, parent directory %s doesn't exist" % (self.resource, dirname)) resource_management.core.exceptions.Fail: Applying File['/usr/hdp/current/hadoop-client/conf/hadoop-policy.xml'] failed, parent directory /usr/hdp/current/hadoop-client/conf doesn't exist ```
2015/10/15
[ "https://Stackoverflow.com/questions/33159169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369921/" ]
``` yum -y erase hdp-select ``` If you have done installation multiple times, some packages might not be cleaned. To remove all HDP packages and start with fresh installation, erase hdp-select. If this is not helping, remove all the versions from `/usr/hdp` delete this directory if it contains multiple versions of `hdp` Remove all the installed packages like `hadoop,hdfs,zookeeper etc.` ``` yum remove zookeeper* hadoop* hdp* zookeeper* ```
Creating `/usr/hdp/current/hadoop-client/conf` on failing host should solve the problem.
33,159,169
I am getting the following errors for HDFS client installation on Ambari. Have reset the server several times but still cannot get it resolved. Any idea how to fix that? stderr: ``` Traceback (most recent call last): File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 120, in <module> HdfsClient().execute() File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 219, in execute method(env) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 36, in install self.configure(env) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 41, in configure hdfs() File "/usr/lib/python2.6/site-packages/ambari_commons/os_family_impl.py", line 89, in thunk return fn(*args, **kwargs) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs.py", line 61, in hdfs group=params.user_group File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 154, in __init__ self.env.run() File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 152, in run self.run_action(resource, action) File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 118, in run_action provider_action() File "/usr/lib/python2.6/site-packages/resource_management/libraries/providers/xml_config.py", line 67, in action_create encoding = self.resource.encoding File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 154, in __init__ self.env.run() File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 152, in run self.run_action(resource, action) File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 118, in run_action provider_action() File "/usr/lib/python2.6/site-packages/resource_management/core/providers/system.py", line 87, in action_create raise Fail("Applying %s failed, parent directory %s doesn't exist" % (self.resource, dirname)) resource_management.core.exceptions.Fail: Applying File['/usr/hdp/current/hadoop-client/conf/hadoop-policy.xml'] failed, parent directory /usr/hdp/current/hadoop-client/conf doesn't exist ```
2015/10/15
[ "https://Stackoverflow.com/questions/33159169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369921/" ]
This is a soft link that link to **/etc/hadoop/conf** I run ``` python /usr/lib/python2.6/site-packages/ambari_agent/HostCleanup.py --silent --skip=users ``` After run it, it removes `/etc/hadoop/conf` However, reinstall does not recreate it. So you may have to create all conf files by yourself. Hope someone can patch it.
I ran into the same problem: I was using HDP 2.3.2 on Centos 7. **The first problem:** Some conf files point to the /etc//conf directory (same as they are supposed to) However, /etc//conf points back to the other conf directory which leads to an endless loop. I was able to fix this problem by removing the /etc//conf symbolic links and creating directories **The second problem** If you run the python scripts to clean up the installation and start over however, several directories do not get recreated, such as the hadoop-client directory. This leads to exact your error message. Also this cleanup script does not work out well as it does not clean several users and directories. You have to userdel and groupdel. UPDATE: It seems it was a problem of HDP 2.3.2. In HDP 2.3.4, I did not run into that problem any more.
33,159,169
I am getting the following errors for HDFS client installation on Ambari. Have reset the server several times but still cannot get it resolved. Any idea how to fix that? stderr: ``` Traceback (most recent call last): File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 120, in <module> HdfsClient().execute() File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 219, in execute method(env) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 36, in install self.configure(env) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 41, in configure hdfs() File "/usr/lib/python2.6/site-packages/ambari_commons/os_family_impl.py", line 89, in thunk return fn(*args, **kwargs) File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs.py", line 61, in hdfs group=params.user_group File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 154, in __init__ self.env.run() File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 152, in run self.run_action(resource, action) File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 118, in run_action provider_action() File "/usr/lib/python2.6/site-packages/resource_management/libraries/providers/xml_config.py", line 67, in action_create encoding = self.resource.encoding File "/usr/lib/python2.6/site-packages/resource_management/core/base.py", line 154, in __init__ self.env.run() File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 152, in run self.run_action(resource, action) File "/usr/lib/python2.6/site-packages/resource_management/core/environment.py", line 118, in run_action provider_action() File "/usr/lib/python2.6/site-packages/resource_management/core/providers/system.py", line 87, in action_create raise Fail("Applying %s failed, parent directory %s doesn't exist" % (self.resource, dirname)) resource_management.core.exceptions.Fail: Applying File['/usr/hdp/current/hadoop-client/conf/hadoop-policy.xml'] failed, parent directory /usr/hdp/current/hadoop-client/conf doesn't exist ```
2015/10/15
[ "https://Stackoverflow.com/questions/33159169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369921/" ]
``` yum -y erase hdp-select ``` If you have done installation multiple times, some packages might not be cleaned. To remove all HDP packages and start with fresh installation, erase hdp-select. If this is not helping, remove all the versions from `/usr/hdp` delete this directory if it contains multiple versions of `hdp` Remove all the installed packages like `hadoop,hdfs,zookeeper etc.` ``` yum remove zookeeper* hadoop* hdp* zookeeper* ```
I ran into the same problem: I was using HDP 2.3.2 on Centos 7. **The first problem:** Some conf files point to the /etc//conf directory (same as they are supposed to) However, /etc//conf points back to the other conf directory which leads to an endless loop. I was able to fix this problem by removing the /etc//conf symbolic links and creating directories **The second problem** If you run the python scripts to clean up the installation and start over however, several directories do not get recreated, such as the hadoop-client directory. This leads to exact your error message. Also this cleanup script does not work out well as it does not clean several users and directories. You have to userdel and groupdel. UPDATE: It seems it was a problem of HDP 2.3.2. In HDP 2.3.4, I did not run into that problem any more.
4,749,235
I have the following HTML code (a list item). The content isn't important--the problem is the end of line 2. ``` <li>Yes, you can learn how to play piano without becoming a great notation reader, however, <strong class="warning">you <em class="emphatic">will</em> have to acquire a <em class="emphatic">very</em>basic amount of notation reading skill</strong>. But the extremely difficult task of honing your note reading skills that classical students are required to endure for years and years is <em class="emphatic">totally non-existant</em>as a requirement for playing non-classical piano.</li> ``` The command fill-paragraph (M-q) has been applied. I can't for the life of me figure out why a line break is being placed on the second line after "reader," since there's more space available on that line to put "however,". Another weird thing I've noticed is that when I delete and then reapply the tab characters on lines 4 and 5 (starting with "have" and "of" respectively), two space characters are automatically inserted as well, like so: ``` <li>Yes, you can learn how to play piano without becoming a great notation reader, however, <strong class="warning">you <em class="emphatic">will</em> have to acquire a <em class="emphatic">very</em>basic amount of notation reading skill</strong>. But the extremely difficult task of honing your note reading skills that classical students are required to endure for years and years is <em class="emphatic">totally non-existant</em>as a requirement for playing non-classical piano.</li> ``` I don't know if this is some kind of clue or not. This doesn't happen with any of the other lines. Is this just a bug, or does any experienced Emacs person know what might be going on here? Thank you
2011/01/20
[ "https://Stackoverflow.com/questions/4749235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/520648/" ]
This is intentional. Lines that start with an XML or SGML tag are paragraph separator lines. If Emacs broke the paragraph in such a way that the tag ended up at the start of a line, subsequent applications of `fill-paragraph` would stop at that line. This is to ensure that, for instance, ``` <p>a paragraph</p> <!-- no blank line --> <p>another paragraph</p> ``` does not turn into ``` <p>a paragraph</p> <!-- no blank line --> <p>another paragraph</p> ``` For the same reason, Emacs will not break a line after a period unless there are two or more spaces after the period, because it uses a double space to distinguish between a period that ends a sentence and a period that ends an abbreviation, and breaking a line after the period that ends an abbreviation would create an ambiguous situation.
Looks like a bug to me. I was able to trim down your example to something like this: ``` <li>blabla blabla <b>some_long_text_here</b> <b>more_long_text_here</b> ``` If I remove a single character of text from it, `fill-paragraph` works as expected. Or if I add a chacter between the two consequtive `<b>` elements.
22,037
I was playing around with aliases today and I noticed that aliases don't seem to be available whilst using `sudo`: ``` danny@kaon:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' danny@kaon:~$ ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // danny@kaon:~$ sudo -i root@kaon:~# ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // root@kaon:~# exit logout danny@kaon:~$ sudo ll -d / sudo: ll: command not found ``` Is there any reason why you cannot use aliases whilst using `sudo`?
2011/01/17
[ "https://askubuntu.com/questions/22037", "https://askubuntu.com", "https://askubuntu.com/users/3583/" ]
Add the following line to your `~/.bashrc`: ``` alias sudo='sudo ' ``` From the [bash manual](http://www.gnu.org/software/bash/manual/bashref.html#Aliases): > > Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the alias and unalias builtin commands. > > > **The first word of each simple command, if unquoted, is checked to see if it has an alias**. If so, that word is replaced by the text of the alias. The characters ‘/’, ‘$’, ‘`’, ‘=’ and any of the shell metacharacters or quoting characters listed above may not appear in an alias name. The replacement text may contain any valid shell input, including shell metacharacters. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to "ls -F", for instance, and Bash does not try to recursively expand the replacement text. **If the last character of the alias value is a space or tab character, then the next command word following the alias is also checked for alias expansion**. > > > (Emphasis mine). Bash only checks the first word of a command for an alias, any words after that are not checked. That means in a command like `sudo ll`, only the first word (`sudo`) is checked by bash for an alias, `ll` is ignored. We can tell bash to check the next word after the alias (i.e `sudo`) by adding a space to the end of the alias value.
I have a different solution whereby you do not need to add `sudo` as an alias. I run Linux Mint 17.3 but it should be pretty similar to Ubuntu. When you are root, then the `.profile` is run from its home directory. If you do not know what the home directory under root is, then you can check with: ``` sudo su echo $HOME ``` As you can see, the home of `root` is `/root/`. Check its contents: ``` cd $HOME ls -al ``` There should be a `.profile` file. Open the file and add the following lines: ``` if [ "$BASH" ]; then if [ -f ~/.bash_aliases];then . ~/.bash_aliases fi fi ``` Basically, what this bash script does is to check for a file called `.bash_aliases`. If the files is present, it executes the file. Save the `.profile` file and create your aliases in `.bash_aliases`. If you already have the aliases file ready, then copy the file to this location Re-launch the terminal and you are good to go!
22,037
I was playing around with aliases today and I noticed that aliases don't seem to be available whilst using `sudo`: ``` danny@kaon:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' danny@kaon:~$ ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // danny@kaon:~$ sudo -i root@kaon:~# ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // root@kaon:~# exit logout danny@kaon:~$ sudo ll -d / sudo: ll: command not found ``` Is there any reason why you cannot use aliases whilst using `sudo`?
2011/01/17
[ "https://askubuntu.com/questions/22037", "https://askubuntu.com", "https://askubuntu.com/users/3583/" ]
Add the following line to your `~/.bashrc`: ``` alias sudo='sudo ' ``` From the [bash manual](http://www.gnu.org/software/bash/manual/bashref.html#Aliases): > > Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the alias and unalias builtin commands. > > > **The first word of each simple command, if unquoted, is checked to see if it has an alias**. If so, that word is replaced by the text of the alias. The characters ‘/’, ‘$’, ‘`’, ‘=’ and any of the shell metacharacters or quoting characters listed above may not appear in an alias name. The replacement text may contain any valid shell input, including shell metacharacters. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to "ls -F", for instance, and Bash does not try to recursively expand the replacement text. **If the last character of the alias value is a space or tab character, then the next command word following the alias is also checked for alias expansion**. > > > (Emphasis mine). Bash only checks the first word of a command for an alias, any words after that are not checked. That means in a command like `sudo ll`, only the first word (`sudo`) is checked by bash for an alias, `ll` is ignored. We can tell bash to check the next word after the alias (i.e `sudo`) by adding a space to the end of the alias value.
I have another nice solution, that adds a bit of trust too: **Use bash completion to automatically replace words behind `sudo` with their aliases when pressing tab.** Save this as `/etc/bash_completion.d/sudo-alias.bashcomp`, and it should automatically be loaded at interactive shell startup: ```bsh _comp_sudo_alias() { from="$2"; COMPREPLY=() if [[ $COMP_CWORD == 1 ]]; then COMPREPLY=( "$( alias -p | grep "^ *alias $from=" | sed -r "s/^ *alias [^=]+='(.*)'$/\1/" )" ) return 0 fi return 1 } complete -o bashdefault -o default -F _comp_sudo_alias sudo ``` Then log in to a new terminal, and you should be good to go.
22,037
I was playing around with aliases today and I noticed that aliases don't seem to be available whilst using `sudo`: ``` danny@kaon:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' danny@kaon:~$ ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // danny@kaon:~$ sudo -i root@kaon:~# ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // root@kaon:~# exit logout danny@kaon:~$ sudo ll -d / sudo: ll: command not found ``` Is there any reason why you cannot use aliases whilst using `sudo`?
2011/01/17
[ "https://askubuntu.com/questions/22037", "https://askubuntu.com", "https://askubuntu.com/users/3583/" ]
I have another nice solution, that adds a bit of trust too: **Use bash completion to automatically replace words behind `sudo` with their aliases when pressing tab.** Save this as `/etc/bash_completion.d/sudo-alias.bashcomp`, and it should automatically be loaded at interactive shell startup: ```bsh _comp_sudo_alias() { from="$2"; COMPREPLY=() if [[ $COMP_CWORD == 1 ]]; then COMPREPLY=( "$( alias -p | grep "^ *alias $from=" | sed -r "s/^ *alias [^=]+='(.*)'$/\1/" )" ) return 0 fi return 1 } complete -o bashdefault -o default -F _comp_sudo_alias sudo ``` Then log in to a new terminal, and you should be good to go.
If you type `sudo -i` and elevate to a sudo prompt (`#`) you won't have the aliases or functions you like to use. To utilize your aliases and functions at the `#` prompt, use: ``` sudo cp "$HOME"/.bashrc /root/.bashrc ``` Where "$HOME" is expanded into "/home/YOUR\_USER\_NAME"
22,037
I was playing around with aliases today and I noticed that aliases don't seem to be available whilst using `sudo`: ``` danny@kaon:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' danny@kaon:~$ ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // danny@kaon:~$ sudo -i root@kaon:~# ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // root@kaon:~# exit logout danny@kaon:~$ sudo ll -d / sudo: ll: command not found ``` Is there any reason why you cannot use aliases whilst using `sudo`?
2011/01/17
[ "https://askubuntu.com/questions/22037", "https://askubuntu.com", "https://askubuntu.com/users/3583/" ]
Add the following line to your `~/.bashrc`: ``` alias sudo='sudo ' ``` From the [bash manual](http://www.gnu.org/software/bash/manual/bashref.html#Aliases): > > Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the alias and unalias builtin commands. > > > **The first word of each simple command, if unquoted, is checked to see if it has an alias**. If so, that word is replaced by the text of the alias. The characters ‘/’, ‘$’, ‘`’, ‘=’ and any of the shell metacharacters or quoting characters listed above may not appear in an alias name. The replacement text may contain any valid shell input, including shell metacharacters. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to "ls -F", for instance, and Bash does not try to recursively expand the replacement text. **If the last character of the alias value is a space or tab character, then the next command word following the alias is also checked for alias expansion**. > > > (Emphasis mine). Bash only checks the first word of a command for an alias, any words after that are not checked. That means in a command like `sudo ll`, only the first word (`sudo`) is checked by bash for an alias, `ll` is ignored. We can tell bash to check the next word after the alias (i.e `sudo`) by adding a space to the end of the alias value.
I wrote a Bash function for it that shadows `sudo`. It checks whether I have an alias for the given command and runs the aliased command instead of the literal one with `sudo` in that case. Here is my function as one-liner: ```bsh sudo() { if alias "$1" &> /dev/null ; then $(type "$1" | sed -E 's/^.*`(.*).$/\1/') "${@:2}" ; else command sudo $@ ; fi } ``` Or nicely formatted: ```bsh sudo() { if alias "$1" &> /dev/null ; then $(type "$1" | sed -E 's/^.*`(.*).$/\1/') "${@:2}" else command sudo "$@" fi } ``` You can append it to your `.bashrc` file, don't forget to source it or restart your terminal session afterwards to apply the changes though.
22,037
I was playing around with aliases today and I noticed that aliases don't seem to be available whilst using `sudo`: ``` danny@kaon:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' danny@kaon:~$ ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // danny@kaon:~$ sudo -i root@kaon:~# ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // root@kaon:~# exit logout danny@kaon:~$ sudo ll -d / sudo: ll: command not found ``` Is there any reason why you cannot use aliases whilst using `sudo`?
2011/01/17
[ "https://askubuntu.com/questions/22037", "https://askubuntu.com", "https://askubuntu.com/users/3583/" ]
I wrote a Bash function for it that shadows `sudo`. It checks whether I have an alias for the given command and runs the aliased command instead of the literal one with `sudo` in that case. Here is my function as one-liner: ```bsh sudo() { if alias "$1" &> /dev/null ; then $(type "$1" | sed -E 's/^.*`(.*).$/\1/') "${@:2}" ; else command sudo $@ ; fi } ``` Or nicely formatted: ```bsh sudo() { if alias "$1" &> /dev/null ; then $(type "$1" | sed -E 's/^.*`(.*).$/\1/') "${@:2}" else command sudo "$@" fi } ``` You can append it to your `.bashrc` file, don't forget to source it or restart your terminal session afterwards to apply the changes though.
@Alvins answer is the shortest one. No doubt! :-) However I thought of a command line solution to **execute an aliased command in sudo** where there is no need to redefine `sudo` with an `alias` command. Here is my proposal for those to whom it may interest: Solution -------- ``` type -a <YOUR COMMAND HERE> | grep -o -P "(?<=\`).*(?=')" | xargs sudo ``` Example ------- In the case of the `ll` command ``` type -a ll | grep -o -P "(?<=\`).*(?=')" | xargs sudo ``` Explanation ----------- when you have an alias (such as: `ll`) the command `type -a` returns the aliased expression: ``` $type -a ll ll is aliased to `ls -l' ``` with `grep` you select the text between the accent ` and apostrophe ' in that case `ls -l` And `xargs` executes the selected text `ls -l` as parameter of `sudo`. Yes, a bit longer but **completely clean** ;-) No need to redefine `sudo` as alias.
22,037
I was playing around with aliases today and I noticed that aliases don't seem to be available whilst using `sudo`: ``` danny@kaon:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' danny@kaon:~$ ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // danny@kaon:~$ sudo -i root@kaon:~# ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // root@kaon:~# exit logout danny@kaon:~$ sudo ll -d / sudo: ll: command not found ``` Is there any reason why you cannot use aliases whilst using `sudo`?
2011/01/17
[ "https://askubuntu.com/questions/22037", "https://askubuntu.com", "https://askubuntu.com/users/3583/" ]
I wrote a Bash function for it that shadows `sudo`. It checks whether I have an alias for the given command and runs the aliased command instead of the literal one with `sudo` in that case. Here is my function as one-liner: ```bsh sudo() { if alias "$1" &> /dev/null ; then $(type "$1" | sed -E 's/^.*`(.*).$/\1/') "${@:2}" ; else command sudo $@ ; fi } ``` Or nicely formatted: ```bsh sudo() { if alias "$1" &> /dev/null ; then $(type "$1" | sed -E 's/^.*`(.*).$/\1/') "${@:2}" else command sudo "$@" fi } ``` You can append it to your `.bashrc` file, don't forget to source it or restart your terminal session afterwards to apply the changes though.
I have a different solution whereby you do not need to add `sudo` as an alias. I run Linux Mint 17.3 but it should be pretty similar to Ubuntu. When you are root, then the `.profile` is run from its home directory. If you do not know what the home directory under root is, then you can check with: ``` sudo su echo $HOME ``` As you can see, the home of `root` is `/root/`. Check its contents: ``` cd $HOME ls -al ``` There should be a `.profile` file. Open the file and add the following lines: ``` if [ "$BASH" ]; then if [ -f ~/.bash_aliases];then . ~/.bash_aliases fi fi ``` Basically, what this bash script does is to check for a file called `.bash_aliases`. If the files is present, it executes the file. Save the `.profile` file and create your aliases in `.bash_aliases`. If you already have the aliases file ready, then copy the file to this location Re-launch the terminal and you are good to go!
22,037
I was playing around with aliases today and I noticed that aliases don't seem to be available whilst using `sudo`: ``` danny@kaon:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' danny@kaon:~$ ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // danny@kaon:~$ sudo -i root@kaon:~# ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // root@kaon:~# exit logout danny@kaon:~$ sudo ll -d / sudo: ll: command not found ``` Is there any reason why you cannot use aliases whilst using `sudo`?
2011/01/17
[ "https://askubuntu.com/questions/22037", "https://askubuntu.com", "https://askubuntu.com/users/3583/" ]
[@WinEunuuchs2Unix](https://askubuntu.com/a/853332/830570): `$PWD` expands to the "present working directory". I think you want `$HOME`. Also, for most situations, it's probably best to have a separate root .bashrc file. In fact, I'd make it a real file in `/root`, soft link to it in the user's home directory (e.g., `.bashrc_root`), and source it from the user's `.bashrc` file. If at some later time this privileged user account is no longer present, the root `.bashrc` file is still available for other users.
If you type `sudo -i` and elevate to a sudo prompt (`#`) you won't have the aliases or functions you like to use. To utilize your aliases and functions at the `#` prompt, use: ``` sudo cp "$HOME"/.bashrc /root/.bashrc ``` Where "$HOME" is expanded into "/home/YOUR\_USER\_NAME"
22,037
I was playing around with aliases today and I noticed that aliases don't seem to be available whilst using `sudo`: ``` danny@kaon:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' danny@kaon:~$ ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // danny@kaon:~$ sudo -i root@kaon:~# ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // root@kaon:~# exit logout danny@kaon:~$ sudo ll -d / sudo: ll: command not found ``` Is there any reason why you cannot use aliases whilst using `sudo`?
2011/01/17
[ "https://askubuntu.com/questions/22037", "https://askubuntu.com", "https://askubuntu.com/users/3583/" ]
If you type `sudo -i` and elevate to a sudo prompt (`#`) you won't have the aliases or functions you like to use. To utilize your aliases and functions at the `#` prompt, use: ``` sudo cp "$HOME"/.bashrc /root/.bashrc ``` Where "$HOME" is expanded into "/home/YOUR\_USER\_NAME"
I have a different solution whereby you do not need to add `sudo` as an alias. I run Linux Mint 17.3 but it should be pretty similar to Ubuntu. When you are root, then the `.profile` is run from its home directory. If you do not know what the home directory under root is, then you can check with: ``` sudo su echo $HOME ``` As you can see, the home of `root` is `/root/`. Check its contents: ``` cd $HOME ls -al ``` There should be a `.profile` file. Open the file and add the following lines: ``` if [ "$BASH" ]; then if [ -f ~/.bash_aliases];then . ~/.bash_aliases fi fi ``` Basically, what this bash script does is to check for a file called `.bash_aliases`. If the files is present, it executes the file. Save the `.profile` file and create your aliases in `.bash_aliases`. If you already have the aliases file ready, then copy the file to this location Re-launch the terminal and you are good to go!
22,037
I was playing around with aliases today and I noticed that aliases don't seem to be available whilst using `sudo`: ``` danny@kaon:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' danny@kaon:~$ ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // danny@kaon:~$ sudo -i root@kaon:~# ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // root@kaon:~# exit logout danny@kaon:~$ sudo ll -d / sudo: ll: command not found ``` Is there any reason why you cannot use aliases whilst using `sudo`?
2011/01/17
[ "https://askubuntu.com/questions/22037", "https://askubuntu.com", "https://askubuntu.com/users/3583/" ]
I wrote a Bash function for it that shadows `sudo`. It checks whether I have an alias for the given command and runs the aliased command instead of the literal one with `sudo` in that case. Here is my function as one-liner: ```bsh sudo() { if alias "$1" &> /dev/null ; then $(type "$1" | sed -E 's/^.*`(.*).$/\1/') "${@:2}" ; else command sudo $@ ; fi } ``` Or nicely formatted: ```bsh sudo() { if alias "$1" &> /dev/null ; then $(type "$1" | sed -E 's/^.*`(.*).$/\1/') "${@:2}" else command sudo "$@" fi } ``` You can append it to your `.bashrc` file, don't forget to source it or restart your terminal session afterwards to apply the changes though.
If you type `sudo -i` and elevate to a sudo prompt (`#`) you won't have the aliases or functions you like to use. To utilize your aliases and functions at the `#` prompt, use: ``` sudo cp "$HOME"/.bashrc /root/.bashrc ``` Where "$HOME" is expanded into "/home/YOUR\_USER\_NAME"
22,037
I was playing around with aliases today and I noticed that aliases don't seem to be available whilst using `sudo`: ``` danny@kaon:~$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto' danny@kaon:~$ ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // danny@kaon:~$ sudo -i root@kaon:~# ll -d / drwxr-xr-x 23 root root 4096 2011-01-06 20:29 // root@kaon:~# exit logout danny@kaon:~$ sudo ll -d / sudo: ll: command not found ``` Is there any reason why you cannot use aliases whilst using `sudo`?
2011/01/17
[ "https://askubuntu.com/questions/22037", "https://askubuntu.com", "https://askubuntu.com/users/3583/" ]
[@WinEunuuchs2Unix](https://askubuntu.com/a/853332/830570): `$PWD` expands to the "present working directory". I think you want `$HOME`. Also, for most situations, it's probably best to have a separate root .bashrc file. In fact, I'd make it a real file in `/root`, soft link to it in the user's home directory (e.g., `.bashrc_root`), and source it from the user's `.bashrc` file. If at some later time this privileged user account is no longer present, the root `.bashrc` file is still available for other users.
I have a different solution whereby you do not need to add `sudo` as an alias. I run Linux Mint 17.3 but it should be pretty similar to Ubuntu. When you are root, then the `.profile` is run from its home directory. If you do not know what the home directory under root is, then you can check with: ``` sudo su echo $HOME ``` As you can see, the home of `root` is `/root/`. Check its contents: ``` cd $HOME ls -al ``` There should be a `.profile` file. Open the file and add the following lines: ``` if [ "$BASH" ]; then if [ -f ~/.bash_aliases];then . ~/.bash_aliases fi fi ``` Basically, what this bash script does is to check for a file called `.bash_aliases`. If the files is present, it executes the file. Save the `.profile` file and create your aliases in `.bash_aliases`. If you already have the aliases file ready, then copy the file to this location Re-launch the terminal and you are good to go!
59,903,489
I followed this tutorial <https://forge.autodesk.com/blog/forge-aspnet-zero-hero-30-minutes> and made a web application that can upload and view a model, but I cannot view an old model without uploading it again as I cannot save the URN of the file to send it to viewer again. So, how can I get and save the URN of the file to use it whenever I want to view the model without uploading it again?
2020/01/24
[ "https://Stackoverflow.com/questions/59903489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12777711/" ]
*Object ID* is typically retrieved using the [Data Management APIs](https://forge.autodesk.com/en/docs/data/v2/reference/http/), for example, when [listing contents of a bucket](https://forge.autodesk.com/en/docs/data/v2/reference/http/buckets-:bucketKey-objects-GET). *URN* is then obtained by base64-encoding the object ID. Here's an [example](https://github.com/petrbroz/learn.forge.viewmodels/blob/net/forgesample/Controllers/OSSController.cs#L157-L161) of how you can base64-encode strings in C#.
I would highly suggest to follow the new [Tutorial](https://learnforge.autodesk.io/#/?id=learn-autodesk-forge). This will give you a better understanding of how things work. If you want to just have the urn of an uploaded model you can just log it into the console at a couple of points. The `showModel(urn)` function in ForgeViewer.js is a good place to do so for example.
2,183,758
I'm confused on a couple of propositions in Bourbaki, Lie Groups and Lie Algebras, Chapter 5. We are given a quadratic form $q$ on $V = \mathbb{R}^n$ which is positive, meaning $q(v) \geq 0$ for all $v$. To $q$ we can associate a symmetric, positive bilinear form $$B(v,w) = \frac{1}{2}[q(v+w) - q(v) - q(w)]$$ We recover $q$ as $q(v) = B(v,v)$. By the *kernel* of $q$, I would normally assume we are talking about one of two things: > > 1 . The set of $v \in V$ such that $q(v) = 0$. > > > 2 . The set of $v \in V$ such that $B(v,w) = 0$ for all $w \in W$. > > > It is straightforward that the second set is contained in the first. In the beginning of Lemma 4, they cite a result in Algebra, Chapter IX which says that since $q$ is positive, they are actually equal. I looked up this result, I still can't figure out if it actually implies what is claimed. Anyway. On the other hand, in the beginning of the proof of Lemma 4, they seem to be using yet another definition. They are saying that if $v = |c\_1|a\_1 + \cdots +|c\_n|a\_n$ is in the kernel of $q$, then $$\sum\limits\_i q\_{ij}|c\_i| = 0$$ for all $j$. That is...not how you compute $q(v)$. You don't treat $q$ as a linear transformation and multiply the column vector. Right? I thought $q(v)$ would be $$\sum\limits\_{i,j} q\_{ij} |c\_ic\_j| $$ [![enter image description here](https://i.stack.imgur.com/6Xrij.png)](https://i.stack.imgur.com/6Xrij.png) [![enter image description here](https://i.stack.imgur.com/2N8CA.png)](https://i.stack.imgur.com/2N8CA.png)
2017/03/12
[ "https://math.stackexchange.com/questions/2183758", "https://math.stackexchange.com", "https://math.stackexchange.com/users/28556/" ]
Added: it appears that their positive is positive semidefinite. Not hard to adjust the stuff below to semidefinite case your early question, positivity of the quadratic form says that both versions of the kernel are the single vector $0.$ Think of a symmetric positive definite real matrix $M.$ If we have a column vector $X$ with $X^T M X = 0,$ then $X = 0.$ The bilinear form is $$ B(X,Y) = X^T M Y = Y^T M X. $$ If, for fixed $X,$ we always have $$ ( X^T M) Y = 0, $$ we are allowed to take $Y = MX,$ which proves that $$X^T M = 0, M X = 0.$$ Since $M$ is definite, $$ X = 0 $$
Okay, here's what I'm trying to prove. Let $V = \mathbb{R}^n$, let $M$ be an $n$ by $n$ real symmetric matrix such that $m\_{ij} \leq 0$ for all $i \neq j$, and such that $X^TMX \geq 0$ for all column vectors $X$. The following are equivalent for $X$: (i): $X^TMX = 0$; (ii): $MX = 0$; (ii): $X^TMY = 0$ for all column vectors $Y$. (ii) $\Rightarrow$ (iii) is clear, since $(MX)^T = X^TM^T = X^TM$, and one can then multiply on the right by $Y$. (iii) $\Rightarrow$ (i) is also clear. The difficulty for me is showing that (i) $\Rightarrow$ (ii). Proof of (i) $\Rightarrow$ (ii) is the case $n = 2$: Let $M = \begin{pmatrix} a & b \\ b & d \end{pmatrix}$ where $b \leq 0$. If $X = \begin{pmatrix} x \\ y \end{pmatrix}$, then $$X^TMX = ax^2 + 2bxy + dy^2$$ If $M$ is invertible, we already know that (i) and (ii) are equivalent to $X$ being $0$. So we may assume $ad = b^2$. Under the assumption $ax^2 + 2bxy + dy^2 = 0$, multiply by $b$ and use the fact that $2b^2 = ad + b^2$ to get $$0 = abx^2 + 2b^2xy + dy^2 = abx^2 + adxy + b^2xy + dy^2 = (ax + by)(bx + dy)$$ If one of the rows of $M$ is zero, then being symmetric, $M$ must be of the form $\begin{pmatrix} a & 0 \\ 0 & 0 \end{pmatrix}$ or $\begin{pmatrix} 0 & 0 \\ 0 & d \end{pmatrix}$, and these are easy to work out. Otherwise, the determinant of $M$ being zero, we can conclude that $(a,b)$ is a nonzero scalar multiple of $(d,b)$, and so $(ax+by)(bx + dy) = 0$ is equivalent to $ax + by$ and $bx + dy$ both being zero, or in other words, $MX = 0$, which was what I wanted to show.
2,183,758
I'm confused on a couple of propositions in Bourbaki, Lie Groups and Lie Algebras, Chapter 5. We are given a quadratic form $q$ on $V = \mathbb{R}^n$ which is positive, meaning $q(v) \geq 0$ for all $v$. To $q$ we can associate a symmetric, positive bilinear form $$B(v,w) = \frac{1}{2}[q(v+w) - q(v) - q(w)]$$ We recover $q$ as $q(v) = B(v,v)$. By the *kernel* of $q$, I would normally assume we are talking about one of two things: > > 1 . The set of $v \in V$ such that $q(v) = 0$. > > > 2 . The set of $v \in V$ such that $B(v,w) = 0$ for all $w \in W$. > > > It is straightforward that the second set is contained in the first. In the beginning of Lemma 4, they cite a result in Algebra, Chapter IX which says that since $q$ is positive, they are actually equal. I looked up this result, I still can't figure out if it actually implies what is claimed. Anyway. On the other hand, in the beginning of the proof of Lemma 4, they seem to be using yet another definition. They are saying that if $v = |c\_1|a\_1 + \cdots +|c\_n|a\_n$ is in the kernel of $q$, then $$\sum\limits\_i q\_{ij}|c\_i| = 0$$ for all $j$. That is...not how you compute $q(v)$. You don't treat $q$ as a linear transformation and multiply the column vector. Right? I thought $q(v)$ would be $$\sum\limits\_{i,j} q\_{ij} |c\_ic\_j| $$ [![enter image description here](https://i.stack.imgur.com/6Xrij.png)](https://i.stack.imgur.com/6Xrij.png) [![enter image description here](https://i.stack.imgur.com/2N8CA.png)](https://i.stack.imgur.com/2N8CA.png)
2017/03/12
[ "https://math.stackexchange.com/questions/2183758", "https://math.stackexchange.com", "https://math.stackexchange.com/users/28556/" ]
We have $M$ real, symmetric, and positive semidefinite. We may take an orthogonal matrix $P$ such that $ P^T D P = M,$ where $D$ is real diagonal. Let dimension be $n.$ Let the first $n-r$ diagonal elements of $D$ be zero, that is $D\_{jj} = 0$ for $1 \leq j \leq n-r.$ Then $D\_{jj} > 0$ for $n-r+1 \leq j \leq n.$ Your condition (i) reads $X^T M X = 0.$ This becomes $X^T P^T D P X = 0.$ Make a new vector $$ Y = PX. $$ We have $$ Y^T D Y = 0. $$ That is $$ \sum\_{j = n-r+1}^n D\_{jj} \; \; y\_j^2 = 0. $$ Positivity says $$y\_j = 0 \; \; \; \; \mbox{for} \; \; \; \; n-r+1 \leq j \leq n.$$ Alright, for $i \leq n -r+1,$ we have $D\_{ij} = 0.$ So $$ (DY)\_i = \sum\_j D\_{ij} y\_j = 0 \; \; \; \; \mbox{for} \; \; \; \;i \leq n\_r+1. $$ Different for $i \geq n-r.$ $$ (DY)\_i = \sum\_j D\_{ij} y\_j = D\_{ii} y\_i = 0 \; \; \; \; \mbox{for} \; \; \; \;i \geq n\_r. $$ Condition (i) implies $$ DPX = 0. $$ Therefore $$ P^T D P X = 0, $$ $$ MX = 0. $$ This was your condition (ii). This material comes under the general heading of Witt's Theorem; it is easier here because we have the real numbers and semidefiniteness, the "null cone" is just a hyperplane. <https://en.wikipedia.org/wiki/Witt>'s\_theorem [I like the book by Cassels for this material](http://store.doverpublications.com/0486466701.html). I have a copy and used it for something a week ago, now I can't find it. Found it...
Added: it appears that their positive is positive semidefinite. Not hard to adjust the stuff below to semidefinite case your early question, positivity of the quadratic form says that both versions of the kernel are the single vector $0.$ Think of a symmetric positive definite real matrix $M.$ If we have a column vector $X$ with $X^T M X = 0,$ then $X = 0.$ The bilinear form is $$ B(X,Y) = X^T M Y = Y^T M X. $$ If, for fixed $X,$ we always have $$ ( X^T M) Y = 0, $$ we are allowed to take $Y = MX,$ which proves that $$X^T M = 0, M X = 0.$$ Since $M$ is definite, $$ X = 0 $$
2,183,758
I'm confused on a couple of propositions in Bourbaki, Lie Groups and Lie Algebras, Chapter 5. We are given a quadratic form $q$ on $V = \mathbb{R}^n$ which is positive, meaning $q(v) \geq 0$ for all $v$. To $q$ we can associate a symmetric, positive bilinear form $$B(v,w) = \frac{1}{2}[q(v+w) - q(v) - q(w)]$$ We recover $q$ as $q(v) = B(v,v)$. By the *kernel* of $q$, I would normally assume we are talking about one of two things: > > 1 . The set of $v \in V$ such that $q(v) = 0$. > > > 2 . The set of $v \in V$ such that $B(v,w) = 0$ for all $w \in W$. > > > It is straightforward that the second set is contained in the first. In the beginning of Lemma 4, they cite a result in Algebra, Chapter IX which says that since $q$ is positive, they are actually equal. I looked up this result, I still can't figure out if it actually implies what is claimed. Anyway. On the other hand, in the beginning of the proof of Lemma 4, they seem to be using yet another definition. They are saying that if $v = |c\_1|a\_1 + \cdots +|c\_n|a\_n$ is in the kernel of $q$, then $$\sum\limits\_i q\_{ij}|c\_i| = 0$$ for all $j$. That is...not how you compute $q(v)$. You don't treat $q$ as a linear transformation and multiply the column vector. Right? I thought $q(v)$ would be $$\sum\limits\_{i,j} q\_{ij} |c\_ic\_j| $$ [![enter image description here](https://i.stack.imgur.com/6Xrij.png)](https://i.stack.imgur.com/6Xrij.png) [![enter image description here](https://i.stack.imgur.com/2N8CA.png)](https://i.stack.imgur.com/2N8CA.png)
2017/03/12
[ "https://math.stackexchange.com/questions/2183758", "https://math.stackexchange.com", "https://math.stackexchange.com/users/28556/" ]
We have $M$ real, symmetric, and positive semidefinite. We may take an orthogonal matrix $P$ such that $ P^T D P = M,$ where $D$ is real diagonal. Let dimension be $n.$ Let the first $n-r$ diagonal elements of $D$ be zero, that is $D\_{jj} = 0$ for $1 \leq j \leq n-r.$ Then $D\_{jj} > 0$ for $n-r+1 \leq j \leq n.$ Your condition (i) reads $X^T M X = 0.$ This becomes $X^T P^T D P X = 0.$ Make a new vector $$ Y = PX. $$ We have $$ Y^T D Y = 0. $$ That is $$ \sum\_{j = n-r+1}^n D\_{jj} \; \; y\_j^2 = 0. $$ Positivity says $$y\_j = 0 \; \; \; \; \mbox{for} \; \; \; \; n-r+1 \leq j \leq n.$$ Alright, for $i \leq n -r+1,$ we have $D\_{ij} = 0.$ So $$ (DY)\_i = \sum\_j D\_{ij} y\_j = 0 \; \; \; \; \mbox{for} \; \; \; \;i \leq n\_r+1. $$ Different for $i \geq n-r.$ $$ (DY)\_i = \sum\_j D\_{ij} y\_j = D\_{ii} y\_i = 0 \; \; \; \; \mbox{for} \; \; \; \;i \geq n\_r. $$ Condition (i) implies $$ DPX = 0. $$ Therefore $$ P^T D P X = 0, $$ $$ MX = 0. $$ This was your condition (ii). This material comes under the general heading of Witt's Theorem; it is easier here because we have the real numbers and semidefiniteness, the "null cone" is just a hyperplane. <https://en.wikipedia.org/wiki/Witt>'s\_theorem [I like the book by Cassels for this material](http://store.doverpublications.com/0486466701.html). I have a copy and used it for something a week ago, now I can't find it. Found it...
Okay, here's what I'm trying to prove. Let $V = \mathbb{R}^n$, let $M$ be an $n$ by $n$ real symmetric matrix such that $m\_{ij} \leq 0$ for all $i \neq j$, and such that $X^TMX \geq 0$ for all column vectors $X$. The following are equivalent for $X$: (i): $X^TMX = 0$; (ii): $MX = 0$; (ii): $X^TMY = 0$ for all column vectors $Y$. (ii) $\Rightarrow$ (iii) is clear, since $(MX)^T = X^TM^T = X^TM$, and one can then multiply on the right by $Y$. (iii) $\Rightarrow$ (i) is also clear. The difficulty for me is showing that (i) $\Rightarrow$ (ii). Proof of (i) $\Rightarrow$ (ii) is the case $n = 2$: Let $M = \begin{pmatrix} a & b \\ b & d \end{pmatrix}$ where $b \leq 0$. If $X = \begin{pmatrix} x \\ y \end{pmatrix}$, then $$X^TMX = ax^2 + 2bxy + dy^2$$ If $M$ is invertible, we already know that (i) and (ii) are equivalent to $X$ being $0$. So we may assume $ad = b^2$. Under the assumption $ax^2 + 2bxy + dy^2 = 0$, multiply by $b$ and use the fact that $2b^2 = ad + b^2$ to get $$0 = abx^2 + 2b^2xy + dy^2 = abx^2 + adxy + b^2xy + dy^2 = (ax + by)(bx + dy)$$ If one of the rows of $M$ is zero, then being symmetric, $M$ must be of the form $\begin{pmatrix} a & 0 \\ 0 & 0 \end{pmatrix}$ or $\begin{pmatrix} 0 & 0 \\ 0 & d \end{pmatrix}$, and these are easy to work out. Otherwise, the determinant of $M$ being zero, we can conclude that $(a,b)$ is a nonzero scalar multiple of $(d,b)$, and so $(ax+by)(bx + dy) = 0$ is equivalent to $ax + by$ and $bx + dy$ both being zero, or in other words, $MX = 0$, which was what I wanted to show.
172,119
I am trying to write a little voxel engine because it's fun, but struggle to find the best way to store the actual voxels. I'm aware I will need chunks of some sort so I don't need to have the entire world in memory, and I'm am aware I need render them with reasonable performance. I read about octrees and from what I understand it starts with 1 cube, and in that cube can be 8 more cubes, and in all those 8 cubes can be another 8 cubes etc. But I don't think this fits my voxel engine because my voxel cubes/items will all be the exact same size. So another option is to just create an array of 16\*16\*16 size and have that be one chunk, and you fill it with items. And parts where there aren't any items will have 0 as value (0 = air). But I'm afraid this is going to waste a lot of memory and won't be very fast. Then another option is a vector for each chunk, and fill it with cubes. And the cube holds its position in the chunk. This saves memory (no air blocks), but makes looking for a cube at a specific location a lot slower. So I can't really find a good solution, and I'm hoping someone can help me with that. So what would you use and why? But another problem is rendering. Just reading each chunk and sending it to the GPU using OpenGL is easy, but very slow. Generating one mesh per chunk would be better, but that means every time I break one block, I have to rebuild the entire chunk which could take a bit of time causing a minor but noticeable hiccup, which I obviously don't want either. So that would be harder. So how would I render the cubes? Just create all the cubes in one vertex buffer per chunk and render that and maybe try to put that in another thread, or is there another way? Thanks!
2019/05/20
[ "https://gamedev.stackexchange.com/questions/172119", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/-1/" ]
Storing the blocks as the positions and the values is actually very inefficient. Even without any overhead caused by the struct or object you use, you need to store 4 distinct values per block. It would only make sense to use it over the "storing blocks in fixed arrays" method (the one you described earlier) is when only a quarter of the blocks are solid, and this way you don't even take any other optimization methods into account. Octrees are actually great for voxel based games, since they specialize at storing data with larger features (e.g. patches of the same block). To illustrate this, I used a quadtree (basically octrees in 2d): This is my starting set containing 32x32 tiles, which would equal 1024 values: [![enter image description here](https://i.stack.imgur.com/2J6cg.png)](https://i.stack.imgur.com/2J6cg.png) Storing this as 1024 separate values doesn't seem that inefficient, but once you reach map sizes similar to games, such as [Terraria](https://terraria.gamepedia.com/Map_size), loading screens would take multiple seconds. And if you increase it to the third dimension, it starts to use up all space in the system. Quadtrees (or octrees in 3d) can help the situation. To create one, you can either go from tiles and group them together, or go from one huge cell and you divide it until you reach the tiles. I will use the first approach, because it's easier to visualize. So, in the first iteration you group everything into 2x2 cells, and if a cell only contains tiles of the same type, you drop the tiles and just store the type. After one iteration, our map will look like this: [![enter image description here](https://i.stack.imgur.com/0mL51.png)](https://i.stack.imgur.com/0mL51.png) The red lines mark what we store. Each square is just 1 value. This brought the size down from 1024 values to 439, that's a 57% decrease. But you know the [mantra](https://i.kym-cdn.com/photos/images/newsfeed/000/531/557/a88.jpg). Let's go one step further and group these into cells: [![enter image description here](https://i.stack.imgur.com/inefc.png)](https://i.stack.imgur.com/inefc.png) This reduced the amount of stored values to 367. That's only 36% of the original size. You obviously need to do this division until every 4 adjacent cell (8 adjacent block in 3d) inside a chunk is stored inside one cell, essentially converting a chunk to one large cell. This also has some other benefits, mainly when doing collision, but you might want to create a separate octree for that, which only cares about whether a single block is solid or not. That way, instead of checking against collision for every block inside a chunk, you can just do it against the cells.
Octrees exist to solve exactly the problem you describe, allowing dense storage of sparse data without large search times. The fact that your voxels are the same size just means that your octree has a fixed depth. eg. for a 16x16x16 chunk, you need at most 5 levels of tree: * chunk root (16x16x16) + first tier octant (8x8x8) - second tier octant (4x4x4) * third tier octant (2x2x2) + single voxel (1x1x1) This means you have at most 5 steps to go to find out whether there's a voxel at a particular position in the chunk: * chunk root: is the whole chunk the same value (eg. all air)? If so, we're done. If not... + first tier: is the octant that contains this position all the same value? If not... - second tier... * third tier... + now we're addressing a single voxel, and can return its value. Much shorter than scanning even 1% of the way through an array of up to 4096 voxels! Notice that this lets us compress the data wherever there's a full octant of the same value - whether that value is all air or all rock or anything else. It's only where octants contain mixed values that we need to subdivide further, down to the limit of single-voxel leaf nodes. --- For addressing the children of a chunk, typically we'll proceed in [Morton order](https://en.wikipedia.org/wiki/Z-order_curve), something like this: 1. X- Y- Z- 2. X- Y- Z+ 3. X- Y+ Z- 4. X- Y+ Z+ 5. X+ Y- Z- 6. X+ Y- Z+ 7. X+ Y+ Z- 8. X+ Y+ Z+ So, our Octree node navigation might look something like this: ``` GetOctreeValue(OctreeNode node, int depth, int3 nodeOrigin, int3 queryPoint) { if(node.IsAllOneValue) return node.Value; int childIndex = 0; childIndex += (queryPoint.x > nodeOrigin.x) ? 4 : 0; childIndex += (queryPoint.y > nodeOrigin.y) ? 2 : 0; childIndex += (queryPoint.z > nodeOrigin.z) ? 1 : 0; OctreeNode child = node.GetChild(childIndex); return GetOctreeValue( child, depth + 1, nodeOrigin + childOffset[depth, childIndex], queryPoint ); } ```
5,585
In the recycling rules for my community, there is an instruction to thoroughly wash all glass, plastic, and metal containers before depositing them into the recycle bin for collection. Is this step really necessary for the recycling process to occur (or occur without delay)? I've heard that recycling facilities already wash all glass, plastic, and metal material using very effective methods anyhow; why then would the items need to be washed twice?
2011/08/04
[ "https://skeptics.stackexchange.com/questions/5585", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/4322/" ]
Here are comments from two of the major recyclers in Australia: [From VISY](http://www.coolmelbourne.org/articles/2011/07/the-cool-rules-of-recycling/): > > **To rinse or not?** > > > Ever feel like you are wasting a ton of water > while rinsing out your recyclables? According to VISY, it is not > necessary to rinse out containers, but you do need to make sure all > food scraps are removed. > > > [From SITA](http://www.wsn.com.au/dir138/wsn.nsf/Content/Education%20and%20Safety_Facts%20and%20Figures%20Glass) who recently took over WSN: > > Rinse the containers to make sure they are clean and won't attract > pests. > > > [From Planet Ark](http://recyclingweek.planetark.org/recycling-info/how-clean.cfm) (respected environmental group) > > One of the most > common questions about recycling is how clean do jars, cans and pizza > boxes need to be before they can go in the recycling bin. > > > Small amounts of food left don’t interfere with the glass and steel > recycling process. Scrape all the solid food scraps out of jars and > cans and then put them in the recycling bin. If you’re concerned about > having left over food in the bin you can lightly rinse out your jars > and cans. Using left over washing up or rinsing water is best as > there’s no point wasting good water just to wash recycling. > > > Looking at the different methods of processing: **[Aluminium](http://www.wsn.com.au/dir138/wsn.nsf/Content/Education%20and%20Safety_Facts%20and%20Figures%20Aluminium)** > > Heating the aluminium to a temperature of 700°C changes it into a > liquid state. It is then cast into ingots, ready for delivery to > rolling mills where they are milled and remade into new products. > > > **[Glass](http://www.wsn.com.au/dir138/wsn.nsf/Content/Education%20and%20Safety_Facts%20and%20Figures%20Glass)** > > The single-colour cullet is put onto a conveyor belt and goes through > a special process called beneficiation, which removes contamination > such as bottle tops, metals, ceramics and labels. The cullet is then > crushed and sent to a glass furnace where it is added to the mix. > > > **[Plastics](http://www.wsn.com.au/dir138/wsn.nsf/Content/Education%20and%20Safety_Facts%20and%20Figures%20Plastics)** > > The plastics are either shredded, chopped or ground and then washed to > remove further contaminants. The plastic is melted and pushed through > an extruder, a bit like an old fashioned mincer or a spaghetti maker. > It is then cooled and pressed through a die and chopped or pelletised > into granules. It is then ready to be made into new products. > > > It would appear that neither bugs nor food scraps would put a spanner in the works. I assume there would also be some sort of prewash before it got to that stage. It appears that a thorough rinse would be a hygiene thing for your own garbage bin, but not going to affect the process. However it is necessary to remove solid food object.
A 2009 [Slate magazine article](http://www.slate.com/id/2210344/) tackles this question: > > Once you put your recyclables on the curb, they aren't processed right away. > [...] > Now imagine your bottle of half-eaten, four-month-old tartar sauce, lounging about in a stuffy warehouse and getting riper by the day. Not pleasant, is it? > > > The author, Nina Shen Rastogi, goes on to quote an [unreferenced anecdote about an anonymous person's mother-in-law](http://answers.yahoo.com/question/index?qid=20081010063128AAuNXDO) from a competing Q&A site. This emphasizes to me that the Slate article, itself, isn't from a peer-reviewed journal, and is a pretty ordinary reference. Can anyone do better?
5,585
In the recycling rules for my community, there is an instruction to thoroughly wash all glass, plastic, and metal containers before depositing them into the recycle bin for collection. Is this step really necessary for the recycling process to occur (or occur without delay)? I've heard that recycling facilities already wash all glass, plastic, and metal material using very effective methods anyhow; why then would the items need to be washed twice?
2011/08/04
[ "https://skeptics.stackexchange.com/questions/5585", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/4322/" ]
Here are comments from two of the major recyclers in Australia: [From VISY](http://www.coolmelbourne.org/articles/2011/07/the-cool-rules-of-recycling/): > > **To rinse or not?** > > > Ever feel like you are wasting a ton of water > while rinsing out your recyclables? According to VISY, it is not > necessary to rinse out containers, but you do need to make sure all > food scraps are removed. > > > [From SITA](http://www.wsn.com.au/dir138/wsn.nsf/Content/Education%20and%20Safety_Facts%20and%20Figures%20Glass) who recently took over WSN: > > Rinse the containers to make sure they are clean and won't attract > pests. > > > [From Planet Ark](http://recyclingweek.planetark.org/recycling-info/how-clean.cfm) (respected environmental group) > > One of the most > common questions about recycling is how clean do jars, cans and pizza > boxes need to be before they can go in the recycling bin. > > > Small amounts of food left don’t interfere with the glass and steel > recycling process. Scrape all the solid food scraps out of jars and > cans and then put them in the recycling bin. If you’re concerned about > having left over food in the bin you can lightly rinse out your jars > and cans. Using left over washing up or rinsing water is best as > there’s no point wasting good water just to wash recycling. > > > Looking at the different methods of processing: **[Aluminium](http://www.wsn.com.au/dir138/wsn.nsf/Content/Education%20and%20Safety_Facts%20and%20Figures%20Aluminium)** > > Heating the aluminium to a temperature of 700°C changes it into a > liquid state. It is then cast into ingots, ready for delivery to > rolling mills where they are milled and remade into new products. > > > **[Glass](http://www.wsn.com.au/dir138/wsn.nsf/Content/Education%20and%20Safety_Facts%20and%20Figures%20Glass)** > > The single-colour cullet is put onto a conveyor belt and goes through > a special process called beneficiation, which removes contamination > such as bottle tops, metals, ceramics and labels. The cullet is then > crushed and sent to a glass furnace where it is added to the mix. > > > **[Plastics](http://www.wsn.com.au/dir138/wsn.nsf/Content/Education%20and%20Safety_Facts%20and%20Figures%20Plastics)** > > The plastics are either shredded, chopped or ground and then washed to > remove further contaminants. The plastic is melted and pushed through > an extruder, a bit like an old fashioned mincer or a spaghetti maker. > It is then cooled and pressed through a die and chopped or pelletised > into granules. It is then ready to be made into new products. > > > It would appear that neither bugs nor food scraps would put a spanner in the works. I assume there would also be some sort of prewash before it got to that stage. It appears that a thorough rinse would be a hygiene thing for your own garbage bin, but not going to affect the process. However it is necessary to remove solid food object.
As an additional point to the existing excellent answers, if you have commingled recyclables, leaving food on the containers can lead to [paper contamination](https://americanrecyclingca.com/2011/05/paper/contamination-in-paper-recycling/). > > Contamination in paper recycling is a serious issue, with negative effects ranging from the strictly financial, to the health and safety of industry workers. The rapid expansion of recycling programs has seen a commensurate rise in contamination of collected recyclables. The trend towards single-stream curbside recycling (where paper and other recyclables are commingled with refuse and sorted at a processing facility) has brought contamination to the forefront of debate. > > > Contamination in paper recycling can refer to soiling of paper with food, grease, chemicals, or other noxious compounds, or to the inclusion of inappropriate material for the intended paper grade. > > > Simple soiling is easy to understand; once you’ve used a newspaper to soak up transmission fluid, for example, it is no longer recyclable. Food can also be a source of contamination, which often comes as a surprise. The truth of the matter is that it is difficult to separate pizza grease (or other food contaminants) from paper fibers. This is a major issue in the hotly contested debate surrounding single-stream recycling, as food contamination seems inevitable. > > > Even if you're not throwing open cans of spaghetti sauce on your newspapers, if the bin is placed outside, there's a good chance that rain and dew can lead to the contents of the can pouring out over the paper (admittedly, leaving the paper out in the rain seems like it will degrade it anyhow, but that's probably another matter).
41,314,073
When I try to run command like - ``` php artisan db:seed ``` it is saying - ``` ************************************** * Application In Production! * ************************************** Do you really wish to run this command? (yes/no) [no]: ``` My .env file says - ``` .... APP_ENV=local APP_KEY=... APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL=http://localhost .... ``` my app.php file says ``` ... 'env' => env('APP_ENV', 'local'), ... ``` My laravel version is 5.3. What setting should I do to run the application in development mode?
2016/12/24
[ "https://Stackoverflow.com/questions/41314073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6847223/" ]
Your settings are correct. Try to clear config cache: ``` php artisan config:cache ```
Please run the command on the terminal or cmd ``` php artisan up ``` it will come you out of the maintenance mode
574,264
I work on an environment for setting up exercises with zero or more associated hints. If I try to insert verbatim content in the body of the exercise, the latex interpreter hangs without specifying an error. A minimal example that reproduces this issue is shown here: ``` \documentclass{article} \usepackage{listings} \ExplSyntaxOn % Create the exercise environment \NewDocumentEnvironment{ex}{O{}+b}{% \par\noindent #2}{% % End exercise } \ExplSyntaxOff \begin{document} \section{First section} \begin{ex} Create a new virtual working environment for python % When the lstlisting environment below is uncommented % latex hangs with this information in the console: % Package Listings Warning: Text dropped after begin of listing on input line 24. % % % (/home/henrik/.TinyTeX/texmf-dist/tex/latex/base/omscmr.fd)) % * %\begin{lstlisting} %pipenv install opencv-python %\end{lstlisting} \end{ex} \end{document} ``` As I interpret this answer <https://tex.stackexchange.com/a/489459/1366> by David Carlisle it may not be possible to achieve what I want. The syntax I want to use in the final version is as follows ``` \begin{ex} Description of the exercise. Run the following command %\begin{verbatim} %print("Hello world") %\end{verbatim} \begin{hint} Run the example from the command line with the python command \end{hint} \begin{hint} The solution is 42. \end{hint} \end{ex} ``` When parsing this a headline should be included that presents the number of the exercise and includes links to the included hints (two in this case) which are inserted later in the document. To do so I have to parse the content / body of the ex environment. The output should look like this, the code for generating this is included at the end of the question. [![Example output](https://i.stack.imgur.com/vMjdU.png)](https://i.stack.imgur.com/vMjdU.png) ``` \documentclass{article} \usepackage{amsmath} \usepackage[colorlinks, linkcolor=blue, citecolor=blue, urlcolor=blue]{hyperref} \newcounter{ex} \numberwithin{ex}{section} \newcounter{hint} \numberwithin{hint}{ex} \newcounter{solution} \numberwithin{solution}{ex} \makeatletter \newcommand{\linkdest}[1]{\raisebox{1.7\baselineskip}[0pt][0pt]{\hypertarget{#1}{}}} \makeatother \ExplSyntaxOn % Define variables for storing the number of hints % and solutions given in the exercise. \int_new:N \l_hintenv_int \int_new:N \l_solenv_int % Open files for storing hints and solutions. \iow_new:N \g_hintfile_iow \iow_new:N \g_solutionfile_iow \iow_open:Nn \g_hintfile_iow {hintfile.tex} \iow_open:Nn \g_solutionfile_iow {solutionfile.tex} % Define strings to use in macros. \tl_new:N \g_text_solution_tl \tl_set:Nn \g_text_solution_tl { ~Solution:~ } \tl_new:N \g_text_solution_head_tl \tl_set:Nn \g_text_solution_head_tl { Solutino } \tl_new:N \g_text_hint_tl \tl_set:Nn \g_text_hint_tl { ~Hint:~ } \tl_new:N \g_text_exercise_tl \tl_set:Nn \g_text_exercise_tl { Exercise~ } \tl_new:N \g_back_to_exercise_tl \tl_set:Nn \g_back_to_exercise_tl { Back~to~exercise~ } % Create the exercise environment \NewDocumentEnvironment{ex}{O{}+b}{% % Start exercise \bigbreak \refstepcounter{ex} \label{exercise\theex} \noindent \textbf{\g_text_exercise_tl\theex{}:~#1} \hfill % Run a regular expression on the body of the % exercise to count the number of hints present % and store that number in a variable. \regex_count:nnN {\c{begin}\{hint\}} {#2} \l_hintenv_int \regex_count:nnN {\c{begin}\{sol\}} {#2} \l_solenv_int % If at least one hint is provided start a list with % links to the inserted hints. \int_compare:nTF { \l_hintenv_int > 0 } { \g_text_hint_tl } { } % For all integers in the range from one to % the number of inserted hints do. \int_step_variable:nNn {\l_hintenv_int} \l_iterator_tl{ \int_compare:nTF { \l_iterator_tl > 1 } { ,~ } { } \hyperlink{hint\theex.\l_iterator_tl}{\l_iterator_tl} } % If at least one solution is provided start a list with % links to the inserted solutions. \int_compare:nTF { \l_solenv_int > 0 } { \g_text_solution_tl } { } % For all integers in the range from one to % the number of inserted solutions do. \int_step_variable:nNn {\l_solenv_int} \l_iterator_tl{ \int_compare:nTF { \l_iterator_tl > 1 } { ,~ } { } \hyperlink{solution\theex.\l_iterator_tl}{\l_iterator_tl} } \par\noindent #2}{% % End exercise } \NewDocumentEnvironment{hint}{O{}+b}{% % hint start \refstepcounter{hint} \tl_set:Nx \l_temp_tl { hint\thehint } \iow_now:Nx \g_hintfile_iow { \par\noindent} \iow_now:Nx \g_hintfile_iow { \exp_not:N \textbf{Hint~\arabic{hint}~to~exercise~\theex}} \iow_now:Nx \g_hintfile_iow { \hfill \g_back_to_exercise_tl } \iow_now:Nx \g_hintfile_iow { \exp_not:N \ref{exercise\theex } } \iow_now:Nx \g_hintfile_iow { \par\noindent} \iow_now:Nx \g_hintfile_iow { \exp_not:N \linkdest{ \l_temp_tl } } \iow_now:Nx \g_hintfile_iow { \exp_not:N \vspace{-0.4cm}\par\noindent} \iow_now:Nn \g_hintfile_iow { #2 } \iow_now:Nn \g_hintfile_iow { \bigskip} \iow_now:Nn \g_hintfile_iow { \filbreak} }{ % hint end } \NewDocumentEnvironment{sol}{O{}+b}{ % hint start \refstepcounter{solution} \tl_set:Nx \l_temp_tl { solution\thesolution } \iow_now:Nx \g_solutionfile_iow { \par\noindent } \iow_now:Nx \g_solutionfile_iow { \exp_not:N \textbf{Solution~\arabic{solution}~to~exercise~\theex}} \iow_now:Nx \g_solutionfile_iow { \hfill \g_back_to_exercise_tl } \iow_now:Nx \g_solutionfile_iow { \exp_not:N \ref{exercise\theex } } \iow_now:Nx \g_solutionfile_iow { \par\noindent} \iow_now:Nx \g_solutionfile_iow { \exp_not:N \linkdest{ \l_temp_tl } } \iow_now:Nx \g_solutionfile_iow { \exp_not:N \vspace{-0.4cm}\par\noindent} \iow_now:Nn \g_solutionfile_iow { #2 } \iow_now:Nn \g_solutionfile_iow { \bigskip} \iow_now:Nn \g_solutionfile_iow { \filbreak} }{ % hint end } % Define command for closing the two files used % for storing hints and solutions. \NewDocumentCommand{\closehintandsolutionfile}{}{ \iow_close:N \g_hintfile_iow \iow_close:N \g_solutionfile_iow } \ExplSyntaxOff \begin{document} \section{Exercises} \begin{ex} Description of the exercise. Run the following command %\begin{verbatim} %print("Hello world") %\end{verbatim} \begin{hint} Run the example from the command line with the python command \end{hint} \begin{hint} The solution is 42. \end{hint} \end{ex} \closehintandsolutionfile \section{Hints} \input{hintfile.tex} \end{document} ```
2020/12/09
[ "https://tex.stackexchange.com/questions/574264", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/1366/" ]
If all else fails, you can place and save the verbatim into a box before entering the `ex` environment. ``` \documentclass{article} \usepackage{amsmath} \usepackage[colorlinks, linkcolor=blue, citecolor=blue, urlcolor=blue]{hyperref} \newcounter{ex} \numberwithin{ex}{section} \newcounter{hint} \numberwithin{hint}{ex} \newcounter{solution} \numberwithin{solution}{ex} \makeatletter \newcommand{\linkdest}[1]{\raisebox{1.7\baselineskip}[0pt][0pt]{\hypertarget{#1}{}}} \makeatother \ExplSyntaxOn % Define variables for storing the number of hints % and solutions given in the exercise. \int_new:N \l_hintenv_int \int_new:N \l_solenv_int % Open files for storing hints and solutions. \iow_new:N \g_hintfile_iow \iow_new:N \g_solutionfile_iow \iow_open:Nn \g_hintfile_iow {hintfile.tex} \iow_open:Nn \g_solutionfile_iow {solutionfile.tex} % Define strings to use in macros. \tl_new:N \g_text_solution_tl \tl_set:Nn \g_text_solution_tl { ~Solution:~ } \tl_new:N \g_text_solution_head_tl \tl_set:Nn \g_text_solution_head_tl { Solutino } \tl_new:N \g_text_hint_tl \tl_set:Nn \g_text_hint_tl { ~Hint:~ } \tl_new:N \g_text_exercise_tl \tl_set:Nn \g_text_exercise_tl { Exercise~ } \tl_new:N \g_back_to_exercise_tl \tl_set:Nn \g_back_to_exercise_tl { Back~to~exercise~ } % Create the exercise environment \NewDocumentEnvironment{ex}{O{}+b}{% % Start exercise \bigbreak \refstepcounter{ex} \label{exercise\theex} \noindent \textbf{\g_text_exercise_tl\theex{}:~#1} \hfill % Run a regular expression on the body of the % exercise to count the number of hints present % and store that number in a variable. \regex_count:nnN {\c{begin}\{hint\}} {#2} \l_hintenv_int \regex_count:nnN {\c{begin}\{sol\}} {#2} \l_solenv_int % If at least one hint is provided start a list with % links to the inserted hints. \int_compare:nTF { \l_hintenv_int > 0 } { \g_text_hint_tl } { } % For all integers in the range from one to % the number of inserted hints do. \int_step_variable:nNn {\l_hintenv_int} \l_iterator_tl{ \int_compare:nTF { \l_iterator_tl > 1 } { ,~ } { } \hyperlink{hint\theex.\l_iterator_tl}{\l_iterator_tl} } % If at least one solution is provided start a list with % links to the inserted solutions. \int_compare:nTF { \l_solenv_int > 0 } { \g_text_solution_tl } { } % For all integers in the range from one to % the number of inserted solutions do. \int_step_variable:nNn {\l_solenv_int} \l_iterator_tl{ \int_compare:nTF { \l_iterator_tl > 1 } { ,~ } { } \hyperlink{solution\theex.\l_iterator_tl}{\l_iterator_tl} } \par\noindent #2}{% % End exercise } \NewDocumentEnvironment{hint}{O{}+b}{% % hint start \refstepcounter{hint} \tl_set:Nx \l_temp_tl { hint\thehint } \iow_now:Nx \g_hintfile_iow { \par\noindent} \iow_now:Nx \g_hintfile_iow { \exp_not:N \textbf{Hint~\arabic{hint}~to~exercise~\theex}} \iow_now:Nx \g_hintfile_iow { \hfill \g_back_to_exercise_tl } \iow_now:Nx \g_hintfile_iow { \exp_not:N \ref{exercise\theex } } \iow_now:Nx \g_hintfile_iow { \par\noindent} \iow_now:Nx \g_hintfile_iow { \exp_not:N \linkdest{ \l_temp_tl } } \iow_now:Nx \g_hintfile_iow { \exp_not:N \vspace{-0.4cm}\par\noindent} \iow_now:Nn \g_hintfile_iow { #2 } \iow_now:Nn \g_hintfile_iow { \bigskip} \iow_now:Nn \g_hintfile_iow { \filbreak} }{ % hint end } \NewDocumentEnvironment{sol}{O{}+b}{ % hint start \refstepcounter{solution} \tl_set:Nx \l_temp_tl { solution\thesolution } \iow_now:Nx \g_solutionfile_iow { \par\noindent } \iow_now:Nx \g_solutionfile_iow { \exp_not:N \textbf{Solution~\arabic{solution}~to~exercise~\theex}} \iow_now:Nx \g_solutionfile_iow { \hfill \g_back_to_exercise_tl } \iow_now:Nx \g_solutionfile_iow { \exp_not:N \ref{exercise\theex } } \iow_now:Nx \g_solutionfile_iow { \par\noindent} \iow_now:Nx \g_solutionfile_iow { \exp_not:N \linkdest{ \l_temp_tl } } \iow_now:Nx \g_solutionfile_iow { \exp_not:N \vspace{-0.4cm}\par\noindent} \iow_now:Nn \g_solutionfile_iow { #2 } \iow_now:Nn \g_solutionfile_iow { \bigskip} \iow_now:Nn \g_solutionfile_iow { \filbreak} }{ % hint end } % Define command for closing the two files used % for storing hints and solutions. \NewDocumentCommand{\closehintandsolutionfile}{}{ \iow_close:N \g_hintfile_iow \iow_close:N \g_solutionfile_iow } \ExplSyntaxOff \usepackage{verbatimbox} \begin{document} \section{Exercises} \begin{myverbbox}{\hw} print("Hello world") Verbatim &^%$&\content \end{myverbbox} \begin{ex} Description of the exercise. Run the following command \smallskip\noindent\hw \begin{hint} Run the example from the command line with the python command \end{hint} \begin{hint} The solution is 42. \end{hint} \end{ex} \closehintandsolutionfile \section{Hints} \input{hintfile.tex} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/CMRPf.jpg)](https://i.stack.imgur.com/CMRPf.jpg)
If LuaTeX is available, you can store and process verbatim content on Lua side, which helps avoid this problem. ``` \documentclass{article} \usepackage{amsmath} \usepackage{luacode} \usepackage{expl3, xparse} \usepackage[colorlinks, linkcolor=blue, citecolor=blue, urlcolor=blue]{hyperref} \newcounter{ex} \numberwithin{ex}{section} \newcounter{hint} \numberwithin{hint}{ex} \newcounter{solution} \numberwithin{solution}{ex} \makeatletter \newcommand{\linkdest}[1]{\raisebox{1.7\baselineskip}[0pt][0pt]{\hypertarget{#1}{}}} \makeatother \begin{luacode*} verb_table = {} function store_lines (str) texio.write_nl("line:"..str) if string.find (str , [[\end{ex}]] ) then luatexbase.remove_from_callback ( "process_input_buffer" , "store_lines") return [[\end{ex}]] else if str[1] ~= "%" then table.insert(verb_table, str) end end return "" end function register_verbatim() verb_table = {} luatexbase.add_to_callback( "process_input_buffer" , store_lines , "store_lines") end \end{luacode*} \ExplSyntaxOn \newcommand{\CurVerbatim}{} \newcommand{\BeginEx}{ \directlua{ register_verbatim() } } % Define variables for storing the number of hints % and solutions given in the exercise. \int_new:N \l_hintenv_int \int_new:N \l_solenv_int % Open files for storing hints and solutions. \iow_new:N \g_hintfile_iow \iow_new:N \g_solutionfile_iow \iow_open:Nn \g_hintfile_iow {hintfile.tex} \iow_open:Nn \g_solutionfile_iow {solutionfile.tex} % Define strings to use in macros. \tl_new:N \g_text_solution_tl \tl_set:Nn \g_text_solution_tl { ~Solution:~ } \tl_new:N \g_text_solution_head_tl \tl_set:Nn \g_text_solution_head_tl { Solutino } \tl_new:N \g_text_hint_tl \tl_set:Nn \g_text_hint_tl { ~Hint:~ } \tl_new:N \g_text_exercise_tl \tl_set:Nn \g_text_exercise_tl { Exercise~ } \tl_new:N \g_back_to_exercise_tl \tl_set:Nn \g_back_to_exercise_tl { Back~to~exercise~ } \cs_generate_variant:Nn \regex_count:nnN {nVN} % Create the exercise environment \NewDocumentEnvironment{ex}{O{}}{% % Begin excercise % capture verbatim on Lua side \BeginEx }{% % End excercise % retreive the content from lua side % save it in \CurVerbatim \directlua{ token.set_macro("CurVerbatim", table.concat(verb_table, "~")) } \bigbreak \refstepcounter{ex} \label{exercise\theex} \noindent \textbf{\g_text_exercise_tl\theex{}:~#1} \hfill % Run a regular expression on the body of the % exercise to count the number of hints present % and store that number in a variable. \regex_count:nVN {\c{begin}\{hint\}} \CurVerbatim \l_hintenv_int \regex_count:nVN {\c{begin}\{sol\}} \CurVerbatim \l_solenv_int % If at least one hint is provided start a list with % links to the inserted hints. \int_compare:nTF { \l_hintenv_int > 0 } { \g_text_hint_tl } { } % For all integers in the range from one to % the number of inserted hints do. \int_step_variable:nNn {\l_hintenv_int} \l_iterator_tl{ \int_compare:nTF { \l_iterator_tl > 1 } { ,~ } { } \hyperlink{hint\theex.\l_iterator_tl}{\l_iterator_tl} } % If at least one solution is provided start a list with % links to the inserted solutions. \int_compare:nTF { \l_solenv_int > 0 } { \g_text_solution_tl } { } % For all integers in the range from one to % the number of inserted solutions do. \int_step_variable:nNn {\l_solenv_int} \l_iterator_tl{ \int_compare:nTF { \l_iterator_tl > 1 } { ,~ } { } \hyperlink{solution\theex.\l_iterator_tl}{\l_iterator_tl} } \par\noindent % write verbatim content out and read it back \directlua{ local~verb = table.concat(verb_table, "\string\n") local~file = io.open(tex.jobname..".tmp", "w") file:write(verb) file:close() } \input{\jobname.tmp} } \NewDocumentEnvironment{hint}{O{}+b}{% % hint start \refstepcounter{hint} \tl_set:Nx \l_temp_tl { hint\thehint } \iow_now:Nx \g_hintfile_iow { \par\noindent} \iow_now:Nx \g_hintfile_iow { \exp_not:N \textbf{Hint~\arabic{hint}~to~exercise~\theex}} \iow_now:Nx \g_hintfile_iow { \hfill \g_back_to_exercise_tl } \iow_now:Nx \g_hintfile_iow { \exp_not:N \ref{exercise\theex } } \iow_now:Nx \g_hintfile_iow { \par\noindent} \iow_now:Nx \g_hintfile_iow { \exp_not:N \linkdest{ \l_temp_tl } } \iow_now:Nx \g_hintfile_iow { \exp_not:N \vspace{-0.4cm}\par\noindent} \iow_now:Nn \g_hintfile_iow { #2 } \iow_now:Nn \g_hintfile_iow { \bigskip} \iow_now:Nn \g_hintfile_iow { \filbreak} }{ % hint end } \NewDocumentEnvironment{sol}{O{}+b}{ % hint start \refstepcounter{solution} \tl_set:Nx \l_temp_tl { solution\thesolution } \iow_now:Nx \g_solutionfile_iow { \par\noindent } \iow_now:Nx \g_solutionfile_iow { \exp_not:N \textbf{Solution~\arabic{solution}~to~exercise~\theex}} \iow_now:Nx \g_solutionfile_iow { \hfill \g_back_to_exercise_tl } \iow_now:Nx \g_solutionfile_iow { \exp_not:N \ref{exercise\theex } } \iow_now:Nx \g_solutionfile_iow { \par\noindent} \iow_now:Nx \g_solutionfile_iow { \exp_not:N \linkdest{ \l_temp_tl } } \iow_now:Nx \g_solutionfile_iow { \exp_not:N \vspace{-0.4cm}\par\noindent} \iow_now:Nn \g_solutionfile_iow { #2 } \iow_now:Nn \g_solutionfile_iow { \bigskip} \iow_now:Nn \g_solutionfile_iow { \filbreak} }{ % hint end } % Define command for closing the two files used % for storing hints and solutions. \NewDocumentCommand{\closehintandsolutionfile}{}{ \iow_close:N \g_hintfile_iow \iow_close:N \g_solutionfile_iow } \ExplSyntaxOff \begin{document} \section{Exercises} \begin{ex} Description of the exercise. Run the following command \begin{verbatim} print("Hello world") \end{verbatim} % need one blank line after verbatim, otherwise excaptions occur \begin{hint} Run the example from the command line with the python command \end{hint} \begin{hint} The solution is 42. \end{hint} \end{ex} \closehintandsolutionfile \section{Hints} \input{hintfile.tex} \end{document} ```
57,844
In a Hamiltonian system [Chirikov's resonance overlap criterion](http://www.scholarpedia.org/article/Chirikov_criterion) approximately predicts the onset of chaotic behavior. Furthermore in a system where resonances overlap, the strengths of the resonances and their frequency differences can be used to approximate diffusion coefficients (as explored by Chirikov in '79). The overlap criterion is easy to estimate and so often used for physical systems. I was surprised to hear that there are non-linear systems that appear to satisfy a resonance overlap criterion but do not exhibit chaotic behavior. Is there a simple example of such a system? What are the properties of such systems? The site above refers to the Toda lattice but I am not gaining any intuition from it. Some background --- One can describe the KAM theorem in terms decaying Fourier coefficients for the perturbation and iterative perturbation theory for the Hamiltonian system. At some level in the perturbation theory the Fourier coefficients are sufficiently small that they no longer overlap and so the perturbation expansion must converge (and so you get an integrable model or tori). The focus here is on the existence of tori not on the onset of chaos. The reason for my interest is I am tempted to try and classify N-body systems based on width of analyticity of their perturbations (setting the decay rates of their Fourier coefficients) but the easiest way I know to do this is to count resonances and devise a way to estimate when they fill phase space.
2011/08/16
[ "https://math.stackexchange.com/questions/57844", "https://math.stackexchange.com", "https://math.stackexchange.com/users/13292/" ]
This is a very partial answer to your question but let's see if this helps So from a very heuristic perspective in the KAM-case the onset of chaos is a result of the smale horseshoes generated by the homoclinic tangles. Of course not any homoclinic tangle has the generating mechanism for the smale horseshoe and this is where the Chirikov condition comes in. If the underlying system is constructed in such a way that the system satisfies (many) resonances but these resonances are actually symmetries of the system then you can `fool' the Chirikov condition in thinking that chaotic dynamics takes place while the system on the whole might be integrable.
A system with intermittency is a good example. There're actually different attractors that can exist in the system's phase space. These attractors can occasionally appear, disappear and merge with each other. So, u can have a strange attractor (near which the system is actively mixed) in some domain of phase space and limit cycle or torus (predictability and integrability to some extent) in the other domain. Speaking in the language of frequencies and resonancies, this means that u can have resonance overlap at one time, and then some order can emerge in the system so overlapping can not exist anymore... In other words, Chirikov's resonance overlap criterion corresponds to a KAM system. But there would be a completely different situation when higher order terms are included in pertubation series...
129,249
I want to be able to use taskwarrior at work. But the computers at work don't allow me to install anything, they all run Win XP, and IE... So, I would like to somehow SSH to a linux box at home, and do it through a browser. I should mention that I'd be working with a dynamic IP. Is this possible? If so, what is the simplest way to do this?
2014/05/13
[ "https://unix.stackexchange.com/questions/129249", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/23295/" ]
That's simply: ``` tail -fn+1 file ``` `-f` to follow, `-n+1` for tail to start from the first line (the beginning of the file).
Another solution is to use the follow feature in `less`. ``` less -f file ``` You can enter follow mode in `less` by pressing `Shift+f`. `Ctrl+c` exits follow mode at which point the `less` functionality is returned.
25,525,612
I'm newbie and want to implement advanced search, I have two model articles and books and I am using sunspot gem for search this is my articles model ``` class Article < ActiveRecord::Base searchable do text :title text :content end ``` this my books model ``` class Book < ActiveRecord::Base searchable do text :title text :description end ``` I have tried to implement a search form where user can select which category want to search for like this search form ![enter image description here](https://i.stack.imgur.com/xmgNo.png) but I have not get it so I will appreciate any help in how can I do it
2014/08/27
[ "https://Stackoverflow.com/questions/25525612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3304070/" ]
Let's say you want to send notifications by e-mail when a ticket is ready to be reviewed. People responsible for the review are set via a `Reviewer` custom field (which can contain multiple values). Then you can send notifications as follows: ``` var entities = require('@jetbrains/youtrack-scripting-api/entities'); exports.rule = entities.Issue.stateMachine({ title: 'Workflow', fieldName: 'State', states: { 'To Be Reviewed': { onEnter: function(ctx) { var issue = ctx.issue; issue.fields.Reviewer.forEach(function(user) { user.notify("Reminder", "This is a reminder", true); }); }, transitions: {} }, }, requirements: { Reviewer: { type: entities.User.fieldType, multi: true } } }); ```
You can create a custom workflow like the following one: ``` when { if (Interested Parties.isNotEmpty) { for each user in Interested Parties { user.notify("subj", "body"); } } } ``` Another point is that you probably do not need this field since you can 'star' an issue on behalf of a user and the user thus will be notified about any changes. Just type *star user\_name* in the command window.
388,430
I have a given limit that depends on a variable $a$: $$\lim\_{x \rightarrow \infty} \left (\frac{e^{ax}}{1 - ax} \right)$$ I understand cases for $a < 0 \implies \lim = 0$ and $a > 0 \implies \lim = -\infty$. However, for the case $a = 0$, the expression $ax$ which is basically $0\cdot \infty$ in undefined. I somehow know, that the result will be $\lim (\frac{e^0}{1}) = 1$ but I am not sure how to justify that $0\cdot\infty$ is $0$ in this case. Thanks for any ideas or an explanation!
2013/05/11
[ "https://math.stackexchange.com/questions/388430", "https://math.stackexchange.com", "https://math.stackexchange.com/users/43803/" ]
If we choose the value $a=0$ we evaluate the expression $\frac{e^{ax}}{1 - ax}$ before passing to the limit so your result would be $$\lim\_{x\to\infty}\left(\left[\frac{e^{ax}}{1 - ax}\right]\_{a=0}\right)=\lim\_{x\to\infty}\frac{e^0}{1-0}=1$$
There is *no* “indetermination” in $e^{ax}$ when $a=0$: it just means $e^0=1$, because $0x=0$. You don't compute such a limit by plugging in $\infty$ in place of $x$, which wouldn't make sense. You *can*, however, use that 1. $\lim\_{x\to\infty}e^{ax}=\infty$ (for $a>0$); 2. $\lim\_{x\to\infty}e^{ax}=0$ (for $a<0$). But this is different from simply plugging in $\infty$. For instance, in the case of $a<0$, you can conclude that $$ \lim\_{x\to\infty}\frac{e^{ax}}{1-ax}=0 $$ because the numerator has $0$ limit and the denominator has $\infty$ limit. On the other hand, you cannot immediately draw a conclusion in case $a>0$, since the numerator and the denominator have limit $\infty$ and $-\infty$, respectively. For this you can do a simple application of L’Hôpital's theorem: $$ \lim\_{x\to\infty}\frac{e^{ax}}{1-ax} \overset{(H)}{=} \lim\_{x\to\infty}\frac{ae^{ax}}{-a} = \lim\_{x\to\infty}-e^{ax}=-\infty $$ For the case $a=0$ you simply have $$ \lim\_{x\to\infty}\frac{e^{ax}}{1-ax} = \lim\_{x\to\infty}\frac{1}{1}=1 $$
13,898,931
I seem to have hit a bump. I'm creating an "Economy" system for a minecraft bukkit server. I'm trying to order the table by "Richest" first, however the order being received is different. When I run the SQL through phpMyAdmin it is recieved in the correct order ![enter image description here](https://i.stack.imgur.com/b2jSa.jpg) ![enter image description here](https://i.stack.imgur.com/WLcZw.png) ``` public static HashMap<String, Double> topPlayers(String economyKey) { sql.build("SELECT b.balance, p.username FROM " + sql.prefix + "players p INNER JOIN " + sql.prefix + "balances b ON p.id=b.user_id WHERE economy_key=? ORDER BY b.balance DESC LIMIT 0,5"); String[] params = { economyKey }; ResultSet results = sql.executePreparedQuery(params); HashMap<String, Double> players = new HashMap<String, Double>(); try { while (results.next()) { players.put(results.getString("username"), results.getDouble("balance")); } } catch (SQLException e) { e.printStackTrace(); } return players; } ```
2012/12/16
[ "https://Stackoverflow.com/questions/13898931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509091/" ]
You're using HashMap which is not ordered. Try to use a [*List*](http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html) or any other ordered data structure - it'll solve your problem.
You are using a `HashMap` that doesn't gaurante the ordering of elements. This what the API docs for [java.util.HashMap](http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html) says : ***This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.*** You should rather go for a concrete class that implements `SortedMap` interface which is ***A Map that further provides a total ordering on its keys***. For example a `TreeMap` will suffice as it implements the `SortedMap` interface.
66,328,274
I am trying to implement wishlist feature in reactjs, how do we check if clicked product is already in the wishlist array, here is my addToWishlist function, what logic am i missing here? ``` const addToWishlist = (id) => { const check_wishlist = products.findIndex((item) => item.id === id); console.log(check_wishlist); if (check_wishlist !== -1) { wishlist.push({ ...products.find((item) => item.id === id) }); setWishlist([...wishlist]); } else { wishlist.filter((item) => item.id !== id); setWishlist([...wishlist]); } console.log(wishlist); }; ```
2021/02/23
[ "https://Stackoverflow.com/questions/66328274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4531885/" ]
You have 2 error in your code 1: You should not push direct to wishlist 2: wishlist.filter not change value of wishlist ```js const addToWishlist = (id) => { const check_wishlist = wishlist.find((item) => item.id === id); if (!check_wishlist) { const product = products.find((item) => item.id === id); setWishlist([...wishlist, product]); } else { setWishlist(wishlist.filter((item) => item.id !== id)); } console.log(wishlist); }; ```
Array.filter always returns new list, so you need to set the new list not the wishlist. ``` const addToWishlist = (id) => { const check_wishlist = wishlist.findIndex((item) => item.id === id); console.log(check_wishlist); if (check_wishlist !== -1) { setWishlist([ ...wishlist products.find((item) => item.id === id); ]); } else { const newList = wishlist.filter((item) => item.id !== id); setWishlist(newList); } console.log(wishlist); }; ```
715,884
Does Ubuntu 14.04 have its own 'Task Manager'? Like the one in Windows, where you would check what program is using how much and such.
2016/01/02
[ "https://askubuntu.com/questions/715884", "https://askubuntu.com", "https://askubuntu.com/users/488182/" ]
You can use `top`. Just open a terminal enter `top` command and it will show you which process is consuming how much **Memory** and **CPU**. Visit the link it will really help you [12-Top-commands](http://www.tecmint.com/12-top-command-examples-in-linux/)
use the following command ``` gnome-system-monitor ``` if not found then run ``` sudo apt-get install gnome-system-monitor ```
715,884
Does Ubuntu 14.04 have its own 'Task Manager'? Like the one in Windows, where you would check what program is using how much and such.
2016/01/02
[ "https://askubuntu.com/questions/715884", "https://askubuntu.com", "https://askubuntu.com/users/488182/" ]
You can use `top`. Just open a terminal enter `top` command and it will show you which process is consuming how much **Memory** and **CPU**. Visit the link it will really help you [12-Top-commands](http://www.tecmint.com/12-top-command-examples-in-linux/)
The nice thing about the Task Manager in Windows is that you can use a keyboard shortcut to bring it up, even if the computer is frozen. The System Monitor in Ubuntu is accessible from the Dash: click on the Dash and type “System” and it should come up. This, however, is fairly slow: it involves the graphics-heavy Dash and a search through installed programs and files. As [another answer](https://askubuntu.com/a/886852) points out, it may be quicker (and more portable to different versions of Ubuntu), to open the System Monitor from the terminal: just type the command `gnome-system-monitor`. (The Terminal itself can be opened from the Dash, or by the keyboard shortcut `Ctrl`+`Alt`+`T`.) However, the best option is to [create a new keyboard shortcut](https://help.ubuntu.com/stable/ubuntu-help/keyboard-shortcuts-set.html). This option is available from System Settings → Keyboard → Shortcuts → Custom Shortcuts. You’ll want to create a new shortcut with the name `System Monitor` and the command `gnome-system-monitor`. The key combination you choose is up to you (I went with `Ctrl`+`Alt`+`End`). Now you’ll be able to launch the System Monitor even when the computer is freezing.
715,884
Does Ubuntu 14.04 have its own 'Task Manager'? Like the one in Windows, where you would check what program is using how much and such.
2016/01/02
[ "https://askubuntu.com/questions/715884", "https://askubuntu.com", "https://askubuntu.com/users/488182/" ]
Open 'System Monitor' application ; it's very similar to task manager in Windows.
use the following command ``` gnome-system-monitor ``` if not found then run ``` sudo apt-get install gnome-system-monitor ```
715,884
Does Ubuntu 14.04 have its own 'Task Manager'? Like the one in Windows, where you would check what program is using how much and such.
2016/01/02
[ "https://askubuntu.com/questions/715884", "https://askubuntu.com", "https://askubuntu.com/users/488182/" ]
Open 'System Monitor' application ; it's very similar to task manager in Windows.
The nice thing about the Task Manager in Windows is that you can use a keyboard shortcut to bring it up, even if the computer is frozen. The System Monitor in Ubuntu is accessible from the Dash: click on the Dash and type “System” and it should come up. This, however, is fairly slow: it involves the graphics-heavy Dash and a search through installed programs and files. As [another answer](https://askubuntu.com/a/886852) points out, it may be quicker (and more portable to different versions of Ubuntu), to open the System Monitor from the terminal: just type the command `gnome-system-monitor`. (The Terminal itself can be opened from the Dash, or by the keyboard shortcut `Ctrl`+`Alt`+`T`.) However, the best option is to [create a new keyboard shortcut](https://help.ubuntu.com/stable/ubuntu-help/keyboard-shortcuts-set.html). This option is available from System Settings → Keyboard → Shortcuts → Custom Shortcuts. You’ll want to create a new shortcut with the name `System Monitor` and the command `gnome-system-monitor`. The key combination you choose is up to you (I went with `Ctrl`+`Alt`+`End`). Now you’ll be able to launch the System Monitor even when the computer is freezing.
715,884
Does Ubuntu 14.04 have its own 'Task Manager'? Like the one in Windows, where you would check what program is using how much and such.
2016/01/02
[ "https://askubuntu.com/questions/715884", "https://askubuntu.com", "https://askubuntu.com/users/488182/" ]
The nice thing about the Task Manager in Windows is that you can use a keyboard shortcut to bring it up, even if the computer is frozen. The System Monitor in Ubuntu is accessible from the Dash: click on the Dash and type “System” and it should come up. This, however, is fairly slow: it involves the graphics-heavy Dash and a search through installed programs and files. As [another answer](https://askubuntu.com/a/886852) points out, it may be quicker (and more portable to different versions of Ubuntu), to open the System Monitor from the terminal: just type the command `gnome-system-monitor`. (The Terminal itself can be opened from the Dash, or by the keyboard shortcut `Ctrl`+`Alt`+`T`.) However, the best option is to [create a new keyboard shortcut](https://help.ubuntu.com/stable/ubuntu-help/keyboard-shortcuts-set.html). This option is available from System Settings → Keyboard → Shortcuts → Custom Shortcuts. You’ll want to create a new shortcut with the name `System Monitor` and the command `gnome-system-monitor`. The key combination you choose is up to you (I went with `Ctrl`+`Alt`+`End`). Now you’ll be able to launch the System Monitor even when the computer is freezing.
use the following command ``` gnome-system-monitor ``` if not found then run ``` sudo apt-get install gnome-system-monitor ```
4,500,493
A mailman sort 202 letters in N boxes. Does it mean each box contain one letter?
2022/07/26
[ "https://math.stackexchange.com/questions/4500493", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1081577/" ]
No. For example, the mailman could sort all $202$ letters into one box and assuming there are no other boxes, then the mailman has sorted all $202$ letters in $N$ boxes, but each box does not contain one letter.
If $N=1$ Yes If $N>1$ No, because maybe all letters are put in one box and other boxes are empty.
672,936
I have found a brute force python programmatic way of concatenating multiple files while inserting some text characters in between the files. Example: `test_file1 + " \'id#\',\',name,\' " +...+ test_fileN` BUT, is there a way to do this using only BASH commands (sed, grep, cat,...)?
2021/10/12
[ "https://unix.stackexchange.com/questions/672936", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/9932/" ]
I would type : ``` (for a in test_file*; do cat $a;echo " \'id#\',\',name,\' ";done) | sed '$d' ``` You just have to replace the `test_file*` by your actual name list (separated by spaces).
Method using shell builtins `set`, `shift` and `printf`, with no loop: ``` echo " \'id#\',\',name,\' " > /tmp/foo set -- test_file[0-9]* f="$1" shift cat "$1" $(printf '/tmp/foo %s ' "$@") rm /tmp/foo ```
33,314
I'm aware that this is a common question and one that can be quite situational, but I have a few specific questions regarding nuance between these two pronouns for "I". jisho.org describes 俺 as "Male term or language, sounds rough or arrogant". However, based on my knowledge, I'd say that this is the most common pronoun among college and older males (please correct me if I'm wrong, I may just watch too much anime where the characters are over-confident). While I understand that it may sound too colloquial in a formal situation, is 俺 really as arrogant as a dictionary definition makes it out to be? In a similar vein, would 僕 sound overly submissive or weak for an adult male (I'm personally a 20 year old college student), or would it just sound more humble and polite (still colloquial, though)? Last, do people change their pronoun based on the situation? For example, would an adult use 僕 typically around friends/coworkers, but if it's necessary to take a leadership position briefly or make a strong point, switch to 俺 to be more assertive, then back to 僕 when the situation gets more relaxed again?
2016/04/02
[ "https://japanese.stackexchange.com/questions/33314", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/10795/" ]
> > I'd say that this is the most common pronoun among college and older males > > > I wouldn't say it's the most common one, but in a manly/friendly/aggressive environment you might encounter it. In real life speech it's not as common as 僕 and 私 since there are a lot less situations where you can use 俺 safely. It is used *a lot* on the internet, though. It's the most common pronoun I encounter in BBS boards. > > While I understand that it may sound too colloquial in a formal situation, is 俺 really as arrogant as a dictionary definition makes it out to be? > > > In Japanese, the nuance some words carry often changes as your environment changes. It depends on a lot of things; context, the people around you, level of politeness, and so on. If you are at work, you're at a polite setting, so using 俺 would come off as overconfident and arrogant. If you're with your manly mates, it comes off as normal. So it really depends on the context in which you're using it. What's for sure is that it's *definitely not* as common as animes make it out to be and most times it *will* sound rude/inappropriate/arrogant. > > In a similar vein, would 僕 sound overly submissive or weak for an adult male (I'm personally a 20 year old college student), or would it just sound more humble and polite (still colloquial, though)? > > > Again, it depends on the context. Some use it almost all the time, some don't. The nuance it carries is that you're just a normal dude, not much more than that. If you're in a formal setting, it could sound a bit inappropriate in the sense that it might sound weak or rude, but generally you should be able to get away with 僕 in almost every situation. How a speaker perceives someone using 僕 is up to them, but I would advise to avoid it in serious settings(work, business, etc). > > Last, do people change their pronoun based on the situation? > > > I don't think people change their pronoun if they're trying to make some sort of point, it sounds kind of anime-ish and weird. Japanese people don't use personal pronouns that much anyway. In fact, when you can avoid it, you generally should. Tip: don't learn Japanese from anime. It's highly unrealistic.
I typically use 僕 when talking to some one older who I respect. I will use 俺 if I am talking with male friends. I rarely ever use 私 unless Im talking to some one I have just met. Im not a native speaker but I have never had anyone correct me on my usage 僕 is generally only used by younger boys but it can also be used by some one who feels they are young or younger than the person they are talking to 俺 is typically an arrogant way of saying I. People who use it usually have higher self esteem than most and think very highly of themselves. Especially if they use it around other who are not good friends But like I said Im not a native speaker so I could be wrong on some points
33,314
I'm aware that this is a common question and one that can be quite situational, but I have a few specific questions regarding nuance between these two pronouns for "I". jisho.org describes 俺 as "Male term or language, sounds rough or arrogant". However, based on my knowledge, I'd say that this is the most common pronoun among college and older males (please correct me if I'm wrong, I may just watch too much anime where the characters are over-confident). While I understand that it may sound too colloquial in a formal situation, is 俺 really as arrogant as a dictionary definition makes it out to be? In a similar vein, would 僕 sound overly submissive or weak for an adult male (I'm personally a 20 year old college student), or would it just sound more humble and polite (still colloquial, though)? Last, do people change their pronoun based on the situation? For example, would an adult use 僕 typically around friends/coworkers, but if it's necessary to take a leadership position briefly or make a strong point, switch to 俺 to be more assertive, then back to 僕 when the situation gets more relaxed again?
2016/04/02
[ "https://japanese.stackexchange.com/questions/33314", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/10795/" ]
First, I'd like to explain the whole scheme concerning personal pronouns. 1. You are supposed to use Standard Japanese when you speak in public or formal situations and in this case, you basically use 私 (derived from old Tokyo) only. 2. Otherwise, you speak in a dialect of your own. 3. In many areas including most populated ones, people speak New Tokyo dialect, which is almost a virtual standard, and in which people use おれ (derived from Kanto, Tohoku) or ぼく (derived from current Yamaguchi pref.). As for use of おれ or ぼく, the former おれ is (I believe overwhelmingly) more common than ぼく as the first person's pronoun in private speech, but it depends on people. Some people use ぼく among internal societies beside their private use of おれ, like pupil in school(\*1) or athletes in sport industry. But as long as you speak in the same society, switching one to the other is not likely to happen. (\*1) It can be said that ぼく is the standard for elementally school classes.
I typically use 僕 when talking to some one older who I respect. I will use 俺 if I am talking with male friends. I rarely ever use 私 unless Im talking to some one I have just met. Im not a native speaker but I have never had anyone correct me on my usage 僕 is generally only used by younger boys but it can also be used by some one who feels they are young or younger than the person they are talking to 俺 is typically an arrogant way of saying I. People who use it usually have higher self esteem than most and think very highly of themselves. Especially if they use it around other who are not good friends But like I said Im not a native speaker so I could be wrong on some points
33,314
I'm aware that this is a common question and one that can be quite situational, but I have a few specific questions regarding nuance between these two pronouns for "I". jisho.org describes 俺 as "Male term or language, sounds rough or arrogant". However, based on my knowledge, I'd say that this is the most common pronoun among college and older males (please correct me if I'm wrong, I may just watch too much anime where the characters are over-confident). While I understand that it may sound too colloquial in a formal situation, is 俺 really as arrogant as a dictionary definition makes it out to be? In a similar vein, would 僕 sound overly submissive or weak for an adult male (I'm personally a 20 year old college student), or would it just sound more humble and polite (still colloquial, though)? Last, do people change their pronoun based on the situation? For example, would an adult use 僕 typically around friends/coworkers, but if it's necessary to take a leadership position briefly or make a strong point, switch to 俺 to be more assertive, then back to 僕 when the situation gets more relaxed again?
2016/04/02
[ "https://japanese.stackexchange.com/questions/33314", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/10795/" ]
> > I'd say that this is the most common pronoun among college and older males > > > I wouldn't say it's the most common one, but in a manly/friendly/aggressive environment you might encounter it. In real life speech it's not as common as 僕 and 私 since there are a lot less situations where you can use 俺 safely. It is used *a lot* on the internet, though. It's the most common pronoun I encounter in BBS boards. > > While I understand that it may sound too colloquial in a formal situation, is 俺 really as arrogant as a dictionary definition makes it out to be? > > > In Japanese, the nuance some words carry often changes as your environment changes. It depends on a lot of things; context, the people around you, level of politeness, and so on. If you are at work, you're at a polite setting, so using 俺 would come off as overconfident and arrogant. If you're with your manly mates, it comes off as normal. So it really depends on the context in which you're using it. What's for sure is that it's *definitely not* as common as animes make it out to be and most times it *will* sound rude/inappropriate/arrogant. > > In a similar vein, would 僕 sound overly submissive or weak for an adult male (I'm personally a 20 year old college student), or would it just sound more humble and polite (still colloquial, though)? > > > Again, it depends on the context. Some use it almost all the time, some don't. The nuance it carries is that you're just a normal dude, not much more than that. If you're in a formal setting, it could sound a bit inappropriate in the sense that it might sound weak or rude, but generally you should be able to get away with 僕 in almost every situation. How a speaker perceives someone using 僕 is up to them, but I would advise to avoid it in serious settings(work, business, etc). > > Last, do people change their pronoun based on the situation? > > > I don't think people change their pronoun if they're trying to make some sort of point, it sounds kind of anime-ish and weird. Japanese people don't use personal pronouns that much anyway. In fact, when you can avoid it, you generally should. Tip: don't learn Japanese from anime. It's highly unrealistic.
First, I'd like to explain the whole scheme concerning personal pronouns. 1. You are supposed to use Standard Japanese when you speak in public or formal situations and in this case, you basically use 私 (derived from old Tokyo) only. 2. Otherwise, you speak in a dialect of your own. 3. In many areas including most populated ones, people speak New Tokyo dialect, which is almost a virtual standard, and in which people use おれ (derived from Kanto, Tohoku) or ぼく (derived from current Yamaguchi pref.). As for use of おれ or ぼく, the former おれ is (I believe overwhelmingly) more common than ぼく as the first person's pronoun in private speech, but it depends on people. Some people use ぼく among internal societies beside their private use of おれ, like pupil in school(\*1) or athletes in sport industry. But as long as you speak in the same society, switching one to the other is not likely to happen. (\*1) It can be said that ぼく is the standard for elementally school classes.
14,336,734
Because of some reasons I have a spring application which has two client applications written in extjs. One only contains the login page and the other the application logic. In Spring I include them into two jsp pages which I'm using in the controller. The login and the redirect to the application page works fine. But if I logout the logout is done successful but I keep staying on the application page instead of being redirected to the login page. security config: ``` <security:logout logout-url="/main/logoutpage.html" delete-cookies="JSESSIONID" invalidate-session="true" logout-success-url="/test/logout.html"/> ``` Controller: ``` @RequestMapping(value="/test/logout.html",method=RequestMethod.GET) public ModelAndView testLogout(@RequestParam(required=false)Integer error, HttpServletRequest request, HttpServletResponse response){ return new ModelAndView("login"); } ``` "login" is the name of the view which contains the login application. In browser debugging I can see following two communcation: ``` Request URL:http://xx:8080/xx/xx/logoutpage.html?_dc=1358246248972 Request Method:GET Status Code:302 Moved Temporarily Request Headersview source Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Cookie:JSESSIONID=6E22E42CC6835C8A6DFF2535907DEF17 Host:xx:8080 Referer:http://xx:8080/xx/xx/Home.html User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11 X-Requested-With:XMLHttpRequest Query String Parametersview URL encoded _dc:1358246248972 Response Headersview source Content-Length:0 Date:Tue, 15 Jan 2013 10:37:33 GMT Location:http://xx:8080/xx/xx/login.html Server:Apache-Coyote/1.1 Set-Cookie:JSESSIONID=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/xx Request URL:http://xx:8080/xx/xx/login.html Request Method:GET Status Code:200 OK Request Headersview source Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Cookie:JSESSIONID=6E22E42CC6835C8A6DFF2535907DEF17 Host:xx:8080 Referer:http://xx:8080/xx/xx/Home.html User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11 X-Requested-With:XMLHttpRequest Response Headersview source Content-Language:de-DE Content-Length:417 Content-Type:text/html;charset=ISO-8859-1 Date:Tue, 15 Jan 2013 10:37:33 GMT Server:Apache-Coyote/1.1 Set-Cookie:JSESSIONID=532EBEED737BD4172E290F0D10085ED5; Path=/xx/; HttpOnly ``` The second response also contains the login page: ``` <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login</title> <script src="http://extjs.cachefly.net/ext-4.1.1-gpl/ext-all.js"></script> <link rel="stylesheet" href="http://extjs.cachefly.net/ext-4.1.1-gpl/resources/css/ext-all.css"> <script type="text/javascript" src="/xx/main/app/app.js"></script> </head> <body></body> </html> ``` Somebody has an idea why the login page is not shown? Thanks
2013/01/15
[ "https://Stackoverflow.com/questions/14336734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1979942/" ]
Sure it's possible. [`Request.Form`](http://msdn.microsoft.com/en-us/library/system.web.httprequest.form.aspx) is a [`NameValueCollection`](http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx). I suggest reading up on [the documentation](http://msdn.microsoft.com/en-us/library/system.web.httprequest.form.aspx).
It certainly is. The type is a [NameValueCollection](http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx): ``` public string extract(NameValueCollection form) { ... } ```
14,336,734
Because of some reasons I have a spring application which has two client applications written in extjs. One only contains the login page and the other the application logic. In Spring I include them into two jsp pages which I'm using in the controller. The login and the redirect to the application page works fine. But if I logout the logout is done successful but I keep staying on the application page instead of being redirected to the login page. security config: ``` <security:logout logout-url="/main/logoutpage.html" delete-cookies="JSESSIONID" invalidate-session="true" logout-success-url="/test/logout.html"/> ``` Controller: ``` @RequestMapping(value="/test/logout.html",method=RequestMethod.GET) public ModelAndView testLogout(@RequestParam(required=false)Integer error, HttpServletRequest request, HttpServletResponse response){ return new ModelAndView("login"); } ``` "login" is the name of the view which contains the login application. In browser debugging I can see following two communcation: ``` Request URL:http://xx:8080/xx/xx/logoutpage.html?_dc=1358246248972 Request Method:GET Status Code:302 Moved Temporarily Request Headersview source Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Cookie:JSESSIONID=6E22E42CC6835C8A6DFF2535907DEF17 Host:xx:8080 Referer:http://xx:8080/xx/xx/Home.html User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11 X-Requested-With:XMLHttpRequest Query String Parametersview URL encoded _dc:1358246248972 Response Headersview source Content-Length:0 Date:Tue, 15 Jan 2013 10:37:33 GMT Location:http://xx:8080/xx/xx/login.html Server:Apache-Coyote/1.1 Set-Cookie:JSESSIONID=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/xx Request URL:http://xx:8080/xx/xx/login.html Request Method:GET Status Code:200 OK Request Headersview source Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Cookie:JSESSIONID=6E22E42CC6835C8A6DFF2535907DEF17 Host:xx:8080 Referer:http://xx:8080/xx/xx/Home.html User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11 X-Requested-With:XMLHttpRequest Response Headersview source Content-Language:de-DE Content-Length:417 Content-Type:text/html;charset=ISO-8859-1 Date:Tue, 15 Jan 2013 10:37:33 GMT Server:Apache-Coyote/1.1 Set-Cookie:JSESSIONID=532EBEED737BD4172E290F0D10085ED5; Path=/xx/; HttpOnly ``` The second response also contains the login page: ``` <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login</title> <script src="http://extjs.cachefly.net/ext-4.1.1-gpl/ext-all.js"></script> <link rel="stylesheet" href="http://extjs.cachefly.net/ext-4.1.1-gpl/resources/css/ext-all.css"> <script type="text/javascript" src="/xx/main/app/app.js"></script> </head> <body></body> </html> ``` Somebody has an idea why the login page is not shown? Thanks
2013/01/15
[ "https://Stackoverflow.com/questions/14336734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1979942/" ]
Sure it's possible. [`Request.Form`](http://msdn.microsoft.com/en-us/library/system.web.httprequest.form.aspx) is a [`NameValueCollection`](http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx). I suggest reading up on [the documentation](http://msdn.microsoft.com/en-us/library/system.web.httprequest.form.aspx).
Yes you can, It's of type `FormCollection`, which inherits from `NameValueCollection`
14,336,734
Because of some reasons I have a spring application which has two client applications written in extjs. One only contains the login page and the other the application logic. In Spring I include them into two jsp pages which I'm using in the controller. The login and the redirect to the application page works fine. But if I logout the logout is done successful but I keep staying on the application page instead of being redirected to the login page. security config: ``` <security:logout logout-url="/main/logoutpage.html" delete-cookies="JSESSIONID" invalidate-session="true" logout-success-url="/test/logout.html"/> ``` Controller: ``` @RequestMapping(value="/test/logout.html",method=RequestMethod.GET) public ModelAndView testLogout(@RequestParam(required=false)Integer error, HttpServletRequest request, HttpServletResponse response){ return new ModelAndView("login"); } ``` "login" is the name of the view which contains the login application. In browser debugging I can see following two communcation: ``` Request URL:http://xx:8080/xx/xx/logoutpage.html?_dc=1358246248972 Request Method:GET Status Code:302 Moved Temporarily Request Headersview source Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Cookie:JSESSIONID=6E22E42CC6835C8A6DFF2535907DEF17 Host:xx:8080 Referer:http://xx:8080/xx/xx/Home.html User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11 X-Requested-With:XMLHttpRequest Query String Parametersview URL encoded _dc:1358246248972 Response Headersview source Content-Length:0 Date:Tue, 15 Jan 2013 10:37:33 GMT Location:http://xx:8080/xx/xx/login.html Server:Apache-Coyote/1.1 Set-Cookie:JSESSIONID=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/xx Request URL:http://xx:8080/xx/xx/login.html Request Method:GET Status Code:200 OK Request Headersview source Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Cookie:JSESSIONID=6E22E42CC6835C8A6DFF2535907DEF17 Host:xx:8080 Referer:http://xx:8080/xx/xx/Home.html User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11 X-Requested-With:XMLHttpRequest Response Headersview source Content-Language:de-DE Content-Length:417 Content-Type:text/html;charset=ISO-8859-1 Date:Tue, 15 Jan 2013 10:37:33 GMT Server:Apache-Coyote/1.1 Set-Cookie:JSESSIONID=532EBEED737BD4172E290F0D10085ED5; Path=/xx/; HttpOnly ``` The second response also contains the login page: ``` <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login</title> <script src="http://extjs.cachefly.net/ext-4.1.1-gpl/ext-all.js"></script> <link rel="stylesheet" href="http://extjs.cachefly.net/ext-4.1.1-gpl/resources/css/ext-all.css"> <script type="text/javascript" src="/xx/main/app/app.js"></script> </head> <body></body> </html> ``` Somebody has an idea why the login page is not shown? Thanks
2013/01/15
[ "https://Stackoverflow.com/questions/14336734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1979942/" ]
Sure it's possible. [`Request.Form`](http://msdn.microsoft.com/en-us/library/system.web.httprequest.form.aspx) is a [`NameValueCollection`](http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx). I suggest reading up on [the documentation](http://msdn.microsoft.com/en-us/library/system.web.httprequest.form.aspx).
Using the [example in the documentaion](http://msdn.microsoft.com/en-us/library/system.web.httprequest.form.aspx) ``` public string extract(NameValueCollection myRequest) { int loop1; StringBuilder processed_data= new StringBuilder(); // Get names of all forms into a string array. String[] arr1 = myRequest.AllKeys; for (loop1 = 0; loop1 < arr1.Length; loop1++) { data.Append("Form: " + arr1[loop1] + "<br>"); } return processed_data.ToString(); } ```