qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
3,770,781 | What is the overhead in the string structure that causes sizeof() to be 32 ? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387527/"
] | In g++5.2 (in e.g. g++4.9, it is different) a string is basically defined as :
```
class string {
char* bufferp;
size_t length;
union {
char local_buffer[16];
size_t capacity;
};
};
```
On an ordinary computer this adds up to 32 bytes (8+8+16).
The actual definition is of course
```
typedef basic_string<char> string;
```
but the idea is the same. | It is library dependent. You shouldn't rely on the size of `std::string` objects because it is likely to change in different environments (obviously between different standard library vendors, but also between different versions of the same library).
Keep in mind that `std::string` implementations are written by people who have optimized for a variety of use cases, typically leading to 2 internal representations, one for short strings (small internal buffer) and one for long strings (heap-allocated external buffer). The overhead is associated to holding both of these inside each `std::string` object. |
3,770,781 | What is the overhead in the string structure that causes sizeof() to be 32 ? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387527/"
] | `std::string` typically contains a buffer for the "small string optimization" --- if the string is less than the buffer size then no heap allocation is required. | In g++5.2 (in e.g. g++4.9, it is different) a string is basically defined as :
```
class string {
char* bufferp;
size_t length;
union {
char local_buffer[16];
size_t capacity;
};
};
```
On an ordinary computer this adds up to 32 bytes (8+8+16).
The actual definition is of course
```
typedef basic_string<char> string;
```
but the idea is the same. |
3,770,781 | What is the overhead in the string structure that causes sizeof() to be 32 ? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387527/"
] | It is library dependent. You shouldn't rely on the size of `std::string` objects because it is likely to change in different environments (obviously between different standard library vendors, but also between different versions of the same library).
Keep in mind that `std::string` implementations are written by people who have optimized for a variety of use cases, typically leading to 2 internal representations, one for short strings (small internal buffer) and one for long strings (heap-allocated external buffer). The overhead is associated to holding both of these inside each `std::string` object. | Q: Why is a dog yellow?
A: It's not necessarily.
The size of a (an?) std::string object is implementation-dependent. I just checked MS VC++ 2010. It does indeed use 32 bytes for std::string. There is a 16 byte union that contains either the text of the string, if it will fit, or a pointer to heap storage for longer strings. If the implementers had chosen to keep 18 byte strings in the string object rather than on the heap, the size would be 34 bytes. The other 16 bytes comprise overhead, containing such things as the length of the string and the amount of memory currently allocated for the string.
A different implementation might always allocate memory from the heap. Such an implementation would undoubtedly require less memory for the string object. |
3,770,781 | What is the overhead in the string structure that causes sizeof() to be 32 ? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387527/"
] | My guess is:
```
class vector
{
char type;
struct Heap
{
char* start;
char* end;
char* allocatedEnd;
};
struct Stack
{
char size;
char data[27];
}
union
{
Stack stackVersion;
Heap heapVersion;
} version;
};
```
But I bet there are hundreds of ways of doing it. | It is library dependent. You shouldn't rely on the size of `std::string` objects because it is likely to change in different environments (obviously between different standard library vendors, but also between different versions of the same library).
Keep in mind that `std::string` implementations are written by people who have optimized for a variety of use cases, typically leading to 2 internal representations, one for short strings (small internal buffer) and one for long strings (heap-allocated external buffer). The overhead is associated to holding both of these inside each `std::string` object. |
3,770,781 | What is the overhead in the string structure that causes sizeof() to be 32 ? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387527/"
] | Most modern `std::string` implementations1 save very small strings directly on the stack in a statically sized `char` array instead of using dynamic heap storage. This is known as [Small (or Short) String Optimisation](https://stackoverflow.com/q/10315041/1968) (SSO). It allows implementations to avoid heap allocations for small string objects and improves locality of reference.
Furthermore, there will be a `std::size_t` member to save the strings size and a pointer to the actual `char` storage.
How this is specifically implemented differs but something along the following lines works:
```
template <typename T>
struct basic_string {
char* begin_;
size_t size_;
union {
size_t capacity_;
char sso_buffer[16];
};
};
```
On typical architectures where `sizeof (void*)` = 8, this gives us a total size of 32 bytes.
---
1 The βbig threeβ (GCCβs libstdc++ since version 5, Clangβs libc++ and MSVCβs implementation) all do it. Others may too. | It is library dependent. You shouldn't rely on the size of `std::string` objects because it is likely to change in different environments (obviously between different standard library vendors, but also between different versions of the same library).
Keep in mind that `std::string` implementations are written by people who have optimized for a variety of use cases, typically leading to 2 internal representations, one for short strings (small internal buffer) and one for long strings (heap-allocated external buffer). The overhead is associated to holding both of these inside each `std::string` object. |
3,770,781 | What is the overhead in the string structure that causes sizeof() to be 32 ? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387527/"
] | `std::string` typically contains a buffer for the "small string optimization" --- if the string is less than the buffer size then no heap allocation is required. | Q: Why is a dog yellow?
A: It's not necessarily.
The size of a (an?) std::string object is implementation-dependent. I just checked MS VC++ 2010. It does indeed use 32 bytes for std::string. There is a 16 byte union that contains either the text of the string, if it will fit, or a pointer to heap storage for longer strings. If the implementers had chosen to keep 18 byte strings in the string object rather than on the heap, the size would be 34 bytes. The other 16 bytes comprise overhead, containing such things as the length of the string and the amount of memory currently allocated for the string.
A different implementation might always allocate memory from the heap. Such an implementation would undoubtedly require less memory for the string object. |
3,770,781 | What is the overhead in the string structure that causes sizeof() to be 32 ? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387527/"
] | Most modern `std::string` implementations1 save very small strings directly on the stack in a statically sized `char` array instead of using dynamic heap storage. This is known as [Small (or Short) String Optimisation](https://stackoverflow.com/q/10315041/1968) (SSO). It allows implementations to avoid heap allocations for small string objects and improves locality of reference.
Furthermore, there will be a `std::size_t` member to save the strings size and a pointer to the actual `char` storage.
How this is specifically implemented differs but something along the following lines works:
```
template <typename T>
struct basic_string {
char* begin_;
size_t size_;
union {
size_t capacity_;
char sso_buffer[16];
};
};
```
On typical architectures where `sizeof (void*)` = 8, this gives us a total size of 32 bytes.
---
1 The βbig threeβ (GCCβs libstdc++ since version 5, Clangβs libc++ and MSVCβs implementation) all do it. Others may too. | In g++5.2 (in e.g. g++4.9, it is different) a string is basically defined as :
```
class string {
char* bufferp;
size_t length;
union {
char local_buffer[16];
size_t capacity;
};
};
```
On an ordinary computer this adds up to 32 bytes (8+8+16).
The actual definition is of course
```
typedef basic_string<char> string;
```
but the idea is the same. |
3,770,781 | What is the overhead in the string structure that causes sizeof() to be 32 ? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387527/"
] | My guess is:
```
class vector
{
char type;
struct Heap
{
char* start;
char* end;
char* allocatedEnd;
};
struct Stack
{
char size;
char data[27];
}
union
{
Stack stackVersion;
Heap heapVersion;
} version;
};
```
But I bet there are hundreds of ways of doing it. | Q: Why is a dog yellow?
A: It's not necessarily.
The size of a (an?) std::string object is implementation-dependent. I just checked MS VC++ 2010. It does indeed use 32 bytes for std::string. There is a 16 byte union that contains either the text of the string, if it will fit, or a pointer to heap storage for longer strings. If the implementers had chosen to keep 18 byte strings in the string object rather than on the heap, the size would be 34 bytes. The other 16 bytes comprise overhead, containing such things as the length of the string and the amount of memory currently allocated for the string.
A different implementation might always allocate memory from the heap. Such an implementation would undoubtedly require less memory for the string object. |
3,770,781 | What is the overhead in the string structure that causes sizeof() to be 32 ? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387527/"
] | Most modern `std::string` implementations1 save very small strings directly on the stack in a statically sized `char` array instead of using dynamic heap storage. This is known as [Small (or Short) String Optimisation](https://stackoverflow.com/q/10315041/1968) (SSO). It allows implementations to avoid heap allocations for small string objects and improves locality of reference.
Furthermore, there will be a `std::size_t` member to save the strings size and a pointer to the actual `char` storage.
How this is specifically implemented differs but something along the following lines works:
```
template <typename T>
struct basic_string {
char* begin_;
size_t size_;
union {
size_t capacity_;
char sso_buffer[16];
};
};
```
On typical architectures where `sizeof (void*)` = 8, this gives us a total size of 32 bytes.
---
1 The βbig threeβ (GCCβs libstdc++ since version 5, Clangβs libc++ and MSVCβs implementation) all do it. Others may too. | Q: Why is a dog yellow?
A: It's not necessarily.
The size of a (an?) std::string object is implementation-dependent. I just checked MS VC++ 2010. It does indeed use 32 bytes for std::string. There is a 16 byte union that contains either the text of the string, if it will fit, or a pointer to heap storage for longer strings. If the implementers had chosen to keep 18 byte strings in the string object rather than on the heap, the size would be 34 bytes. The other 16 bytes comprise overhead, containing such things as the length of the string and the amount of memory currently allocated for the string.
A different implementation might always allocate memory from the heap. Such an implementation would undoubtedly require less memory for the string object. |
60,440,764 | I have a (n,n,2) numpy array whose elements I want to select based on a (n,n) mask without using loops. Is there a way to vectorize this operation in numpy? Say I have a numpy array
```
X = array([[[18, 8],
[ 9, 2],
[11, 4],
[18, 14]],
[[ 8, 10],
[13, 5],
[13, 6],
[13, 18]],
[[ 8, 4],
[ 2, 13],
[19, 11],
[ 3, 15]],
[[12, 6],
[ 7, 3],
[19, 17],
[ 1, 12]]])
```
and a mask
```
M = array([[1, 0, 0, 0],
[1, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]])
```
Treating each 2-D entry in X as one element, is there a way to use the mask M to select elements of X? That is, select the 2-D element in X if its corresponding element in the mask M is 1.
So the example above will return
```
[
[[18, 8]],
[[ 8, 10],
[13, 5]],
[[19, 11]],
[]
]
``` | 2020/02/27 | [
"https://Stackoverflow.com/questions/60440764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5013900/"
] | You have to find another way to do you backups because max\_allowed\_packet can't be set to that value.
[The doc](https://mariadb.com/kb/en/server-system-variables/#max_allowed_packet) states that the max is 1GB.
Are you sure that you need a value that big? The value should be as big as your biggest blob, not the size of your database.
Having blobs that big can be tricky to handle. | (I'll address your question from many angles. You may not realize how many issues you actually have.)
**Clarification**. So, you have rows bigger than the max allowed for `max_allowed_packet`, and hence for `mysqldump`?
**SELECT**. Can you even `SELECT` those rows? If not, you are in an even bigger pickle.
**Backup**. Refer to <https://dba.stackexchange.com/questions/20/how-can-i-optimize-a-mysqldump-of-a-large-database/2853#2853> for other ways to take a backup. Or <https://dba.stackexchange.com/questions/161708/mysql-database-backup/161886#161886>
**OOM**. How much RAM do you have? I hope it is at least 8GB. Otherwise, you are threatening to blow out RAM.
**Another setting**. If you could get the packet limit to work, keep in mind that `innodb_log_file_size` must be at least 10 times that size. (It is currently only 2G.)
**Pushback**. Here is an argument to give to the devs... If the 'vid' ('video'?) will be provided to end-users via a web server, then it would simpler all around (and solve the 1GB limit) by storing a *link* to a video *file*. Then use `<img ...>` (or whatever) that will reach directly for the file. This will bypass the database, making things faster and simpler.
**Chunking**. I was once forced to store huge things -- even bigger than 4GB. My solution was to divide big data into 50KB chunks (arbitrarily) and have 2 tables -- one with the meta info, one with as many rows as needed to store all the chunks. Messy code, messy database, stupid design. Oh, and I ran into some other limitations. Apache had some max on file size. |
24,792,839 | I'm about to begin cursing at my computer!
I have one program that output a datetime as a string, but I want to feed it into another as a datetime.
The string I get is on the form:
```
dd/MM/yy hh:mm:ss
```
And I would like to find an appropriate way to get a DateTime object back.
I'm thinking something like:
```
string date = "11/07/14 18:19:20";
string dateformat = "dd/MM/yy hh:mm:ss";
DateTime converted_date = DateTime.ParseExact(date,
dateformat, CultureInfo.InvariantCulture);
```
But several of the conversion of dates result in an Exception being thrown back with the message "Not valid timedate".
What am I missing? | 2014/07/17 | [
"https://Stackoverflow.com/questions/24792839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/869148/"
] | The hour is not in 12-hour format. For 24-hour format, it's H.
```
string date = "11/07/14 18:19:20";
string dateformat = "dd/MM/yy H:mm:ss";
DateTime converted_date = DateTime.ParseExact(date,
dateformat, CultureInfo.InvariantCulture);
``` | 'hh' for hour is actually 12 hour clock, 01-12. I think you want 'HH' or 'H' for 24-hour clock ('HH' is zero-padded, 'H' is not). Check out: <http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx> for specific formats. |
12,090 | I know it's been a while so it's not going to be any surprise to hear that I'm handing in my diamond.
As for reasons, it's multifaceted. Certainly I got burnt out on a lot of issues (handling the system tagging issue and the unprotection debacle specifically). However, life also threw me some fun stuff in the form of COVID, and a divorce, depression, and a new relationship. A big factor though is that I stopped playing D&D and all its offshoots and editions quite a while ago, which greatly reduced the amount of things that actively pulled me into engagement on the site.
Regardless though, I considered my experience moderating here positive and, if things change for me, I won't put out the possibility of going for a diamond again in the future if the site will still have me.
I do want to thank the community for electing me and giving me the chance to be your moderator. I think this is a wonderful community and I was lucky to be able to have been your moderator. I hope the community continues to grow and get better.
I won't be deleting my account or anything like that of course, and I'll likely be around very occasionally.
If anybody wanted to contact me, currently the best way to do so is on Discord at rubiksmoose#9728. | 2022/05/23 | [
"https://rpg.meta.stackexchange.com/questions/12090",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/28591/"
] | Well, I for one would like to say
Thank You!
==========
You did an excellent job by us, and we are grateful. All the best! | >
> I felt a great disturbance in the Force...
>
>
>
You have been with us for years. You have been a cornercube we could rely on. And you have been here for all of us. For that I want to wish you
>
> [So Long, and Thanks for All the Fish](https://www.youtube.com/watch?v=ojydNb3Lrrs)
>
>
>
While I feel tempted to ask you to
>
> [Please don't go. The Drones need you. They look up to you.](https://www.youtube.com/watch?v=2FZNPxmTB4o)
>
>
>
I will instead ask you to be the best you you can be and let me apologize for the mischief and grief and infighting the community had over the years. WE weren't always the most easy to handle, I know. So instead, let us part with one of the most magnificent messages a being could leave to someone else - and sorry to quote Douglas Andams twice, he is just too on point:
>
> The first letter was a βwβ, the second an βeβ. Then there was a gap. An βaβ followed, then a βpβ, an βoβ and an βlβ. Marvin paused for a rest. After a few moments they resumed and let him see the βoβ, the βgβ, the βiβ, the βsβ and the βeβ. The next two words were βforβ and βtheβ. The last one was a long one, and Marvin needed another rest before he could tackle it. It started with an βiβ, then βnβ then a βcβ. Next came an βoβ and an βnβ, followed by a βvβ, an βeβ, another βnβ and an βiβ. After a final pause, Marvin gathered his strength for the last stretch. He read the βeβ, the βnβ, the βcβ and at last the final βeβ, and staggered back into their arms.
>
>
> |
12,090 | I know it's been a while so it's not going to be any surprise to hear that I'm handing in my diamond.
As for reasons, it's multifaceted. Certainly I got burnt out on a lot of issues (handling the system tagging issue and the unprotection debacle specifically). However, life also threw me some fun stuff in the form of COVID, and a divorce, depression, and a new relationship. A big factor though is that I stopped playing D&D and all its offshoots and editions quite a while ago, which greatly reduced the amount of things that actively pulled me into engagement on the site.
Regardless though, I considered my experience moderating here positive and, if things change for me, I won't put out the possibility of going for a diamond again in the future if the site will still have me.
I do want to thank the community for electing me and giving me the chance to be your moderator. I think this is a wonderful community and I was lucky to be able to have been your moderator. I hope the community continues to grow and get better.
I won't be deleting my account or anything like that of course, and I'll likely be around very occasionally.
If anybody wanted to contact me, currently the best way to do so is on Discord at rubiksmoose#9728. | 2022/05/23 | [
"https://rpg.meta.stackexchange.com/questions/12090",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/28591/"
] | Well, I for one would like to say
Thank You!
==========
You did an excellent job by us, and we are grateful. All the best! | Rubiks,
Thanks so much for your service to the community.
I remember your amusing icon from my earliest days on RPG.SE. No doubt there's some precipitating story involving a plastic gadget, a hiker taking a rest, a curious elk, and a flash of otherworldly magic....
Best wishes |
12,090 | I know it's been a while so it's not going to be any surprise to hear that I'm handing in my diamond.
As for reasons, it's multifaceted. Certainly I got burnt out on a lot of issues (handling the system tagging issue and the unprotection debacle specifically). However, life also threw me some fun stuff in the form of COVID, and a divorce, depression, and a new relationship. A big factor though is that I stopped playing D&D and all its offshoots and editions quite a while ago, which greatly reduced the amount of things that actively pulled me into engagement on the site.
Regardless though, I considered my experience moderating here positive and, if things change for me, I won't put out the possibility of going for a diamond again in the future if the site will still have me.
I do want to thank the community for electing me and giving me the chance to be your moderator. I think this is a wonderful community and I was lucky to be able to have been your moderator. I hope the community continues to grow and get better.
I won't be deleting my account or anything like that of course, and I'll likely be around very occasionally.
If anybody wanted to contact me, currently the best way to do so is on Discord at rubiksmoose#9728. | 2022/05/23 | [
"https://rpg.meta.stackexchange.com/questions/12090",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/28591/"
] | Well, I for one would like to say
Thank You!
==========
You did an excellent job by us, and we are grateful. All the best! | I must accept being Moose deprived
----------------------------------
I have commented any number of times that I miss our beloved Moose, and I guess we'll miss you some more. I may send you a funny pic now and again on Discord.
Been great having you as part of the voices of reason for as long as you could offer us your most precious gift: your time. |
12,090 | I know it's been a while so it's not going to be any surprise to hear that I'm handing in my diamond.
As for reasons, it's multifaceted. Certainly I got burnt out on a lot of issues (handling the system tagging issue and the unprotection debacle specifically). However, life also threw me some fun stuff in the form of COVID, and a divorce, depression, and a new relationship. A big factor though is that I stopped playing D&D and all its offshoots and editions quite a while ago, which greatly reduced the amount of things that actively pulled me into engagement on the site.
Regardless though, I considered my experience moderating here positive and, if things change for me, I won't put out the possibility of going for a diamond again in the future if the site will still have me.
I do want to thank the community for electing me and giving me the chance to be your moderator. I think this is a wonderful community and I was lucky to be able to have been your moderator. I hope the community continues to grow and get better.
I won't be deleting my account or anything like that of course, and I'll likely be around very occasionally.
If anybody wanted to contact me, currently the best way to do so is on Discord at rubiksmoose#9728. | 2022/05/23 | [
"https://rpg.meta.stackexchange.com/questions/12090",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/28591/"
] | Thanks for being a great co-mod!
--------------------------------
I'm sorry to see you step down as a moderator, but it's totally understandable β it can be a stressful role, and life must come first. You did a great job as moderator; I couldn't have been elected alongside anyone better. (And you're welcome to be reinstated as mod if you ever change your mind.)
Good luck in your future endeavors, and feel free to hit me up on Discord or elsewhere anytime! :) | >
> I felt a great disturbance in the Force...
>
>
>
You have been with us for years. You have been a cornercube we could rely on. And you have been here for all of us. For that I want to wish you
>
> [So Long, and Thanks for All the Fish](https://www.youtube.com/watch?v=ojydNb3Lrrs)
>
>
>
While I feel tempted to ask you to
>
> [Please don't go. The Drones need you. They look up to you.](https://www.youtube.com/watch?v=2FZNPxmTB4o)
>
>
>
I will instead ask you to be the best you you can be and let me apologize for the mischief and grief and infighting the community had over the years. WE weren't always the most easy to handle, I know. So instead, let us part with one of the most magnificent messages a being could leave to someone else - and sorry to quote Douglas Andams twice, he is just too on point:
>
> The first letter was a βwβ, the second an βeβ. Then there was a gap. An βaβ followed, then a βpβ, an βoβ and an βlβ. Marvin paused for a rest. After a few moments they resumed and let him see the βoβ, the βgβ, the βiβ, the βsβ and the βeβ. The next two words were βforβ and βtheβ. The last one was a long one, and Marvin needed another rest before he could tackle it. It started with an βiβ, then βnβ then a βcβ. Next came an βoβ and an βnβ, followed by a βvβ, an βeβ, another βnβ and an βiβ. After a final pause, Marvin gathered his strength for the last stretch. He read the βeβ, the βnβ, the βcβ and at last the final βeβ, and staggered back into their arms.
>
>
> |
12,090 | I know it's been a while so it's not going to be any surprise to hear that I'm handing in my diamond.
As for reasons, it's multifaceted. Certainly I got burnt out on a lot of issues (handling the system tagging issue and the unprotection debacle specifically). However, life also threw me some fun stuff in the form of COVID, and a divorce, depression, and a new relationship. A big factor though is that I stopped playing D&D and all its offshoots and editions quite a while ago, which greatly reduced the amount of things that actively pulled me into engagement on the site.
Regardless though, I considered my experience moderating here positive and, if things change for me, I won't put out the possibility of going for a diamond again in the future if the site will still have me.
I do want to thank the community for electing me and giving me the chance to be your moderator. I think this is a wonderful community and I was lucky to be able to have been your moderator. I hope the community continues to grow and get better.
I won't be deleting my account or anything like that of course, and I'll likely be around very occasionally.
If anybody wanted to contact me, currently the best way to do so is on Discord at rubiksmoose#9728. | 2022/05/23 | [
"https://rpg.meta.stackexchange.com/questions/12090",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/28591/"
] | >
> I felt a great disturbance in the Force...
>
>
>
You have been with us for years. You have been a cornercube we could rely on. And you have been here for all of us. For that I want to wish you
>
> [So Long, and Thanks for All the Fish](https://www.youtube.com/watch?v=ojydNb3Lrrs)
>
>
>
While I feel tempted to ask you to
>
> [Please don't go. The Drones need you. They look up to you.](https://www.youtube.com/watch?v=2FZNPxmTB4o)
>
>
>
I will instead ask you to be the best you you can be and let me apologize for the mischief and grief and infighting the community had over the years. WE weren't always the most easy to handle, I know. So instead, let us part with one of the most magnificent messages a being could leave to someone else - and sorry to quote Douglas Andams twice, he is just too on point:
>
> The first letter was a βwβ, the second an βeβ. Then there was a gap. An βaβ followed, then a βpβ, an βoβ and an βlβ. Marvin paused for a rest. After a few moments they resumed and let him see the βoβ, the βgβ, the βiβ, the βsβ and the βeβ. The next two words were βforβ and βtheβ. The last one was a long one, and Marvin needed another rest before he could tackle it. It started with an βiβ, then βnβ then a βcβ. Next came an βoβ and an βnβ, followed by a βvβ, an βeβ, another βnβ and an βiβ. After a final pause, Marvin gathered his strength for the last stretch. He read the βeβ, the βnβ, the βcβ and at last the final βeβ, and staggered back into their arms.
>
>
> | Rubiks,
Thanks so much for your service to the community.
I remember your amusing icon from my earliest days on RPG.SE. No doubt there's some precipitating story involving a plastic gadget, a hiker taking a rest, a curious elk, and a flash of otherworldly magic....
Best wishes |
12,090 | I know it's been a while so it's not going to be any surprise to hear that I'm handing in my diamond.
As for reasons, it's multifaceted. Certainly I got burnt out on a lot of issues (handling the system tagging issue and the unprotection debacle specifically). However, life also threw me some fun stuff in the form of COVID, and a divorce, depression, and a new relationship. A big factor though is that I stopped playing D&D and all its offshoots and editions quite a while ago, which greatly reduced the amount of things that actively pulled me into engagement on the site.
Regardless though, I considered my experience moderating here positive and, if things change for me, I won't put out the possibility of going for a diamond again in the future if the site will still have me.
I do want to thank the community for electing me and giving me the chance to be your moderator. I think this is a wonderful community and I was lucky to be able to have been your moderator. I hope the community continues to grow and get better.
I won't be deleting my account or anything like that of course, and I'll likely be around very occasionally.
If anybody wanted to contact me, currently the best way to do so is on Discord at rubiksmoose#9728. | 2022/05/23 | [
"https://rpg.meta.stackexchange.com/questions/12090",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/28591/"
] | >
> I felt a great disturbance in the Force...
>
>
>
You have been with us for years. You have been a cornercube we could rely on. And you have been here for all of us. For that I want to wish you
>
> [So Long, and Thanks for All the Fish](https://www.youtube.com/watch?v=ojydNb3Lrrs)
>
>
>
While I feel tempted to ask you to
>
> [Please don't go. The Drones need you. They look up to you.](https://www.youtube.com/watch?v=2FZNPxmTB4o)
>
>
>
I will instead ask you to be the best you you can be and let me apologize for the mischief and grief and infighting the community had over the years. WE weren't always the most easy to handle, I know. So instead, let us part with one of the most magnificent messages a being could leave to someone else - and sorry to quote Douglas Andams twice, he is just too on point:
>
> The first letter was a βwβ, the second an βeβ. Then there was a gap. An βaβ followed, then a βpβ, an βoβ and an βlβ. Marvin paused for a rest. After a few moments they resumed and let him see the βoβ, the βgβ, the βiβ, the βsβ and the βeβ. The next two words were βforβ and βtheβ. The last one was a long one, and Marvin needed another rest before he could tackle it. It started with an βiβ, then βnβ then a βcβ. Next came an βoβ and an βnβ, followed by a βvβ, an βeβ, another βnβ and an βiβ. After a final pause, Marvin gathered his strength for the last stretch. He read the βeβ, the βnβ, the βcβ and at last the final βeβ, and staggered back into their arms.
>
>
> | I must accept being Moose deprived
----------------------------------
I have commented any number of times that I miss our beloved Moose, and I guess we'll miss you some more. I may send you a funny pic now and again on Discord.
Been great having you as part of the voices of reason for as long as you could offer us your most precious gift: your time. |
12,090 | I know it's been a while so it's not going to be any surprise to hear that I'm handing in my diamond.
As for reasons, it's multifaceted. Certainly I got burnt out on a lot of issues (handling the system tagging issue and the unprotection debacle specifically). However, life also threw me some fun stuff in the form of COVID, and a divorce, depression, and a new relationship. A big factor though is that I stopped playing D&D and all its offshoots and editions quite a while ago, which greatly reduced the amount of things that actively pulled me into engagement on the site.
Regardless though, I considered my experience moderating here positive and, if things change for me, I won't put out the possibility of going for a diamond again in the future if the site will still have me.
I do want to thank the community for electing me and giving me the chance to be your moderator. I think this is a wonderful community and I was lucky to be able to have been your moderator. I hope the community continues to grow and get better.
I won't be deleting my account or anything like that of course, and I'll likely be around very occasionally.
If anybody wanted to contact me, currently the best way to do so is on Discord at rubiksmoose#9728. | 2022/05/23 | [
"https://rpg.meta.stackexchange.com/questions/12090",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/28591/"
] | Thanks for being a great co-mod!
--------------------------------
I'm sorry to see you step down as a moderator, but it's totally understandable β it can be a stressful role, and life must come first. You did a great job as moderator; I couldn't have been elected alongside anyone better. (And you're welcome to be reinstated as mod if you ever change your mind.)
Good luck in your future endeavors, and feel free to hit me up on Discord or elsewhere anytime! :) | Rubiks,
Thanks so much for your service to the community.
I remember your amusing icon from my earliest days on RPG.SE. No doubt there's some precipitating story involving a plastic gadget, a hiker taking a rest, a curious elk, and a flash of otherworldly magic....
Best wishes |
12,090 | I know it's been a while so it's not going to be any surprise to hear that I'm handing in my diamond.
As for reasons, it's multifaceted. Certainly I got burnt out on a lot of issues (handling the system tagging issue and the unprotection debacle specifically). However, life also threw me some fun stuff in the form of COVID, and a divorce, depression, and a new relationship. A big factor though is that I stopped playing D&D and all its offshoots and editions quite a while ago, which greatly reduced the amount of things that actively pulled me into engagement on the site.
Regardless though, I considered my experience moderating here positive and, if things change for me, I won't put out the possibility of going for a diamond again in the future if the site will still have me.
I do want to thank the community for electing me and giving me the chance to be your moderator. I think this is a wonderful community and I was lucky to be able to have been your moderator. I hope the community continues to grow and get better.
I won't be deleting my account or anything like that of course, and I'll likely be around very occasionally.
If anybody wanted to contact me, currently the best way to do so is on Discord at rubiksmoose#9728. | 2022/05/23 | [
"https://rpg.meta.stackexchange.com/questions/12090",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/28591/"
] | Thanks for being a great co-mod!
--------------------------------
I'm sorry to see you step down as a moderator, but it's totally understandable β it can be a stressful role, and life must come first. You did a great job as moderator; I couldn't have been elected alongside anyone better. (And you're welcome to be reinstated as mod if you ever change your mind.)
Good luck in your future endeavors, and feel free to hit me up on Discord or elsewhere anytime! :) | I must accept being Moose deprived
----------------------------------
I have commented any number of times that I miss our beloved Moose, and I guess we'll miss you some more. I may send you a funny pic now and again on Discord.
Been great having you as part of the voices of reason for as long as you could offer us your most precious gift: your time. |
74,539,394 | Problem
=======
I have a list of approximatly 200000 nodes that represent lat/lon position in a city and I have to compute the Minimum Spanning Tree. I know that I need to use Prim algorithm but first of all I need a connected graph. (We can assume that those nodes are in a Euclidian plan)
To build this connected graph I thought firstly to compute the complete graph but (205000\*(205000-1)/2 is around 19 billions edges and I can't handle that.
Options
=======
Then I came across to Delaunay triangulation: with the fact that if I build this "Delauney graph", it contains a sub graph that is the Minimum Spanning Tree according and I have a total of around 600000 edges according to [Wikipedia](https://en.wikipedia.org/wiki/Euclidean_minimum_spanning_tree#Two_dimensions) *[..]it has at most 3n-6 edges.* So it may be a good starting point for a Minimum Spanning Tree algorithm.
Another options is to build an approximately connected graph but with that I will maybe miss important edges that will influence my Minimum Spanning Tree.
My question
===========
Is Delaunay a reliable solution in this case? If so, is there any other reliable solution than delaunay triangulation to this problem ?
Further information: this problem has to be solved in C. | 2022/11/22 | [
"https://Stackoverflow.com/questions/74539394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20576185/"
] | The Delaunay triangulation of a point set is always a superset of the EMST of these points. So it is absolutely "reliable"\*. And recommended, as it has a size linear in the number of points and can be efficiently built.
\*When there are cocircular point quadruples, neither the triangulation nor the EMST are uniquely defined, but this is usually harmless. | There's a big question here of what libraries you have access to and how much you trust yourself as a coder. (I'm assuming the fact that you're new on SO should not be taken as a measure of your overall experience as a programmer - if it is, well, RIP.)
If we assume you don't have access to Delaunay and can't implement it yourself, minimum spanning trees algorithms that pre-suppose a graph aren't necessarily off limits to you. You can have the complete graph *conceptually* but not *actually*. Kruskal's algorithm, for instance, assumes you have a sorted list of all edges in your graph; most of your edges will not be near the minimum, and you do not have to compare all `n^2` to find the minimum.
You can find minimum edges quickly by estimations that give you a reduced set, then refinement. For instance, if you divide your graph into a `100*100` grid, for any point `p` in the graph, points in the same grid square as `p` are guaranteed to be closer than points three or more squares away. This gives a much smaller set of points you have to compare to safely know you've found the closest.
It still won't be easy, but that might be easier than Delaunay. |
11,137,677 | Just a quick preparation for my exam, for example I have:
```
f(x) = 5x<sup>2</sup> + 4x * log(x) + 2
```
Would the big O be `O(x<sup>2</sup> + x * log(x))` or should I take consideration of non-logarithmic coefficients such as 5 or 4?
Likewise, consider this code
```
for (int i = 0; i < block.length; i++)
for (int j = 0; j < block.length; j++)
for (int k = 0; k < 5; k++)
g(); //assume worst case time performance of g() is O(1)
```
So would the big O be O(5n2) or O(n2)? | 2012/06/21 | [
"https://Stackoverflow.com/questions/11137677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1359720/"
] | Complexity for `f(x) = 5x^2 + 4xlogx + 2` is `O(x^2)` because
```
O(g(x) + k(x)) = max(O(g(x), k(x))
// and O(X^2) > O(xlogx)
//additionally coeffs are disregarded
O(c*g(x)) = O(g(x))
```
So if you have a sum you just select the largest complexity as at the end of the day, when *n* goes to infinity the largest component will give the most computational load. It also doesn't matter if you have any coeffs because you try to *roughly* estimate what's going to happen.
---
For your other sample see reasoning below
```
for (int i = 0; i < block.length; i++)
for (int j = 0; j < block.length; j++)
for (int k = 0; k < 5; k++)
g(); //assume worst case time performance of g() is O(1)
```
First convert loops into sums and work out the sums from right to left
```
Sum (i=0,n)
Sum(j=0, n)
Sum(k=0, k=5)
1
```
Counter of O(1) from 1 to 5 is still O(1), remember you disregard coeffs
```
Sum(k=0, k=5) 1 = O(5k) = O(1)
```
So you end up with the middle sum, which counts a function of O(1) n times, this gives the complexity of O(n)
```
Sum(j=0, n) 1 = O(n)
```
Finally you get to the leftmost sum and notice that you count *n n*-times, i.e. `n+n+n...`, which is equal to `n*n` or `n^2`
```
Sum (i=0,n) n = O(n^2)
```
So the final answer is O(n^2). | `O(x**2)` because:
`lim n^2 if (x->8) = 8`
`lim 5n^2 if (x->8) = 8`
`8 is infinity`
but if you have the sum of few expressions you need to understood the fastest growing function. it will be an answer on you question.
any other constant before expression will give you the same answer. In that case you should use [asymptotic analysis](http://en.wikipedia.org/wiki/Asymptotic_analysis)
I may give you an advice. If you faced the sum of few function you need:
>
> * decompose your expression on the components
> * imagine the plots of each element
> * understood the fastest growing element which not exceeded the infinite
>
>
>
this element will give you answer |
58,190,850 | I have created a bubble conversation html.
Now I am trying to add a footer to it.
(Footer similar code in <https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_fixed_footer>)
```css
ul {
list-style: none;
margin: 0;
padding: 0;
}
ul li {
display: inline-block;
clear: both;
padding: 5px;
border-radius: 20px;
margin-bottom: 2px;
width: 80%;
background: #eee;
}
.him {
float: left;
border: 1px solid #000000;
}
.me {
float: right;
}
#footer {
height: 30px;
position: fixed;
left: 0;
bottom: 0;
width: 100%;
background-color: red;
color: white;
text-align: center;
}
body {
padding-bottom: 30px;
}
```
```html
<div>
<div>
<ul>
<li class="me">N-19</li>
<li class="me">N-18</li>
<li class="him">N-17</li>
<li class="me">N-16</li>
<li class="me">N-15</li>
<li class="me">N-14</li>
<li class="him">N-13</li>
<li class="me">N-12</li>
<li class="me">N-11</li>
<li class="me">N-10</li>
<li class="me">N-9</li>
<li class="me">N-8</li>
<li class="him">N-7</li>
<li class="me">N-6</li>
<li class="me">N-5</li>
<li class="me">N-4</li>
<li class="me">N-3</li>
<li class="me">N-2</li>
<li class="me">N-1</li>
<li class="him">N</li>
</ul>
</div>
<div id="footer">
Footer
</div>
</div>
```
But I am not seeing the last lines of the conversation. The problem is that the footer is overlaping them because of the float property of the < li > elements.
[](https://i.stack.imgur.com/ICxMx.png)
How can I avoid it? | 2019/10/01 | [
"https://Stackoverflow.com/questions/58190850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2132478/"
] | check this out: `css grid` is a very good property of `css`.
we can divide screen into number of columns and rows . i used here css-grid.
for more info on css-grid read
<https://css-tricks.com/snippets/css/complete-guide-grid/>
```css
ul {
list-style: none;
margin: 0;
padding: 0;
display:grid;
grid-template-columns:33% 33% 34%;
}
ul li {
display: block;
clear: both;
padding: 5px;
border-radius: 20px;
margin-bottom: 2px;
background: #eee;
}
.him {
grid-column:1/3;
border: 1px solid #000000;
}
.me {
grid-column:2/4
}
#footer {
height: 30px;
position: fixed;
bottom:0;
width: 100%;
background-color: red;
color: white;
text-align: center;
}
body {
padding-bottom: 30px;
}
```
```html
<div>
<div>
<ul>
<li class="me">N-19</li>
<li class="me">N-18</li>
<li class="him">N-17</li>
<li class="me">N-16</li>
<li class="me">N-15</li>
<li class="me">N-14</li>
<li class="him">N-13</li>
<li class="me">N-12</li>
<li class="me">N-11</li>
<li class="me">N-10</li>
<li class="me">N-9</li>
<li class="me">N-8</li>
<li class="him">N-7</li>
<li class="me">N-6</li>
<li class="me">N-5</li>
<li class="me">N-4</li>
<li class="me">N-3</li>
<li class="me">N-2</li>
<li class="me">N-1</li>
<li class="him">N</li>
</ul>
</div>
<div id="footer">
Footer
</div>
</div>
``` | Due to `padding-bottom` could not be applied here, my answer didn't fit in the case, therefore I've done a research on the alternatives for a grid layout proposed and, surprisingly, for the `fixed` positioning of the footer block.
In this example I've decided to leave the code without the `<ul>` which has quite a big list of [default element css values](https://www.w3schools.com/cssref/css_default_values.asp). I supposed that the first message always comes from the user, and used `:not()` CSS selector to style the replies blocks. You can change `.user` and `:not(user)` to any classes like `.me` and `.him` according to your HTML.
```css
section {display:flex;flex-direction:column}
section * {
width: 75%;
border: 1px solid #757575;
border-radius:20px;
padding:2px 10px;
margin-bottom:2px
}
.user {
background:#ccc;
margin-left: auto
}
section :not(.user) {
background:#eee
}
section :not(.user) + .user, .user + :not(.user) {
margin-top:5px
}
footer {
height: 30px;
position: sticky; /* Yes. It works now */
bottom: 0;
background: #000;
color: white;
text-align: center;
line-height: 28px
}
```
```html
<section>
<div class="user">Need some help with HTML</div>
<div class="user">And CSS maybe</div>
<div class="user">Want it to work with long-lenth messages as well, you know. And in all the browsers, even IE...</div>
<div>Sure</div>
<div>Lets test this one</div>
<div>Quite a good in terms of browser support in 2019</div>
<div class="user">Awsome!</div>
<div class="user">Thank you so much</div>
<div>You are welcome</div>
<div class="user">Goodbye</div>
</section>
<footer>
<p>Sticky Footer</p>
</footer>
``` |
24,659,851 | I have this class:
```
class fileUnstructuredView {
private:
void* view;
public:
operator void*() {
return view;
}
};
```
and it can do this:
```
void* melon = vldf::fileUnstructuredView();
```
but it cant do that:
```
int* bambi = vldf::fileUnstructuredView();
//or
int* bambi = (int*)vldf::fileUnstructuredView();
```
instead i have to do
```
int* bambi = (int*)(void*)vldf::fileUnstructuredView();
```
or create another explicit type conversion operator for int\*.
The point is, i want to easily convert the class into various pointer types including all the basic ones and some pod structure types. Is there a way to do that without creating a conversion operator for all of them? The closest thing to what I'm asking that I can think of is the ZeroMemory method that doesn't seem to have any types required for its arguments. | 2014/07/09 | [
"https://Stackoverflow.com/questions/24659851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1314976/"
] | Yes, you can have a conversion function template.
```
template <class T>
operator T*() {
return static_cast<T*>(view);
}
``` | Use a template to allow conversions to all types, and then use `enable_if` to only allow it for POD and basic types.
```
class fileUnstructuredView {
private:
void* view;
public:
template<class T,
class enabled=typename std::enable_if<std::is_pod<T>::value>::type
>
operator T*() { //implicit conversions, so I left the:
return view; //pointer conversion warning
}
template<class T>
T* explicit_cast() { //explicit cast, so we:
return static_cast<T*>(view); //prevent the pointer conversion warning
}
};
```
<http://coliru.stacked-crooked.com/a/774925a1fb3e49f5> |
25,242,700 | I am not sure why the action bar does not appear on my main menu, i already cleaned my project but it still doesn't work.
**the main xml**
```
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
<item android:id="@+id/mainmenu"
android:title="Main Menu"
android:orderInCategory="1"
android:showAsAction="always"/>
<item android:id="@+id/play_actionbar"
android:title="Play"
android:orderInCategory="2"
android:showAsAction="always"/>
<item android:id="@+id/admin_actionbar"
android:title="Admin"
android:orderInCategory="3"
android:showAsAction="always"/>
<item android:id="@+id/video_actiobar"
android:title="Video"
android:orderInCategory="4"
android:showAsAction="always"/>
```
**the java code**
```
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
``` | 2014/08/11 | [
"https://Stackoverflow.com/questions/25242700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3829911/"
] | try this
```
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// TODO Auto-generated method stub
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, (Menu) menu);
return super.onCreateOptionsMenu(menu);
}
``` | change the code to this way and check it works
```
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
```
check the link for more how it works (<http://www.androidhive.info/2013/11/android-working-with-action-bar/>) |
25,242,700 | I am not sure why the action bar does not appear on my main menu, i already cleaned my project but it still doesn't work.
**the main xml**
```
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
<item android:id="@+id/mainmenu"
android:title="Main Menu"
android:orderInCategory="1"
android:showAsAction="always"/>
<item android:id="@+id/play_actionbar"
android:title="Play"
android:orderInCategory="2"
android:showAsAction="always"/>
<item android:id="@+id/admin_actionbar"
android:title="Admin"
android:orderInCategory="3"
android:showAsAction="always"/>
<item android:id="@+id/video_actiobar"
android:title="Video"
android:orderInCategory="4"
android:showAsAction="always"/>
```
**the java code**
```
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
``` | 2014/08/11 | [
"https://Stackoverflow.com/questions/25242700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3829911/"
] | try this
```
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// TODO Auto-generated method stub
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, (Menu) menu);
return super.onCreateOptionsMenu(menu);
}
``` | In your Manifest, for your activity, make sure you declare it has Actionbar:
```
<activity
android:name="com.test.activities.MyActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Holo.Light.DarkActionBar" >
``` |
25,242,700 | I am not sure why the action bar does not appear on my main menu, i already cleaned my project but it still doesn't work.
**the main xml**
```
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
<item android:id="@+id/mainmenu"
android:title="Main Menu"
android:orderInCategory="1"
android:showAsAction="always"/>
<item android:id="@+id/play_actionbar"
android:title="Play"
android:orderInCategory="2"
android:showAsAction="always"/>
<item android:id="@+id/admin_actionbar"
android:title="Admin"
android:orderInCategory="3"
android:showAsAction="always"/>
<item android:id="@+id/video_actiobar"
android:title="Video"
android:orderInCategory="4"
android:showAsAction="always"/>
```
**the java code**
```
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
``` | 2014/08/11 | [
"https://Stackoverflow.com/questions/25242700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3829911/"
] | try this
```
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// TODO Auto-generated method stub
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, (Menu) menu);
return super.onCreateOptionsMenu(menu);
}
``` | You can use [ActionBarsherlock](http://actionbarsherlock.com/) or AppCompat for supporting actionbar for android versions below 3.0 .
For using ABS(actionbarsherlock)
You can extend your activity by `SherlockActivity`
and change your method to
```
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// TODO Auto-generated method stub
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, (Menu) menu);
return super.onCreateOptionsMenu(menu);
}
```
as answered by @Amer Hadi
check here for more details [ActionBar](http://developer.android.com/guide/topics/ui/actionbar.html) |
25,242,700 | I am not sure why the action bar does not appear on my main menu, i already cleaned my project but it still doesn't work.
**the main xml**
```
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
<item android:id="@+id/mainmenu"
android:title="Main Menu"
android:orderInCategory="1"
android:showAsAction="always"/>
<item android:id="@+id/play_actionbar"
android:title="Play"
android:orderInCategory="2"
android:showAsAction="always"/>
<item android:id="@+id/admin_actionbar"
android:title="Admin"
android:orderInCategory="3"
android:showAsAction="always"/>
<item android:id="@+id/video_actiobar"
android:title="Video"
android:orderInCategory="4"
android:showAsAction="always"/>
```
**the java code**
```
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
``` | 2014/08/11 | [
"https://Stackoverflow.com/questions/25242700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3829911/"
] | try this
```
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// TODO Auto-generated method stub
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, (Menu) menu);
return super.onCreateOptionsMenu(menu);
}
``` | try 100% working on 2.2 to 4.4. just add support libraries.
```
activity_main_actions.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<!-- Refresh -->
<item
android:id="@+id/action_refresh"
android:icon="@drawable/ic_action_refresh"
android:title="@string/action_refresh"
app:showAsAction="always"/>
<!-- Help -->
<item
android:id="@+id/action_help"
android:icon="@drawable/ic_action_help"
android:title="@string/action_help"
app:showAsAction="never"/>
<!-- Check updates -->
<item
android:id="@+id/action_check_updates"
android:icon="@drawable/ic_action_refresh"
android:title="@string/action_check_updates"
app:showAsAction="never"/>
```
code in activity:
```
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
``` |
3,048,188 | I want to create and then open a txt file using the ShellExecute command.
I have used this code for years with Delphi 7 and it worked:
```
function Execute(CONST ExeName, Parameters: string): Boolean;
begin
Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
```
Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app from outside IDE, it works fine.
Looks like the debugger has something to say to me, but I don't know what. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3048188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] | Sounds to me like you have the "[debug spawned processes](http://docwiki.embarcadero.com/RADStudio/en/Embarcadero_Debuggers)" option turned on. When that's enabled, the debugger interrupts the new process at the earliest possible time. Press the "run" button to let it continue running.
You can confirm this hypothesis the next time you debug your program. Compare the process ID (2352, in your example) with the list of processes shown by Task Manager. Which process in that list matches the process ID reported by the debugger? | Shot in the dark here, but try running the IDE as administrator, and then not as administrator. That may be a factor. Some users make a shortcut with the administrator option set, so that the auto-update runs successfully. So you may be running the IDE as admin, if you've done that. |
3,048,188 | I want to create and then open a txt file using the ShellExecute command.
I have used this code for years with Delphi 7 and it worked:
```
function Execute(CONST ExeName, Parameters: string): Boolean;
begin
Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
```
Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app from outside IDE, it works fine.
Looks like the debugger has something to say to me, but I don't know what. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3048188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] | Sounds to me like you have the "[debug spawned processes](http://docwiki.embarcadero.com/RADStudio/en/Embarcadero_Debuggers)" option turned on. When that's enabled, the debugger interrupts the new process at the earliest possible time. Press the "run" button to let it continue running.
You can confirm this hypothesis the next time you debug your program. Compare the process ID (2352, in your example) with the list of processes shown by Task Manager. Which process in that list matches the process ID reported by the debugger? | ShellExecuteW solve my problems (XE2/Win7/32bit) with "debug spawned processes" option turned off
:)
mybe because strings and pchar are wide pointer from 2010 |
3,048,188 | I want to create and then open a txt file using the ShellExecute command.
I have used this code for years with Delphi 7 and it worked:
```
function Execute(CONST ExeName, Parameters: string): Boolean;
begin
Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
```
Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app from outside IDE, it works fine.
Looks like the debugger has something to say to me, but I don't know what. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3048188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] | I had a problem yesterday with the debugger crashing my application, but running it outside the IDE it would run fine. I was using packages in my development.
I used [process explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) to verify I found I was loading a copy from another location than expected. I had two copies of the same BPL floating around. Once I removed the one I was not compiling I was fine.
Applying that to this problem, I would check to make sure you don't have any copies of compiled code that includes: .DCU, .DCP, .BPL, .EXE around. Then I would also make sure you you can ctrl-click on "ShellExecute" to and see the declaration. You may have your library path setup in a way that it can't find the source. | ShellExecuteW solve my problems (XE2/Win7/32bit) with "debug spawned processes" option turned off
:)
mybe because strings and pchar are wide pointer from 2010 |
3,048,188 | I want to create and then open a txt file using the ShellExecute command.
I have used this code for years with Delphi 7 and it worked:
```
function Execute(CONST ExeName, Parameters: string): Boolean;
begin
Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
```
Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app from outside IDE, it works fine.
Looks like the debugger has something to say to me, but I don't know what. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3048188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] | Sounds to me like you have the "[debug spawned processes](http://docwiki.embarcadero.com/RADStudio/en/Embarcadero_Debuggers)" option turned on. When that's enabled, the debugger interrupts the new process at the earliest possible time. Press the "run" button to let it continue running.
You can confirm this hypothesis the next time you debug your program. Compare the process ID (2352, in your example) with the list of processes shown by Task Manager. Which process in that list matches the process ID reported by the debugger? | This is not the answer for your question (I vote for Rob Kennedy & Chris Thornton), but you can write your routine in a more compact way:
```
function Executa(const ExeName, Parameters: string): Boolean;
begin
Result :=
(ShellExecute(0, 'open', PChar(ExeName), Pointer(Parameters), nil, SW_SHOWNORMAL) > 32);
end;
```
Note Pointer() instead of PChar() for 4th argument. This is a documented behaviour of PChar/Pointer casts (see help). |
3,048,188 | I want to create and then open a txt file using the ShellExecute command.
I have used this code for years with Delphi 7 and it worked:
```
function Execute(CONST ExeName, Parameters: string): Boolean;
begin
Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
```
Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app from outside IDE, it works fine.
Looks like the debugger has something to say to me, but I don't know what. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3048188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] | Same by me , i solved it by replacing ShellExecute with following:
```
function TformMain.CreateProcessSimple(
sExecutableFilePath : string )
: string;
function GetExeByExtension(sExt : string) : string;
var
sExtDesc:string;
begin
with TRegistry.Create do
begin
try
RootKey:=HKEY_CLASSES_ROOT;
if OpenKeyReadOnly(sExt) then
begin
sExtDesc:=ReadString('') ;
CloseKey;
end;
if sExtDesc <>'' then
begin
if OpenKeyReadOnly(sExtDesc + '\Shell\Open\Command') then
begin
Result:= ReadString('') ;
end
end;
finally
Free;
end;
end;
end;
var
pi: TProcessInformation;
si: TStartupInfo;
fapp: string;
begin
fapp:=GetExeByExtension(ExtractFileExt(sExecutableFilePath));
FillMemory( @si, sizeof( si ), 0 );
si.cb := sizeof( si );
if Pos('%1',fApp)>0 then begin
sExecutableFilePath:=StringReplace(fapp,'%1',sExecutableFilePath,[rfReplaceAll]);
end else begin
sExecutableFilePath:=fApp+' "'+sExecutableFilePath+'"';
end;
CreateProcess(
Nil,
// path to the executable file:
PChar( sExecutableFilePath ),
Nil, Nil, False,
NORMAL_PRIORITY_CLASS, Nil, Nil,
si, pi );
// "after calling code" such as
// the code to wait until the
// process is done should go here
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
end;
``` | ShellExecuteW solve my problems (XE2/Win7/32bit) with "debug spawned processes" option turned off
:)
mybe because strings and pchar are wide pointer from 2010 |
3,048,188 | I want to create and then open a txt file using the ShellExecute command.
I have used this code for years with Delphi 7 and it worked:
```
function Execute(CONST ExeName, Parameters: string): Boolean;
begin
Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
```
Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app from outside IDE, it works fine.
Looks like the debugger has something to say to me, but I don't know what. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3048188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] | Sounds to me like you have the "[debug spawned processes](http://docwiki.embarcadero.com/RADStudio/en/Embarcadero_Debuggers)" option turned on. When that's enabled, the debugger interrupts the new process at the earliest possible time. Press the "run" button to let it continue running.
You can confirm this hypothesis the next time you debug your program. Compare the process ID (2352, in your example) with the list of processes shown by Task Manager. Which process in that list matches the process ID reported by the debugger? | I had a problem yesterday with the debugger crashing my application, but running it outside the IDE it would run fine. I was using packages in my development.
I used [process explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) to verify I found I was loading a copy from another location than expected. I had two copies of the same BPL floating around. Once I removed the one I was not compiling I was fine.
Applying that to this problem, I would check to make sure you don't have any copies of compiled code that includes: .DCU, .DCP, .BPL, .EXE around. Then I would also make sure you you can ctrl-click on "ShellExecute" to and see the declaration. You may have your library path setup in a way that it can't find the source. |
3,048,188 | I want to create and then open a txt file using the ShellExecute command.
I have used this code for years with Delphi 7 and it worked:
```
function Execute(CONST ExeName, Parameters: string): Boolean;
begin
Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
```
Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app from outside IDE, it works fine.
Looks like the debugger has something to say to me, but I don't know what. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3048188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] | Sounds to me like you have the "[debug spawned processes](http://docwiki.embarcadero.com/RADStudio/en/Embarcadero_Debuggers)" option turned on. When that's enabled, the debugger interrupts the new process at the earliest possible time. Press the "run" button to let it continue running.
You can confirm this hypothesis the next time you debug your program. Compare the process ID (2352, in your example) with the list of processes shown by Task Manager. Which process in that list matches the process ID reported by the debugger? | Same by me , i solved it by replacing ShellExecute with following:
```
function TformMain.CreateProcessSimple(
sExecutableFilePath : string )
: string;
function GetExeByExtension(sExt : string) : string;
var
sExtDesc:string;
begin
with TRegistry.Create do
begin
try
RootKey:=HKEY_CLASSES_ROOT;
if OpenKeyReadOnly(sExt) then
begin
sExtDesc:=ReadString('') ;
CloseKey;
end;
if sExtDesc <>'' then
begin
if OpenKeyReadOnly(sExtDesc + '\Shell\Open\Command') then
begin
Result:= ReadString('') ;
end
end;
finally
Free;
end;
end;
end;
var
pi: TProcessInformation;
si: TStartupInfo;
fapp: string;
begin
fapp:=GetExeByExtension(ExtractFileExt(sExecutableFilePath));
FillMemory( @si, sizeof( si ), 0 );
si.cb := sizeof( si );
if Pos('%1',fApp)>0 then begin
sExecutableFilePath:=StringReplace(fapp,'%1',sExecutableFilePath,[rfReplaceAll]);
end else begin
sExecutableFilePath:=fApp+' "'+sExecutableFilePath+'"';
end;
CreateProcess(
Nil,
// path to the executable file:
PChar( sExecutableFilePath ),
Nil, Nil, False,
NORMAL_PRIORITY_CLASS, Nil, Nil,
si, pi );
// "after calling code" such as
// the code to wait until the
// process is done should go here
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
end;
``` |
3,048,188 | I want to create and then open a txt file using the ShellExecute command.
I have used this code for years with Delphi 7 and it worked:
```
function Execute(CONST ExeName, Parameters: string): Boolean;
begin
Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
```
Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app from outside IDE, it works fine.
Looks like the debugger has something to say to me, but I don't know what. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3048188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] | Shot in the dark here, but try running the IDE as administrator, and then not as administrator. That may be a factor. Some users make a shortcut with the administrator option set, so that the auto-update runs successfully. So you may be running the IDE as admin, if you've done that. | ShellExecuteW solve my problems (XE2/Win7/32bit) with "debug spawned processes" option turned off
:)
mybe because strings and pchar are wide pointer from 2010 |
3,048,188 | I want to create and then open a txt file using the ShellExecute command.
I have used this code for years with Delphi 7 and it worked:
```
function Execute(CONST ExeName, Parameters: string): Boolean;
begin
Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
```
Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app from outside IDE, it works fine.
Looks like the debugger has something to say to me, but I don't know what. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3048188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] | This is not the answer for your question (I vote for Rob Kennedy & Chris Thornton), but you can write your routine in a more compact way:
```
function Executa(const ExeName, Parameters: string): Boolean;
begin
Result :=
(ShellExecute(0, 'open', PChar(ExeName), Pointer(Parameters), nil, SW_SHOWNORMAL) > 32);
end;
```
Note Pointer() instead of PChar() for 4th argument. This is a documented behaviour of PChar/Pointer casts (see help). | Shot in the dark here, but try running the IDE as administrator, and then not as administrator. That may be a factor. Some users make a shortcut with the administrator option set, so that the auto-update runs successfully. So you may be running the IDE as admin, if you've done that. |
3,048,188 | I want to create and then open a txt file using the ShellExecute command.
I have used this code for years with Delphi 7 and it worked:
```
function Execute(CONST ExeName, Parameters: string): Boolean;
begin
Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
```
Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app from outside IDE, it works fine.
Looks like the debugger has something to say to me, but I don't know what. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3048188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46207/"
] | This is not the answer for your question (I vote for Rob Kennedy & Chris Thornton), but you can write your routine in a more compact way:
```
function Executa(const ExeName, Parameters: string): Boolean;
begin
Result :=
(ShellExecute(0, 'open', PChar(ExeName), Pointer(Parameters), nil, SW_SHOWNORMAL) > 32);
end;
```
Note Pointer() instead of PChar() for 4th argument. This is a documented behaviour of PChar/Pointer casts (see help). | ShellExecuteW solve my problems (XE2/Win7/32bit) with "debug spawned processes" option turned off
:)
mybe because strings and pchar are wide pointer from 2010 |
22,760,270 | I'm making a scatter plot that uses two different symbols based on a condition in the data.
In a for loop iterating through the rows of the data, if a condition is met a point is plotted with a circle, and if not met the point is plotted with a square:
```
for i in thick.index:
if thick['Interest'][i] == 1:
plt.scatter(thick['NiThickness'][i], thick['GdThickness'][i], marker = 'o', color = 'b')
else:
plt.scatter(thick['NiThickness'][i], thick['GdThickness'][i], marker = 's', color = 'r')
```
where 'Interest' is a column filled with ones and zeros(zeroes?).
I'd like to have one label in the legend for the circles, and one for the squares, but if I declare `label = 'circle'` in the `plt.scatter(...)` command I get as many rows in the legend as there rows in my data file.
Is there a simple trick I'm missing?
Thanks. | 2014/03/31 | [
"https://Stackoverflow.com/questions/22760270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3087409/"
] | FireMonkey images use a 32-bit per pixel schema with 8 bits each for red, green and blue plus an extra 8 bits for transparency, also called an alpha channel. If the value of the alpha channel is #FF the pixel will be opaque, #00 will be completely transparent and values in between will vary the transparency accordingly.
Therefore a colour in FireMonkey (actually a TAlphaColor) can be set with an 8 digit hex number where the bits map to #AARRGGBB where AA is the transparency/alpha channel.
Thus, #FF00FF00 is opaque green and #88FF0000 is semi-transparent red. Any color value in which the first two digits are #00 with be completely transparent.
FireMonkey includes are pre-defined constant claNull for a completely transparent colour.
You can also use the TAlphaColorRec record to access individual colours of a TAlphaColor variable using it's fields, A, R, G and B. E.g.
Red := TAlphaColorRec(MyColour).R;
TAlphaColorRec(MyColour).A := #00; | Yoy can change de background color (simple color) of Image and select it in the MultiResBitmap editor BEFORE load the bipmap image (bitmap with white on background):

Or add real transparency to the image and convert it to PNG.
If you load a PNG with thansparency the editor charge it perfectly.

Regards. |
22,760,270 | I'm making a scatter plot that uses two different symbols based on a condition in the data.
In a for loop iterating through the rows of the data, if a condition is met a point is plotted with a circle, and if not met the point is plotted with a square:
```
for i in thick.index:
if thick['Interest'][i] == 1:
plt.scatter(thick['NiThickness'][i], thick['GdThickness'][i], marker = 'o', color = 'b')
else:
plt.scatter(thick['NiThickness'][i], thick['GdThickness'][i], marker = 's', color = 'r')
```
where 'Interest' is a column filled with ones and zeros(zeroes?).
I'd like to have one label in the legend for the circles, and one for the squares, but if I declare `label = 'circle'` in the `plt.scatter(...)` command I get as many rows in the legend as there rows in my data file.
Is there a simple trick I'm missing?
Thanks. | 2014/03/31 | [
"https://Stackoverflow.com/questions/22760270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3087409/"
] | Yoy can change de background color (simple color) of Image and select it in the MultiResBitmap editor BEFORE load the bipmap image (bitmap with white on background):

Or add real transparency to the image and convert it to PNG.
If you load a PNG with thansparency the editor charge it perfectly.

Regards. | I give a code answer here [Is there an FMX function to set a TImage's transparent color at runtime?](https://stackoverflow.com/questions/22948442/is-there-an-fmx-function-to-set-a-timages-transparent-color-at-runtime) that might solve this problem. It's in C++ with XE5, but I imagine conversion to Delphi should be fairly straightforward. |
22,760,270 | I'm making a scatter plot that uses two different symbols based on a condition in the data.
In a for loop iterating through the rows of the data, if a condition is met a point is plotted with a circle, and if not met the point is plotted with a square:
```
for i in thick.index:
if thick['Interest'][i] == 1:
plt.scatter(thick['NiThickness'][i], thick['GdThickness'][i], marker = 'o', color = 'b')
else:
plt.scatter(thick['NiThickness'][i], thick['GdThickness'][i], marker = 's', color = 'r')
```
where 'Interest' is a column filled with ones and zeros(zeroes?).
I'd like to have one label in the legend for the circles, and one for the squares, but if I declare `label = 'circle'` in the `plt.scatter(...)` command I get as many rows in the legend as there rows in my data file.
Is there a simple trick I'm missing?
Thanks. | 2014/03/31 | [
"https://Stackoverflow.com/questions/22760270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3087409/"
] | FireMonkey images use a 32-bit per pixel schema with 8 bits each for red, green and blue plus an extra 8 bits for transparency, also called an alpha channel. If the value of the alpha channel is #FF the pixel will be opaque, #00 will be completely transparent and values in between will vary the transparency accordingly.
Therefore a colour in FireMonkey (actually a TAlphaColor) can be set with an 8 digit hex number where the bits map to #AARRGGBB where AA is the transparency/alpha channel.
Thus, #FF00FF00 is opaque green and #88FF0000 is semi-transparent red. Any color value in which the first two digits are #00 with be completely transparent.
FireMonkey includes are pre-defined constant claNull for a completely transparent colour.
You can also use the TAlphaColorRec record to access individual colours of a TAlphaColor variable using it's fields, A, R, G and B. E.g.
Red := TAlphaColorRec(MyColour).R;
TAlphaColorRec(MyColour).A := #00; | I give a code answer here [Is there an FMX function to set a TImage's transparent color at runtime?](https://stackoverflow.com/questions/22948442/is-there-an-fmx-function-to-set-a-timages-transparent-color-at-runtime) that might solve this problem. It's in C++ with XE5, but I imagine conversion to Delphi should be fairly straightforward. |
51,320,770 | As shown in the image, the constraints are not visible besides activating them.
I have no idea how to solve this problem.

Thanks.
[Edit]
Here is the XML Code, i haven't changed anything just added the Elements on the Design Tab.
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">
<Button
android:id="@+id/btn_jump"
android:layout_width="128dp"
android:layout_height="48dp"
android:text="Jump Activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1" />
<EditText
android:id="@+id/edt_Name"
android:layout_width="215dp"
android:layout_height="43dp"
android:layout_marginTop="107dp"
android:ems="10"
android:inputType="textPersonName"
android:text=""
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1" />
</android.support.constraint.ConstraintLayout>
``` | 2018/07/13 | [
"https://Stackoverflow.com/questions/51320770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7489860/"
] | It is happen In Android Studio 3.1.3 when We are using appcompact-v7:28.0.0-alpha3 library (It automatically take this library). Open the build.gradle (Module:app) and check in the dependencies that which version of appcompact are you using. If "com.android.support:appcompat-v7:28.0.0-alpha3" then just changed the alpha3 to alpha1 or you can use the previous version 27 also. Now you can see it all component in the blueprint. | Well this is a known **issue in appCompat library version** v7-28.0.0alpha/ which is being used directly with the latest build tools!
there are **two solutions** to this!
either **upgrade your build tools** from your sdk manager's tools tab!
or **second way**
is reverting back to 27.1.1
[](https://i.stack.imgur.com/Z45jG.jpg)
change the highlighted one into as
[](https://i.stack.imgur.com/rOsIG.png) |
51,320,770 | As shown in the image, the constraints are not visible besides activating them.
I have no idea how to solve this problem.

Thanks.
[Edit]
Here is the XML Code, i haven't changed anything just added the Elements on the Design Tab.
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">
<Button
android:id="@+id/btn_jump"
android:layout_width="128dp"
android:layout_height="48dp"
android:text="Jump Activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1" />
<EditText
android:id="@+id/edt_Name"
android:layout_width="215dp"
android:layout_height="43dp"
android:layout_marginTop="107dp"
android:ems="10"
android:inputType="textPersonName"
android:text=""
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1" />
</android.support.constraint.ConstraintLayout>
``` | 2018/07/13 | [
"https://Stackoverflow.com/questions/51320770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7489860/"
] | It is happen In Android Studio 3.1.3 when We are using appcompact-v7:28.0.0-alpha3 library (It automatically take this library). Open the build.gradle (Module:app) and check in the dependencies that which version of appcompact are you using. If "com.android.support:appcompat-v7:28.0.0-alpha3" then just changed the alpha3 to alpha1 or you can use the previous version 27 also. Now you can see it all component in the blueprint. | My version version of Android Studio (v3.1.4) has a slightly different line of code for appcompact with no mention of alpha3
`implementation 'com.android.support:appcompact-v7:28.0.0-rc01'` so i just changed it to
above version 27 and clicked Sync Project With Gradle Files and it now shows the constraints perfectly. |
7,048,472 | I have been using the following to get and email people in my database. The problem is now that the database has over 500+ members the script slows down and SHOWS each member email address in TO: field. I tried a suggestion on another site to use BCC instead but I was wondering isn't there a way to alter this to send the emails individually?
```
$sql = "SELECT * FROM users WHERE system = '101' AND mailing_list = 'yes'";
$result = mysql_query($sql) or die("Unable to execute<br />$sql<br />".mysql_error());
$row = mysql_fetch_array($result);
var_dump($row);
$to .= $row['email'] . "\r\n";
//send email
``` | 2011/08/13 | [
"https://Stackoverflow.com/questions/7048472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892728/"
] | php's mail() is very inefficient, I suggest using something like [phpmailer](http://phpmailer.worxware.com/)
from the manual:
>
> Note:
>
>
> It is worth noting that the mail() function is not suitable for larger
> volumes of email in a loop. This function opens and closes an SMTP
> socket for each email, which is not very efficient.
>
>
> For the sending of large amounts of email, see the Β» PEAR::Mail, and Β»
> PEAR::Mail\_Queue packages.
>
>
> | You need to use PHPMailer as it is meant to be used for just this situation. the trouble with mail() is that it opens and closes a connection after each email. You obviously want to open 1 connection, send all your emails (one by one) and close the connection.
Something like [below](http://www.twmsc2011.com/docs/extending.html):
```
require("class.phpmailer.php");
$mail = new phpmailer();
$mail->From = "list@example.com";
$mail->FromName = "List manager";
$mail->Host = "smtp1.example.com;smtp2.example.com";
$mail->Mailer = "smtp";
@MYSQL_CONNECT("localhost","root","password");
@mysql_select_db("my_company");
$query = "SELECT full_name, email, photo FROM employee WHERE id=$id";
$result = @MYSQL_QUERY($query);
while ($row = mysql_fetch_array ($result))
{
// HTML body
$body = "Hello <font size=\"4\">" . $row["full_name"] . "</font>, <p>";
$body .= "<i>Your</i> personal photograph to this message.<p>";
$body .= "Sincerely, <br>";
$body .= "phpmailer List manager";
// Plain text body (for mail clients that cannot read HTML)
$text_body = "Hello " . $row["full_name"] . ", \n\n";
$text_body .= "Your personal photograph to this message.\n\n";
$text_body .= "Sincerely, \n";
$text_body .= "phpmailer List manager";
$mail->Body = $body;
$mail->AltBody = $text_body;
$mail->AddAddress($row["email"], $row["full_name"]);
$mail->AddStringAttachment($row["photo"], "YourPhoto.jpg");
if(!$mail->Send())
echo "There has been a mail error sending to " . $row["email"] . "<br>";
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
}
``` |
33,473,236 | Hi guys I have a problem displaying my map values. This is my code :
**CustomAdapter:**
```
Map<String, List<Show>> map;
List<Map.Entry<String, List<Show>>> list;
public WorldShowsAdapter(Context context,
Map<String, List<Show>> map) {
this.context = context;
this.map = map;
list = new ArrayList(map.entrySet());
}
@Override
public Map.Entry<String, List<WorldShow>> getItem(int position) {
return list.get(position);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if(convertView == null) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_show_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvShowName = (TextView) convertView.findViewById(R.id.tvShowName);
viewHolder.tvShowName2 = (TextView) convertView.findViewById(R.id.tvShowName2);
viewHolder.btViewAllShows = (MyButton) convertView.findViewById(R.id.btViewAllShows);
viewHolder.rvShows = (RecyclerView) convertView.findViewById(R.id.rvShows);
viewHolder.llBackground = (LinearLayout) convertView.findViewById(R.id.llBackground);
viewHolder.showsManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
viewHolder.rvWorldShows.setLayoutManager(viewHolder.showsManager);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Map.Entry<String, List<Show>> entry = this.getItem(position);
viewHolder.tvShowName.setText(entry.getKey());
List<Show> shows = entry.getValue();
for (Show s: shows) {
viewHolder.tvShowName2.setText(s.getShowTitle());
}
}
private void display(RecyclerView rvWorldShows,
Map<String, List<WorldShow>> catShows,
List<WorldShow> showData) {
WorldDetailsShowsRecyclerViewAdapter showsAdapter
= new WorldDetailsShowsRecyclerViewAdapter(context, catShows, showData);
if(showsAdapter.getItemCount() > 0) {
rvShows.setVisibility(View.VISIBLE);
rvShows.setAdapter(showsAdapter);
} else {
rvShows.setVisibility(View.GONE);
}
}
```
I'm only getting the last value.
When I changed to this:
```
viewHolder.tvShowName2.setText(entry.getValue().toString());
```
It's displaying this:
```
[Talk=[
com.test.models.Show@fe6eb61,
com.test.models.Show@f0ff686,
com.test.models.Show@88cfb47]
```
Any ideas why I'm getting these? I'd appreciate any help. Thanks! | 2015/11/02 | [
"https://Stackoverflow.com/questions/33473236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Provide more codes might help to imporove accuracy of an answer; however, let's be assuming you have already been able to discover all characteristic values. Usually you just need to iterate all characteristics and set/write value according to each Client Characteristic Configuration(CCC) descriptor in `CBPeripheralDelegate` implementation.
An example is attached below:
```
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (error) {
NSLog(@"Error discovering characteristics: %@", error);
return;
}
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID isEqual:[CBManager accelDataUUID]]) {
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
} else if ([characteristic.UUID isEqual:[CBManager accelConfigUUID]]) {
[peripheral writeValue:[CBManager switchData:YES]
forCharacteristic:characteristic
type:CBCharacteristicWriteWithResponse];
}
//... if you have more to iterate
}
}
``` | You need to check for the availability of the characteristic's notification.
[From Apple's doc](https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/PerformingCommonCentralRoleTasks/PerformingCommonCentralRoleTasks.html#//apple_ref/doc/uid/TP40013257-CH3-SW7)
>
> When you subscribe to (or unsubscribe from) a characteristicβs value,
> the peripheral calls the
> `peripheral:didUpdateNotificationStateForCharacteristic:error:` method
> of its delegate object. If the subscription request fails for any
> reason, you can implement this delegate method to access the cause of
> the error, as the following example shows:
>
>
>
```
-(void)peripheral:(CBPeripheral *)peripheral
didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic
error:(NSError *)error {
if (error) {
NSLog(@"Error changing notification state: %@",
[error localizedDescription]);
}
...
```
>
> Note: Not all characteristics offer subscription. You can determine
> if a characteristic offers subscription by checking if its properties
> attribute includes either of the `CBCharacteristicPropertyNotify` or
> `CBCharacteristicPropertyIndicate` constants.
>
>
> |
57,357,189 | I have a program which gets a very big txt data and changes the order of some columns in this txt data. For more details about what it does exactly see my question [here](https://stackoverflow.com/questions/57274751/change-order-of-columns-in-a-txt-file). I use a list with maps and I can imagine that this is too much for the java virtual machine since the txt file has 400,000 entries but I have no idea what do else. I have tried it with a smaller txt file and then it works fine. Otherwise it runs for more than an hour and then I get an OutOfMemoryError.
Here is my code:
```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Final {
public static void main(String[] args) {
String path = "C:\\\\\\\\Users\\\\\\\\Ferid\\\\\\\\Downloads\\\\\\\\secdef\\\\\\\\secdef.txt";
File file = new File(path);
new Final().updateFile(file);
}
private void updateFile(File file) {
List<String> allRows = getAllRows(file);
String[] baseRow = allRows.get(0).split("\\|");
List<String> columns = getBaseColumns(baseRow);
System.out.println(columns.size());
appendNewColumns(allRows, columns);
System.out.println(columns.size());
List<Map<String, String>> mapList = convertToMap(allRows, columns);
List<String> newList = new ArrayList<String>();
appendHeader(columns, newList);
appendData(mapList, newList, columns);
String toPath = "C:\\\\\\\\Users\\\\\\\\Ferid\\\\\\\\Downloads\\\\\\\\secdef\\\\\\\\finalz2.txt";
writeToNewFile(newList, toPath);
}
/**
* Gibt alle Zeilen aus der Datei zurΓΌck.
*/
private static List<String> getAllRows(File file) {
List<String> allRows = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String row = null;
int i = 0;
while ((row = reader.readLine()) != null) {
allRows.add(row);
}
} catch (IOException e) {
e.printStackTrace();
}
return allRows;
}
/**
* Gibt die Hauptspalten aus der 1. Zeile zurΓΌck.
*/
private static List<String> getBaseColumns(String[] baseRow) {
List<String> columns = new ArrayList<>();
for (String rowEntry : baseRow) {
String[] entry = rowEntry.split("=");
columns.add(entry[0]);
}
return columns;
}
/**
* FΓΌgt alle neuen Spalten hinzu.
*/
private static void appendNewColumns(List<String> rows, List<String> columns) {
for (String row : rows) {
String[] splittedRow = row.split("\\|");
for (String column : splittedRow) {
String[] entry = column.split("=");
if (columns.contains(entry[0])) {
continue;
}
columns.add(entry[0]);
}
}
}
/**
* Konvertiert die ListeneintrΓ€ge zu Maps.
*/
private static List<Map<String, String>> convertToMap(List<String> rows, List<String> columns) {
List<Map<String, String>> mapList = new ArrayList<>();
for (String row : rows) {
Map<String, String> map = new TreeMap<>();
String[] splittedRow = row.split("\\|");
List<String> rowList = Arrays.asList(splittedRow);
for (String col : columns) {
String newCol = findByColumn(rowList, col);
if (newCol == null) {
map.put(col, "null");
} else {
String[] arr = newCol.split("=");
map.put(col, arr[1]);
}
}
mapList.add(map);
}
return mapList;
}
/**
*
*/
private static String findByColumn(List<String> row, String col) {
return row.stream().filter(o -> o.startsWith(col)).findFirst().orElse(null);
}
/**
* FΓΌgt die Header-Zeile in die neue Liste hinzu.
*/
private static void appendHeader(List<String> columns, List<String> list1) {
String header = "";
for (String column : columns) {
header += column + "|";
}
list1.add(header + "\n");
}
/**
* FΓΌgt alle Daten in die entsprechenden neuen Dateien hinzu.
*/
private static void appendData(List<Map<String, String>> mapList, List<String> list1, List<String> columns) {
for (Map<String, String> entry : mapList) {
String line = "";
for (String key : columns) {
// for (String key : entry.keySet()) {
line += entry.get(key) + "|";
}
list1.add(line + "\n");
}
}
/**
* Schreibt alle Werte in die neue Datei.
*/
private static void writeToNewFile(List<String> list, String path) {
FileOutputStream out = null;
try {
out = new FileOutputStream(new File(path));
for (String line : list) {
out.write(line.getBytes());
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
``` | 2019/08/05 | [
"https://Stackoverflow.com/questions/57357189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8271518/"
] | In cases like this, it makes sense, if at all possible, to read the file line by line and handle each line seperately, and NOT keep the whole file in memory.
Currently your code looks like this:
1. read all lines into list L
2. for each row in L find all columns
3. convert rows in L to maps (using "null" string inside the map instead of not setting a value!! This is probably what really bites you in the end!)
4. serialize the maps as rows
I call bs on just increasing the available memory, then it will just fail later. You have a general problem with memory usage and performance here. Let me propose a different way:
```
1. for each line read (don't read the whole file at once!):
1.1 find columns, collect in List C
2. for each line read (again, don't read the whole file at once, do it as you read):
2.2 for each column in C, write value if the row contains it, or null
2.3 append to the result file (also don't keep the result in memory!)
```
So somewhat like this:
```
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(file));
String row = null;
int i = 0;
List<String> columns = new ArrayList<>();
while ((row = reader.readLine()) != null) {
columns.addAll(getColumns(row));
}
reader = new BufferedReader(new FileReader(file));
writer = new BufferedWriter(new FileWriter(outFile));
int i = 0;
while ((row = reader.readLine()) != null) {
writeRow(row, columns, writer);
}
} catch (IOException e) {
e.printStackTrace();
}
``` | You can specify the maximum memory JVM can use by specyfying: -Xmx
eg. `-Xmx8G`,
Use M or G |
57,357,189 | I have a program which gets a very big txt data and changes the order of some columns in this txt data. For more details about what it does exactly see my question [here](https://stackoverflow.com/questions/57274751/change-order-of-columns-in-a-txt-file). I use a list with maps and I can imagine that this is too much for the java virtual machine since the txt file has 400,000 entries but I have no idea what do else. I have tried it with a smaller txt file and then it works fine. Otherwise it runs for more than an hour and then I get an OutOfMemoryError.
Here is my code:
```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Final {
public static void main(String[] args) {
String path = "C:\\\\\\\\Users\\\\\\\\Ferid\\\\\\\\Downloads\\\\\\\\secdef\\\\\\\\secdef.txt";
File file = new File(path);
new Final().updateFile(file);
}
private void updateFile(File file) {
List<String> allRows = getAllRows(file);
String[] baseRow = allRows.get(0).split("\\|");
List<String> columns = getBaseColumns(baseRow);
System.out.println(columns.size());
appendNewColumns(allRows, columns);
System.out.println(columns.size());
List<Map<String, String>> mapList = convertToMap(allRows, columns);
List<String> newList = new ArrayList<String>();
appendHeader(columns, newList);
appendData(mapList, newList, columns);
String toPath = "C:\\\\\\\\Users\\\\\\\\Ferid\\\\\\\\Downloads\\\\\\\\secdef\\\\\\\\finalz2.txt";
writeToNewFile(newList, toPath);
}
/**
* Gibt alle Zeilen aus der Datei zurΓΌck.
*/
private static List<String> getAllRows(File file) {
List<String> allRows = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String row = null;
int i = 0;
while ((row = reader.readLine()) != null) {
allRows.add(row);
}
} catch (IOException e) {
e.printStackTrace();
}
return allRows;
}
/**
* Gibt die Hauptspalten aus der 1. Zeile zurΓΌck.
*/
private static List<String> getBaseColumns(String[] baseRow) {
List<String> columns = new ArrayList<>();
for (String rowEntry : baseRow) {
String[] entry = rowEntry.split("=");
columns.add(entry[0]);
}
return columns;
}
/**
* FΓΌgt alle neuen Spalten hinzu.
*/
private static void appendNewColumns(List<String> rows, List<String> columns) {
for (String row : rows) {
String[] splittedRow = row.split("\\|");
for (String column : splittedRow) {
String[] entry = column.split("=");
if (columns.contains(entry[0])) {
continue;
}
columns.add(entry[0]);
}
}
}
/**
* Konvertiert die ListeneintrΓ€ge zu Maps.
*/
private static List<Map<String, String>> convertToMap(List<String> rows, List<String> columns) {
List<Map<String, String>> mapList = new ArrayList<>();
for (String row : rows) {
Map<String, String> map = new TreeMap<>();
String[] splittedRow = row.split("\\|");
List<String> rowList = Arrays.asList(splittedRow);
for (String col : columns) {
String newCol = findByColumn(rowList, col);
if (newCol == null) {
map.put(col, "null");
} else {
String[] arr = newCol.split("=");
map.put(col, arr[1]);
}
}
mapList.add(map);
}
return mapList;
}
/**
*
*/
private static String findByColumn(List<String> row, String col) {
return row.stream().filter(o -> o.startsWith(col)).findFirst().orElse(null);
}
/**
* FΓΌgt die Header-Zeile in die neue Liste hinzu.
*/
private static void appendHeader(List<String> columns, List<String> list1) {
String header = "";
for (String column : columns) {
header += column + "|";
}
list1.add(header + "\n");
}
/**
* FΓΌgt alle Daten in die entsprechenden neuen Dateien hinzu.
*/
private static void appendData(List<Map<String, String>> mapList, List<String> list1, List<String> columns) {
for (Map<String, String> entry : mapList) {
String line = "";
for (String key : columns) {
// for (String key : entry.keySet()) {
line += entry.get(key) + "|";
}
list1.add(line + "\n");
}
}
/**
* Schreibt alle Werte in die neue Datei.
*/
private static void writeToNewFile(List<String> list, String path) {
FileOutputStream out = null;
try {
out = new FileOutputStream(new File(path));
for (String line : list) {
out.write(line.getBytes());
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
``` | 2019/08/05 | [
"https://Stackoverflow.com/questions/57357189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8271518/"
] | In cases like this, it makes sense, if at all possible, to read the file line by line and handle each line seperately, and NOT keep the whole file in memory.
Currently your code looks like this:
1. read all lines into list L
2. for each row in L find all columns
3. convert rows in L to maps (using "null" string inside the map instead of not setting a value!! This is probably what really bites you in the end!)
4. serialize the maps as rows
I call bs on just increasing the available memory, then it will just fail later. You have a general problem with memory usage and performance here. Let me propose a different way:
```
1. for each line read (don't read the whole file at once!):
1.1 find columns, collect in List C
2. for each line read (again, don't read the whole file at once, do it as you read):
2.2 for each column in C, write value if the row contains it, or null
2.3 append to the result file (also don't keep the result in memory!)
```
So somewhat like this:
```
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(file));
String row = null;
int i = 0;
List<String> columns = new ArrayList<>();
while ((row = reader.readLine()) != null) {
columns.addAll(getColumns(row));
}
reader = new BufferedReader(new FileReader(file));
writer = new BufferedWriter(new FileWriter(outFile));
int i = 0;
while ((row = reader.readLine()) != null) {
writeRow(row, columns, writer);
}
} catch (IOException e) {
e.printStackTrace();
}
``` | We aren't really able to give a concrete recommendation for the amount of memory to allocate, because that will depend greatly on your server setup, the size of your user base, and their behaviour. You will need to find a value that works for you, i.e. no noticeable GC pauses, and no OutOfMemory errors.
For reference, the 3 most common parameters used to change the memory (heap) allocation are:
>
> * **Xms** - the minimum size of the heap
> * **Xmx** - the maximum size of the heap
> * **XX:MaxPermSize** - the maximum size of PermGen (this is not used in Java 8 and above)
>
>
>
If you do decide to increase the memory settings, there are a few general guidelines to follow.
* Increase Xmx in small increments (eg 512mb at a time), until you no
longer experience the OutOfMemory error. This is because increasing
the heap beyond the capabilities of your server to adequately Garbage
Collect can cause other problems (eg performance/freezing)
* If your error is ***java . lang . OutOfMemoryError : PermGen space***,
increase the -XX:MaxPermSize parameter in 256mb increments until the
error stops occurring.
* If your error does not reference PermGen, there is no need to
increase it. In a simplistic explanation, PermGen is used to store
classes, and is generally quite static in size, and has been removed
in Java 8. More info here. Consider setting Xms and Xmx to the same
value, as this can decrease the time GC takes to occur, as it will
not attempt to resize the heap down on each collection.
If you start Confluence as a Service on Windows, then you should not use these instructions. Instead, refer to the "Windows Service" section below.
You should only follow these instructions if you are starting Confluence via the batch file. The batch file is not used when Confluence is started as a Service.
To Configure System Properties in Windows Installations When Starting from the `.bat` File,
1. Shutdown Confluence
2. From /bin (Stand-alone) or /bin (EAR-WAR installation), open `setenv.bat`.
3. Find the section
>
> **CATALINA\_OPTS="-Xms1024m -Xmx1024m -XX:+UseG1GC $CATALINA\_OPTS"** in Confluence 5.8 or above
>
>
> **CATALINA\_OPTS="$CATALINA\_OPTS -Xms1024m -Xmx1024m -XX:MaxPermSize=256m -XX:+UseG1GC"** in Confluence 5.6 or 5.7
>
>
> **JAVA\_OPTS="-Xms256m -Xmx512m -XX:MaxPermSize=256m** in previous versions
>
>
>
4. Xmx is maximum, Xms is minimum, and MaxPermSize is PermGen.
5. Start Confluence |
88,846 | I'm approaching the end of the first year of my PhD and I really am struggling to find what my research question is. I'm slightly panicing that I don't know what I'm doing yet and I get very little support from my supervisor.
I've spent time exploring the literature and I have a few broad ideas of potential areas. The problem is, when I discuss the topics with my supervisor, he gives me no advice or guidance about how to develop these ideas into research questions or whether these ideas are even valuable/ could make a PhD.
We meet fairly regularly (maybe once a month). But in most of our meetings it's just me bringing him up to speed on the research I've done and some ideas, and I really don't get any feedback that is constructive to me narrowing down a topic and really developing it.
I've tried to be more direct, and specifically asked 'what topic do you think has the most value?' to which he'll reply 'what topic do YOU think has the most value?'. He doesn't do a lot of independent research either as he spends a lot of time teaching, so it's difficult for me to just attach myself to something he has worked on.
I'm really not sure how I can get some feedback on my work and find a topic. Any advice?
**Edit:**
Thanks so much to everyone who has responded to this question. Your advice has been really helpful and constructive. | 2017/05/02 | [
"https://academia.stackexchange.com/questions/88846",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/72922/"
] | Several things come to mind:
First, know that this is frustrating for many PhD students and it is normal for people to feel anxious if they aren't on a set course for their dissertation at the end of year 1.
Second, is it possible that your advisor is not a great match for you? My dissertation chair was not an expert at all in my dissertation topic (no one in my program was), but he was an accomplished scholar who could help me develop skills in identifying appropriate literature and narrowing down a topic. You may want to consider if someone else in your program is a better fit and switch advisors. This happens sometimes. It's normal.
Third, this is why PhD programs have students assemble dissertation committees, rather than just work with one person. If switching advisors is not an option, find someone else in the area you want to research and meet with him or her. Invite him or her to coffee or lunch. If they are at a distance, ask them to talk on the phone. Many researchers would be flattered that you are interested in their area and want to pick their brain. This may help.
Finally, does the literature indicate that there are specific topics in this larger area that need to be explored? Maybe you are not consulting with the right literature or there is a lot more out there to consult with.
Hope this helps! Good luck! | As HEITZ has written, there are many styles and his seems to be firmly in the 'you must reach the answer within yourself' category.
Yes, it's very true that students can be influenced into doing something they weren't 100% in love with and therefore end up being disillusioned, but they are there to guide you and the ideology of 'no interference' quickly can end up being 'no helping'.
I had what I thought was a 'pursue your own path with my guidance' supervisor who just ended up being aloof, useless and completely uninterested in my research. Worst of all, when I tackled them about it, they berated me for wanting to have my hand held etc. I'd therefore suggest you tackle the problem head on in case yours is similar.
**What to do:**
As others have recommended - state what you need in concrete terms and set up a weekly meeting till you get over this hump. Lay out the options and go through each of them in detail - have a list of actual questions about each topic, and don't settle for vagueness.
If you're looking for topic worth, you need to state it more directly; which of these topics was recently a big issue at x, why does topic y matter now? Point blank say 'I'd like your opinion really' if asked the question back.
If they aren't able to deliver that then you need to look else where, even if you feel it might be disruptive. |
88,846 | I'm approaching the end of the first year of my PhD and I really am struggling to find what my research question is. I'm slightly panicing that I don't know what I'm doing yet and I get very little support from my supervisor.
I've spent time exploring the literature and I have a few broad ideas of potential areas. The problem is, when I discuss the topics with my supervisor, he gives me no advice or guidance about how to develop these ideas into research questions or whether these ideas are even valuable/ could make a PhD.
We meet fairly regularly (maybe once a month). But in most of our meetings it's just me bringing him up to speed on the research I've done and some ideas, and I really don't get any feedback that is constructive to me narrowing down a topic and really developing it.
I've tried to be more direct, and specifically asked 'what topic do you think has the most value?' to which he'll reply 'what topic do YOU think has the most value?'. He doesn't do a lot of independent research either as he spends a lot of time teaching, so it's difficult for me to just attach myself to something he has worked on.
I'm really not sure how I can get some feedback on my work and find a topic. Any advice?
**Edit:**
Thanks so much to everyone who has responded to this question. Your advice has been really helpful and constructive. | 2017/05/02 | [
"https://academia.stackexchange.com/questions/88846",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/72922/"
] | There are several advising 'styles' if you can call them that. The spectrum probably runs from 'do this project now' to 'let's meet repeatedly for 6 months until something materializes'
Professors are not usually trained in project management, so you might need to step up here and take control of your destiny. He or she is probably not going to give you the direction you want. Rest assured, if you pick the project that interests you the most and you work hard, you'll turn it into something tangible.
So, change your tone from 'should I do x or y?' to 'I'm doing x starting Monday unless you disagree'. Perhaps your advisor will be very helpful once you have more targeted questions, which you'll get once you start the project.
However, I am worried about your 'regular monthly meetings'. You should be meeting weekly or more. If your advisor just isn't engaged in what you're doing, move on. | As HEITZ has written, there are many styles and his seems to be firmly in the 'you must reach the answer within yourself' category.
Yes, it's very true that students can be influenced into doing something they weren't 100% in love with and therefore end up being disillusioned, but they are there to guide you and the ideology of 'no interference' quickly can end up being 'no helping'.
I had what I thought was a 'pursue your own path with my guidance' supervisor who just ended up being aloof, useless and completely uninterested in my research. Worst of all, when I tackled them about it, they berated me for wanting to have my hand held etc. I'd therefore suggest you tackle the problem head on in case yours is similar.
**What to do:**
As others have recommended - state what you need in concrete terms and set up a weekly meeting till you get over this hump. Lay out the options and go through each of them in detail - have a list of actual questions about each topic, and don't settle for vagueness.
If you're looking for topic worth, you need to state it more directly; which of these topics was recently a big issue at x, why does topic y matter now? Point blank say 'I'd like your opinion really' if asked the question back.
If they aren't able to deliver that then you need to look else where, even if you feel it might be disruptive. |
41,181,742 | I want to do an OCR benchmark for scanned text (typically any scan, i.e. A4). I was able to find some NEOCR datasets [here](http://datasets.visionbib.com/), but NEOCR is not really what I want.
I would appreciate links to sources of free databases that have appropriate images and the actual texts (contained in the images) referenced.
I hope this thread will also be useful for other people doing OCR surfing for datasets, since I didn't find any good reference to such sources.
Thanks! | 2016/12/16 | [
"https://Stackoverflow.com/questions/41181742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1804389/"
] | I've had good luck using university research data sets in a number of projects. These are often useful because the input and expected results need to be published to independently reproduce the study results. One example is the UNLV data set for the [Fourth Annual Test of OCR Accuracy](https://github.com/tesseract-ocr/tesseract/wiki/UNLV-Testing-of-Tesseract) discussed more below.
Another approach is to start with a data set and create your own training set. It may also be worthwhile to work with [Project Gutenberg](http://www.gutenberg.org/) which has transcribed 57,136 books. You could take the HTML version (with images) and print it out using a variety of transformations like fonts, rotation, etc. Then you could convert the images and scan them to compare against the text version. See an example further below.
**1) Annual Tests of OCR Accuracy DOE and UNLV**
The Department of Energy (DOE) and Information Science Research Institute (ISRI) of UNLV ran OCR tests for 5 years from 1992 to 1995. You can find the study descriptions for each year here:
* Overview: <http://www.expervision.com/testimonial-world-leading-and-champion-ocr/annual-test-of-ocr-accuracy-by-us-department-of-energy-doe-university-of-nevada-las-vegas-unlv>
**1.1) UNLV Tesseract OCR Test Data published in Fourth Annual Test of OCR Accuracy**
The data for the fourth annual test using [Tesseract](https://en.wikipedia.org/wiki/Tesseract_(software)) is posted online. Since this was an OCR study, it may suit your purposes.
This data is now hosted as part of the ISRI of UNLV OCR Evaluation Tools project posted on Google Code:
* Project: <https://code.google.com/archive/p/isri-ocr-evaluation-tools/>
>
> Images and Ground Truth text and zone files for several thousand English and some Spanish pages that were used in the UNLV/ISRI annual tests of OCR accuracy between 1992 and 1996.
>
>
> Source code of OCR evaluation tools used in the UNLV/ISRI annual tests of OCR Accuracy.
>
>
> Publications of the Information Science Research Institute of UNLV applicable to OCR and text retrieval.
>
>
>
You can find information on this data set here:
* Description: <https://github.com/tesseract-ocr/tesseract/wiki/UNLV-Testing-of-Tesseract>
* Datasets: <https://code.google.com/archive/p/isri-ocr-evaluation-tools/downloads>
At the datasets link, you'll find a number of gziped tarballs you can download. In each tarball is a number of directories with a set of files. Each document has 3 files:
* `.tif` binary image file
* `.txt` text file
* `.uzn` zone file for describing the scanned image
Note: while posting, I noticed this data set was originally posted in a comment by @Stef above.
**2) Project Gutenberg**
[Project Gutenberg](http://www.gutenberg.org/) has transcribed 57,136 free ebooks in the following formats:
* HTML
* EPUB (with images)
* EPUB (no images)
* Kindle (with images)
* Kindle (no images)
* Plain Text UTF-8
Here is an example: <http://www.gutenberg.org/ebooks/766>
You could create a test data set by doing the following:
Create test files:
1. Start with HTML, ePub, Kindle, or plain text versions
2. Render and transform using different fonts, rotation, background color, with and without images, etc.
3. Convert the rendering to the desired format, e.g. TIFF, PDF, etc.
Test:
1. Run generated images through OCR system
2. Compare with original plain text version | Coco dataset :
<https://vision.cornell.edu/se3/coco-text-2/>
Char74Kdatase :
<http://www.ee.surrey.ac.uk/CVSSP/demos/chars74k/>
COCO dataset is a benchmark dataset for images. World's toughest competitions are arranged using COCO dataset. It can be used for object detecion, image captioning, OCR. |
42,984,884 | It is awfully often required to write repeatable pieces of code.
Consider the following example from `Java` (although, it may not be the best example, but I hope you get the general idea...)
`String X = rs.getString("X");`
Where `X` will have values: `'name'`,`'surname'` ... and `20`-`30` other values.
(Another example would be an `HTML` code and any other code - you need to create for `X`)
The end result should be:
```
String name=rs.getString("name");
String surname=rs.getString("surname");
....
String whatever = rs.getString("whatever");
```
Here is another example with `html` table and some `scriplets`, in this case string to replicate would be `<th>X</th>` and `<td><%=myBean.getX()%></td>` the end result would be:
```
<table style="width:100%">
<tr>
<th>name</th>
<th>surname</th>
<th>..</th>
<th>whatever</th>
</tr>
<tr>
<td><%=myBean.getName()%></td>
<td><%=myBean.getSurname()%></td>
<td>..</td>
<td><%=myBean.getWhatever()%></td>
</tr>
</table>
```
So, apart form copy-pasting the above for `30` times and then editing, the the only 'clever' way I found to deal with this is to use `python`, `jinja2` library and write a small code generator.
But, in order to do that I had to install `python`, install the library, create a `template`, create a custom `script` to read values from a `text file` and then generate code for the values read.
I was wondering is there any easier way to achieve the above?
Any editor or plugin to support code generation?
I know that IDEs such as Netbeans, Eclipse can generate some code - like getters and setters ... etc, but it is not enough...
In a nutshell,
I want to regenerate some lines of code by altering only specific parts ... The question is how to achieve that easily? (I know the hard way to do this) ..I am seeking for ideas... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42984884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532778/"
] | In such scenarios, the best thing you could do is to use a constant array together with a HashMap. The constant array will hold keynames for the hashmap whereas the hashmap will also hold the value for each one.
For instance:
```
String[] keys = {"name", "surname", "whatever" };
HashMap<String, String> elements = new HashMap<String, String>();
for (String key : keys)
{
elements.put(key, rs.getString(key));
}
```
You just have to be careful that all the elements are from the same type. If they are not, you will have to either store them as Objects and then cast them.
EDIT: for using in a Scriptlet, a good idea would be:
```
<tr>
<% for (String key : keys)
{
%>
<td><%= elements.get(key)%></td>
<% } %>
</tr>
``` | In IntelliJ we have "Live Template" feature that you use to generate part of the code.
For example, when you type "sout" , IntelliJ suggests "System.out.println".
When you type "main" , Eclipse suggests "public static void main(String[] args)"
You can create something like that for pieces of code that are very commom. |
42,984,884 | It is awfully often required to write repeatable pieces of code.
Consider the following example from `Java` (although, it may not be the best example, but I hope you get the general idea...)
`String X = rs.getString("X");`
Where `X` will have values: `'name'`,`'surname'` ... and `20`-`30` other values.
(Another example would be an `HTML` code and any other code - you need to create for `X`)
The end result should be:
```
String name=rs.getString("name");
String surname=rs.getString("surname");
....
String whatever = rs.getString("whatever");
```
Here is another example with `html` table and some `scriplets`, in this case string to replicate would be `<th>X</th>` and `<td><%=myBean.getX()%></td>` the end result would be:
```
<table style="width:100%">
<tr>
<th>name</th>
<th>surname</th>
<th>..</th>
<th>whatever</th>
</tr>
<tr>
<td><%=myBean.getName()%></td>
<td><%=myBean.getSurname()%></td>
<td>..</td>
<td><%=myBean.getWhatever()%></td>
</tr>
</table>
```
So, apart form copy-pasting the above for `30` times and then editing, the the only 'clever' way I found to deal with this is to use `python`, `jinja2` library and write a small code generator.
But, in order to do that I had to install `python`, install the library, create a `template`, create a custom `script` to read values from a `text file` and then generate code for the values read.
I was wondering is there any easier way to achieve the above?
Any editor or plugin to support code generation?
I know that IDEs such as Netbeans, Eclipse can generate some code - like getters and setters ... etc, but it is not enough...
In a nutshell,
I want to regenerate some lines of code by altering only specific parts ... The question is how to achieve that easily? (I know the hard way to do this) ..I am seeking for ideas... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42984884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532778/"
] | Probably I am looking for something that does not exist.
So, I'll just post my '*hard way*' of achieving, what I have described in my question (in hope that this would be useful for somebody - sometime).
Here I will preset a small code generator I am using to generate java, html, jsp, xsd and other codes.
I am using [Python27](https://www.python.org/download/releases/2.7/) and [Jinja2-2.7.2](https://pypi.python.org/pypi/Jinja2/2.7.2)
My Files:
**InputData.txt**
```
:This is field list
field1:field1 description
field2:field2 description
field3:field3 description
field4:field4 description
name:first name of the person
surname:last name of the person
whatever:whatever you need
```
**CodeGenerator.py**
```
import jinja2
import codecs
templateLoader = jinja2.FileSystemLoader( searchpath="." )
templateEnv = jinja2.Environment( loader=templateLoader )
TEMPLATE_FILE = "CodeGenerator.jinja"
template = templateEnv.get_template( TEMPLATE_FILE )
COLUMNS = [tuple(line.split(':')) for line in codecs.open( "InputData.txt", "r", "utf-8" )]
COLUMNS = map(lambda s: (s[0],(s[0].strip().title(),s[1].strip())), COLUMNS)
#title() copy of the string in which first characters of all the words are capitalized.
#strip() copy of the string, all chars have been stripped from the beginning and the end
#lambda s --> (field1,(Field1,field1 description))
#ignore the first line
COLUMNS.pop(0)
#add variables to work with
templateVars = { "table" : "MyTableName",
"description" : "A simple code generator",
"columns" : COLUMNS
}
outputText = template.render( templateVars )
f = open('Generated.txt', 'w')
outputText = outputText.encode('utf-8')
f.write(outputText)
f.close()
print outputText
```
**CodeGenerator.jinja**
```
//------------------model------------------------
//Generated code for model
import java.io.Serializable;
public class {{table|capitalize}}_Model implements Serializable{
{%for columnName,columnTitle in columns%}
private String {{columnName|lower}};{%endfor%}
{% for columnName,columnTitle in columns %}
public void set{{columnName|capitalize}}(String {{columnName|lower}}){
this.{{columnName|lower}}={{columnName|lower}};
}
public String get{{columnName|capitalize}}(){
return this.{{columnName|lower}};
}
{% endfor %}
public {{table|capitalize}}_Model({% for columnName,columnTitle in columns %}String {{columnName|lower}}{% if not loop.last %},{% endif %}{% endfor %}){
{% for columnName,columnTitle in columns %}
this.{{columnName|lower}}={{columnName|lower}}; {% endfor %}
}
public String toString(){
return {% for columnName,columnTitle in columns %}"{{columnName|lower}}:" + this.{{columnName|lower}}{% if not loop.last %}+{% endif %}{% endfor %};
}
}
//------------------model------------------------
//-----------------getStrings--------------------
{% for columnName,columnTitle in columns %}
String {{columnName}}=rs.getString("{{columnName}}");
{% endfor %}
//----------------------------------------------
//------------------jsp example-----------------
{% for columnName,columnTitle in columns %}
<s:label cssStyle ="margin-top:5px;color:blue;" value="{{columnTitle[1]}} :" id="{{columnName}}_label"/>
<s:textfield label="{{columnTitle[1]}}" name="myBean.{{columnName}}" />
{% endfor %}
//------------------jsp example-----------------
``` | In IntelliJ we have "Live Template" feature that you use to generate part of the code.
For example, when you type "sout" , IntelliJ suggests "System.out.println".
When you type "main" , Eclipse suggests "public static void main(String[] args)"
You can create something like that for pieces of code that are very commom. |
42,984,884 | It is awfully often required to write repeatable pieces of code.
Consider the following example from `Java` (although, it may not be the best example, but I hope you get the general idea...)
`String X = rs.getString("X");`
Where `X` will have values: `'name'`,`'surname'` ... and `20`-`30` other values.
(Another example would be an `HTML` code and any other code - you need to create for `X`)
The end result should be:
```
String name=rs.getString("name");
String surname=rs.getString("surname");
....
String whatever = rs.getString("whatever");
```
Here is another example with `html` table and some `scriplets`, in this case string to replicate would be `<th>X</th>` and `<td><%=myBean.getX()%></td>` the end result would be:
```
<table style="width:100%">
<tr>
<th>name</th>
<th>surname</th>
<th>..</th>
<th>whatever</th>
</tr>
<tr>
<td><%=myBean.getName()%></td>
<td><%=myBean.getSurname()%></td>
<td>..</td>
<td><%=myBean.getWhatever()%></td>
</tr>
</table>
```
So, apart form copy-pasting the above for `30` times and then editing, the the only 'clever' way I found to deal with this is to use `python`, `jinja2` library and write a small code generator.
But, in order to do that I had to install `python`, install the library, create a `template`, create a custom `script` to read values from a `text file` and then generate code for the values read.
I was wondering is there any easier way to achieve the above?
Any editor or plugin to support code generation?
I know that IDEs such as Netbeans, Eclipse can generate some code - like getters and setters ... etc, but it is not enough...
In a nutshell,
I want to regenerate some lines of code by altering only specific parts ... The question is how to achieve that easily? (I know the hard way to do this) ..I am seeking for ideas... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42984884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532778/"
] | You can do that with a lightweight code generator like Telosys :
* <http://www.telosys.org/>
* <https://modeling-languages.com/telosys-tools-the-concept-of-lightweight-model-for-code-generation/>
In your case Telosys-CLI with a DSL model is probably the right choice, you'll just have to create your specific templates in Velocity language ( <http://velocity.apache.org/> ) | In IntelliJ we have "Live Template" feature that you use to generate part of the code.
For example, when you type "sout" , IntelliJ suggests "System.out.println".
When you type "main" , Eclipse suggests "public static void main(String[] args)"
You can create something like that for pieces of code that are very commom. |
42,984,884 | It is awfully often required to write repeatable pieces of code.
Consider the following example from `Java` (although, it may not be the best example, but I hope you get the general idea...)
`String X = rs.getString("X");`
Where `X` will have values: `'name'`,`'surname'` ... and `20`-`30` other values.
(Another example would be an `HTML` code and any other code - you need to create for `X`)
The end result should be:
```
String name=rs.getString("name");
String surname=rs.getString("surname");
....
String whatever = rs.getString("whatever");
```
Here is another example with `html` table and some `scriplets`, in this case string to replicate would be `<th>X</th>` and `<td><%=myBean.getX()%></td>` the end result would be:
```
<table style="width:100%">
<tr>
<th>name</th>
<th>surname</th>
<th>..</th>
<th>whatever</th>
</tr>
<tr>
<td><%=myBean.getName()%></td>
<td><%=myBean.getSurname()%></td>
<td>..</td>
<td><%=myBean.getWhatever()%></td>
</tr>
</table>
```
So, apart form copy-pasting the above for `30` times and then editing, the the only 'clever' way I found to deal with this is to use `python`, `jinja2` library and write a small code generator.
But, in order to do that I had to install `python`, install the library, create a `template`, create a custom `script` to read values from a `text file` and then generate code for the values read.
I was wondering is there any easier way to achieve the above?
Any editor or plugin to support code generation?
I know that IDEs such as Netbeans, Eclipse can generate some code - like getters and setters ... etc, but it is not enough...
In a nutshell,
I want to regenerate some lines of code by altering only specific parts ... The question is how to achieve that easily? (I know the hard way to do this) ..I am seeking for ideas... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42984884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532778/"
] | In such scenarios, the best thing you could do is to use a constant array together with a HashMap. The constant array will hold keynames for the hashmap whereas the hashmap will also hold the value for each one.
For instance:
```
String[] keys = {"name", "surname", "whatever" };
HashMap<String, String> elements = new HashMap<String, String>();
for (String key : keys)
{
elements.put(key, rs.getString(key));
}
```
You just have to be careful that all the elements are from the same type. If they are not, you will have to either store them as Objects and then cast them.
EDIT: for using in a Scriptlet, a good idea would be:
```
<tr>
<% for (String key : keys)
{
%>
<td><%= elements.get(key)%></td>
<% } %>
</tr>
``` | If I understand your problem correctly, you have a `ResultSet` with a lot of columns. And you do not want to get them one by one.
It is possible to get all the columns from a `ResultSet` the following way:
```
ResultSetMetaData metaData = resultSet.getMetaData();
for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) {
String columnName = metaData.getColumnName(columnIndex);
String value = resultSet.getString(columnIndex);
}
```
Granted all the values will b e represented as strings in this example, but you can determine the type of the column also by using the same `metaData` object. Read more about it in the documentation: <https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html> |
42,984,884 | It is awfully often required to write repeatable pieces of code.
Consider the following example from `Java` (although, it may not be the best example, but I hope you get the general idea...)
`String X = rs.getString("X");`
Where `X` will have values: `'name'`,`'surname'` ... and `20`-`30` other values.
(Another example would be an `HTML` code and any other code - you need to create for `X`)
The end result should be:
```
String name=rs.getString("name");
String surname=rs.getString("surname");
....
String whatever = rs.getString("whatever");
```
Here is another example with `html` table and some `scriplets`, in this case string to replicate would be `<th>X</th>` and `<td><%=myBean.getX()%></td>` the end result would be:
```
<table style="width:100%">
<tr>
<th>name</th>
<th>surname</th>
<th>..</th>
<th>whatever</th>
</tr>
<tr>
<td><%=myBean.getName()%></td>
<td><%=myBean.getSurname()%></td>
<td>..</td>
<td><%=myBean.getWhatever()%></td>
</tr>
</table>
```
So, apart form copy-pasting the above for `30` times and then editing, the the only 'clever' way I found to deal with this is to use `python`, `jinja2` library and write a small code generator.
But, in order to do that I had to install `python`, install the library, create a `template`, create a custom `script` to read values from a `text file` and then generate code for the values read.
I was wondering is there any easier way to achieve the above?
Any editor or plugin to support code generation?
I know that IDEs such as Netbeans, Eclipse can generate some code - like getters and setters ... etc, but it is not enough...
In a nutshell,
I want to regenerate some lines of code by altering only specific parts ... The question is how to achieve that easily? (I know the hard way to do this) ..I am seeking for ideas... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42984884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532778/"
] | Probably I am looking for something that does not exist.
So, I'll just post my '*hard way*' of achieving, what I have described in my question (in hope that this would be useful for somebody - sometime).
Here I will preset a small code generator I am using to generate java, html, jsp, xsd and other codes.
I am using [Python27](https://www.python.org/download/releases/2.7/) and [Jinja2-2.7.2](https://pypi.python.org/pypi/Jinja2/2.7.2)
My Files:
**InputData.txt**
```
:This is field list
field1:field1 description
field2:field2 description
field3:field3 description
field4:field4 description
name:first name of the person
surname:last name of the person
whatever:whatever you need
```
**CodeGenerator.py**
```
import jinja2
import codecs
templateLoader = jinja2.FileSystemLoader( searchpath="." )
templateEnv = jinja2.Environment( loader=templateLoader )
TEMPLATE_FILE = "CodeGenerator.jinja"
template = templateEnv.get_template( TEMPLATE_FILE )
COLUMNS = [tuple(line.split(':')) for line in codecs.open( "InputData.txt", "r", "utf-8" )]
COLUMNS = map(lambda s: (s[0],(s[0].strip().title(),s[1].strip())), COLUMNS)
#title() copy of the string in which first characters of all the words are capitalized.
#strip() copy of the string, all chars have been stripped from the beginning and the end
#lambda s --> (field1,(Field1,field1 description))
#ignore the first line
COLUMNS.pop(0)
#add variables to work with
templateVars = { "table" : "MyTableName",
"description" : "A simple code generator",
"columns" : COLUMNS
}
outputText = template.render( templateVars )
f = open('Generated.txt', 'w')
outputText = outputText.encode('utf-8')
f.write(outputText)
f.close()
print outputText
```
**CodeGenerator.jinja**
```
//------------------model------------------------
//Generated code for model
import java.io.Serializable;
public class {{table|capitalize}}_Model implements Serializable{
{%for columnName,columnTitle in columns%}
private String {{columnName|lower}};{%endfor%}
{% for columnName,columnTitle in columns %}
public void set{{columnName|capitalize}}(String {{columnName|lower}}){
this.{{columnName|lower}}={{columnName|lower}};
}
public String get{{columnName|capitalize}}(){
return this.{{columnName|lower}};
}
{% endfor %}
public {{table|capitalize}}_Model({% for columnName,columnTitle in columns %}String {{columnName|lower}}{% if not loop.last %},{% endif %}{% endfor %}){
{% for columnName,columnTitle in columns %}
this.{{columnName|lower}}={{columnName|lower}}; {% endfor %}
}
public String toString(){
return {% for columnName,columnTitle in columns %}"{{columnName|lower}}:" + this.{{columnName|lower}}{% if not loop.last %}+{% endif %}{% endfor %};
}
}
//------------------model------------------------
//-----------------getStrings--------------------
{% for columnName,columnTitle in columns %}
String {{columnName}}=rs.getString("{{columnName}}");
{% endfor %}
//----------------------------------------------
//------------------jsp example-----------------
{% for columnName,columnTitle in columns %}
<s:label cssStyle ="margin-top:5px;color:blue;" value="{{columnTitle[1]}} :" id="{{columnName}}_label"/>
<s:textfield label="{{columnTitle[1]}}" name="myBean.{{columnName}}" />
{% endfor %}
//------------------jsp example-----------------
``` | In such scenarios, the best thing you could do is to use a constant array together with a HashMap. The constant array will hold keynames for the hashmap whereas the hashmap will also hold the value for each one.
For instance:
```
String[] keys = {"name", "surname", "whatever" };
HashMap<String, String> elements = new HashMap<String, String>();
for (String key : keys)
{
elements.put(key, rs.getString(key));
}
```
You just have to be careful that all the elements are from the same type. If they are not, you will have to either store them as Objects and then cast them.
EDIT: for using in a Scriptlet, a good idea would be:
```
<tr>
<% for (String key : keys)
{
%>
<td><%= elements.get(key)%></td>
<% } %>
</tr>
``` |
42,984,884 | It is awfully often required to write repeatable pieces of code.
Consider the following example from `Java` (although, it may not be the best example, but I hope you get the general idea...)
`String X = rs.getString("X");`
Where `X` will have values: `'name'`,`'surname'` ... and `20`-`30` other values.
(Another example would be an `HTML` code and any other code - you need to create for `X`)
The end result should be:
```
String name=rs.getString("name");
String surname=rs.getString("surname");
....
String whatever = rs.getString("whatever");
```
Here is another example with `html` table and some `scriplets`, in this case string to replicate would be `<th>X</th>` and `<td><%=myBean.getX()%></td>` the end result would be:
```
<table style="width:100%">
<tr>
<th>name</th>
<th>surname</th>
<th>..</th>
<th>whatever</th>
</tr>
<tr>
<td><%=myBean.getName()%></td>
<td><%=myBean.getSurname()%></td>
<td>..</td>
<td><%=myBean.getWhatever()%></td>
</tr>
</table>
```
So, apart form copy-pasting the above for `30` times and then editing, the the only 'clever' way I found to deal with this is to use `python`, `jinja2` library and write a small code generator.
But, in order to do that I had to install `python`, install the library, create a `template`, create a custom `script` to read values from a `text file` and then generate code for the values read.
I was wondering is there any easier way to achieve the above?
Any editor or plugin to support code generation?
I know that IDEs such as Netbeans, Eclipse can generate some code - like getters and setters ... etc, but it is not enough...
In a nutshell,
I want to regenerate some lines of code by altering only specific parts ... The question is how to achieve that easily? (I know the hard way to do this) ..I am seeking for ideas... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42984884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532778/"
] | You can do that with a lightweight code generator like Telosys :
* <http://www.telosys.org/>
* <https://modeling-languages.com/telosys-tools-the-concept-of-lightweight-model-for-code-generation/>
In your case Telosys-CLI with a DSL model is probably the right choice, you'll just have to create your specific templates in Velocity language ( <http://velocity.apache.org/> ) | In such scenarios, the best thing you could do is to use a constant array together with a HashMap. The constant array will hold keynames for the hashmap whereas the hashmap will also hold the value for each one.
For instance:
```
String[] keys = {"name", "surname", "whatever" };
HashMap<String, String> elements = new HashMap<String, String>();
for (String key : keys)
{
elements.put(key, rs.getString(key));
}
```
You just have to be careful that all the elements are from the same type. If they are not, you will have to either store them as Objects and then cast them.
EDIT: for using in a Scriptlet, a good idea would be:
```
<tr>
<% for (String key : keys)
{
%>
<td><%= elements.get(key)%></td>
<% } %>
</tr>
``` |
42,984,884 | It is awfully often required to write repeatable pieces of code.
Consider the following example from `Java` (although, it may not be the best example, but I hope you get the general idea...)
`String X = rs.getString("X");`
Where `X` will have values: `'name'`,`'surname'` ... and `20`-`30` other values.
(Another example would be an `HTML` code and any other code - you need to create for `X`)
The end result should be:
```
String name=rs.getString("name");
String surname=rs.getString("surname");
....
String whatever = rs.getString("whatever");
```
Here is another example with `html` table and some `scriplets`, in this case string to replicate would be `<th>X</th>` and `<td><%=myBean.getX()%></td>` the end result would be:
```
<table style="width:100%">
<tr>
<th>name</th>
<th>surname</th>
<th>..</th>
<th>whatever</th>
</tr>
<tr>
<td><%=myBean.getName()%></td>
<td><%=myBean.getSurname()%></td>
<td>..</td>
<td><%=myBean.getWhatever()%></td>
</tr>
</table>
```
So, apart form copy-pasting the above for `30` times and then editing, the the only 'clever' way I found to deal with this is to use `python`, `jinja2` library and write a small code generator.
But, in order to do that I had to install `python`, install the library, create a `template`, create a custom `script` to read values from a `text file` and then generate code for the values read.
I was wondering is there any easier way to achieve the above?
Any editor or plugin to support code generation?
I know that IDEs such as Netbeans, Eclipse can generate some code - like getters and setters ... etc, but it is not enough...
In a nutshell,
I want to regenerate some lines of code by altering only specific parts ... The question is how to achieve that easily? (I know the hard way to do this) ..I am seeking for ideas... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42984884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532778/"
] | Probably I am looking for something that does not exist.
So, I'll just post my '*hard way*' of achieving, what I have described in my question (in hope that this would be useful for somebody - sometime).
Here I will preset a small code generator I am using to generate java, html, jsp, xsd and other codes.
I am using [Python27](https://www.python.org/download/releases/2.7/) and [Jinja2-2.7.2](https://pypi.python.org/pypi/Jinja2/2.7.2)
My Files:
**InputData.txt**
```
:This is field list
field1:field1 description
field2:field2 description
field3:field3 description
field4:field4 description
name:first name of the person
surname:last name of the person
whatever:whatever you need
```
**CodeGenerator.py**
```
import jinja2
import codecs
templateLoader = jinja2.FileSystemLoader( searchpath="." )
templateEnv = jinja2.Environment( loader=templateLoader )
TEMPLATE_FILE = "CodeGenerator.jinja"
template = templateEnv.get_template( TEMPLATE_FILE )
COLUMNS = [tuple(line.split(':')) for line in codecs.open( "InputData.txt", "r", "utf-8" )]
COLUMNS = map(lambda s: (s[0],(s[0].strip().title(),s[1].strip())), COLUMNS)
#title() copy of the string in which first characters of all the words are capitalized.
#strip() copy of the string, all chars have been stripped from the beginning and the end
#lambda s --> (field1,(Field1,field1 description))
#ignore the first line
COLUMNS.pop(0)
#add variables to work with
templateVars = { "table" : "MyTableName",
"description" : "A simple code generator",
"columns" : COLUMNS
}
outputText = template.render( templateVars )
f = open('Generated.txt', 'w')
outputText = outputText.encode('utf-8')
f.write(outputText)
f.close()
print outputText
```
**CodeGenerator.jinja**
```
//------------------model------------------------
//Generated code for model
import java.io.Serializable;
public class {{table|capitalize}}_Model implements Serializable{
{%for columnName,columnTitle in columns%}
private String {{columnName|lower}};{%endfor%}
{% for columnName,columnTitle in columns %}
public void set{{columnName|capitalize}}(String {{columnName|lower}}){
this.{{columnName|lower}}={{columnName|lower}};
}
public String get{{columnName|capitalize}}(){
return this.{{columnName|lower}};
}
{% endfor %}
public {{table|capitalize}}_Model({% for columnName,columnTitle in columns %}String {{columnName|lower}}{% if not loop.last %},{% endif %}{% endfor %}){
{% for columnName,columnTitle in columns %}
this.{{columnName|lower}}={{columnName|lower}}; {% endfor %}
}
public String toString(){
return {% for columnName,columnTitle in columns %}"{{columnName|lower}}:" + this.{{columnName|lower}}{% if not loop.last %}+{% endif %}{% endfor %};
}
}
//------------------model------------------------
//-----------------getStrings--------------------
{% for columnName,columnTitle in columns %}
String {{columnName}}=rs.getString("{{columnName}}");
{% endfor %}
//----------------------------------------------
//------------------jsp example-----------------
{% for columnName,columnTitle in columns %}
<s:label cssStyle ="margin-top:5px;color:blue;" value="{{columnTitle[1]}} :" id="{{columnName}}_label"/>
<s:textfield label="{{columnTitle[1]}}" name="myBean.{{columnName}}" />
{% endfor %}
//------------------jsp example-----------------
``` | If I understand your problem correctly, you have a `ResultSet` with a lot of columns. And you do not want to get them one by one.
It is possible to get all the columns from a `ResultSet` the following way:
```
ResultSetMetaData metaData = resultSet.getMetaData();
for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) {
String columnName = metaData.getColumnName(columnIndex);
String value = resultSet.getString(columnIndex);
}
```
Granted all the values will b e represented as strings in this example, but you can determine the type of the column also by using the same `metaData` object. Read more about it in the documentation: <https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html> |
42,984,884 | It is awfully often required to write repeatable pieces of code.
Consider the following example from `Java` (although, it may not be the best example, but I hope you get the general idea...)
`String X = rs.getString("X");`
Where `X` will have values: `'name'`,`'surname'` ... and `20`-`30` other values.
(Another example would be an `HTML` code and any other code - you need to create for `X`)
The end result should be:
```
String name=rs.getString("name");
String surname=rs.getString("surname");
....
String whatever = rs.getString("whatever");
```
Here is another example with `html` table and some `scriplets`, in this case string to replicate would be `<th>X</th>` and `<td><%=myBean.getX()%></td>` the end result would be:
```
<table style="width:100%">
<tr>
<th>name</th>
<th>surname</th>
<th>..</th>
<th>whatever</th>
</tr>
<tr>
<td><%=myBean.getName()%></td>
<td><%=myBean.getSurname()%></td>
<td>..</td>
<td><%=myBean.getWhatever()%></td>
</tr>
</table>
```
So, apart form copy-pasting the above for `30` times and then editing, the the only 'clever' way I found to deal with this is to use `python`, `jinja2` library and write a small code generator.
But, in order to do that I had to install `python`, install the library, create a `template`, create a custom `script` to read values from a `text file` and then generate code for the values read.
I was wondering is there any easier way to achieve the above?
Any editor or plugin to support code generation?
I know that IDEs such as Netbeans, Eclipse can generate some code - like getters and setters ... etc, but it is not enough...
In a nutshell,
I want to regenerate some lines of code by altering only specific parts ... The question is how to achieve that easily? (I know the hard way to do this) ..I am seeking for ideas... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42984884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532778/"
] | You can do that with a lightweight code generator like Telosys :
* <http://www.telosys.org/>
* <https://modeling-languages.com/telosys-tools-the-concept-of-lightweight-model-for-code-generation/>
In your case Telosys-CLI with a DSL model is probably the right choice, you'll just have to create your specific templates in Velocity language ( <http://velocity.apache.org/> ) | If I understand your problem correctly, you have a `ResultSet` with a lot of columns. And you do not want to get them one by one.
It is possible to get all the columns from a `ResultSet` the following way:
```
ResultSetMetaData metaData = resultSet.getMetaData();
for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) {
String columnName = metaData.getColumnName(columnIndex);
String value = resultSet.getString(columnIndex);
}
```
Granted all the values will b e represented as strings in this example, but you can determine the type of the column also by using the same `metaData` object. Read more about it in the documentation: <https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html> |
31,981,072 | I installed cordova-plugin-splashscreen but this doesnt help me.
What lines should I add to my config.xml file and where to place the splash.9.png file?
Previously (before updating my Cordova version to the latest one) splashscreen was working fine with the following options:
```
<preference name="splashscreen" value="splash" />
<preference name="splashScreenDelay" value="10000" />
```
and one splash.9.png file in res/drawable folded.
What am I doing wrong? | 2015/08/13 | [
"https://Stackoverflow.com/questions/31981072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2922399/"
] | I think you can use the attribute sortFunction. I quote from the Primefaces 5.1 User Guide page 153-154
>
> Instead of using the default sorting algorithm which uses a java
> comparator, you can plug-in your own sort method as well
>
>
>
```
public int sortByModel(Object car1, Object car2) {
car2.compareTo(car1);
}
```
And then in your html file
```
<p:dataTable var="car" value="#{carBean.cars}">
<p:column sortBy="#{car.model}" sortFunction="#{carBean.sortByModel}"
headerText="Model">
<h:outputText value="#{car.model}" />
</p:column>
...more columns
</p:dataTable>
``` | You need to use sortFunction="#{testBean.customSort}" and you can customized your sorting. |
680,957 | >
> For the Fibonacci sequence $F\_1=F\_2=1$, $F\_{n+2}=F\_n+F\_{n+1}$, prove that $$\sum\_{i=1}^n F\_i= F\_{n+2} - 1$$ for $n\ge 1$.
>
>
>
I don't quite know how to approach this problem.
Can someone help and explain please? | 2014/02/18 | [
"https://math.stackexchange.com/questions/680957",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/124878/"
] | Let us do an induction on $n$.
* *Induction start.* For $n=1$, we have $F\_1=1=F\_3-1$, so the induction start is done.
* *Induction hypothesis.* Let us assume we proved the assertion already for $n-1$.
* *Induction step.* Then
$$\sum\_{k=1}^n F\_k = \color{red}{\sum\_{k=1}^{n-1} F\_k} + F\_n = \color{red}{F\_{n+1}-1}+F\_n = F\_{n+2}-1$$
In the second equality we have used the induction hypothesis and in the last equality the definition of the Fibonacci sequence. | Just for fun, let us try to prove $\sum\limits\_{k=1}^n F\_k= F\_{n+2} - 1$ using [Binet's formula](http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression).
---
Recall that we have
$$F\_n=\frac{a^n-b^n}{\sqrt5}$$
where $a=\frac{1+\sqrt5}2$ and $b=\frac{1-\sqrt5}2$.
A few identities, that are easy to check and which may be useful:
$$
\begin{align\*}
a+b&=1\\
a-b&=\sqrt5\\
ab&=-1\\
1+a&=a^2\\
1+b&=b^2
\end{align\*}
$$
(Most of these identities simply follow from noticing that $a$, $b$ are roots of $x^2-x-1$ and using [Vieta's formulas](http://en.wikipedia.org/wiki/Vieta%27s_formulas)).
---
Now we want to compute
$$\sum\limits\_{k=1}^n F\_k=
\sum\limits\_{k=1}^n \frac{a^k-b^k}{\sqrt5}=
\frac 1{\sqrt5} \left(\sum\limits\_{k=1}^n a^k- \sum\limits\_{k=1}^n b^k\right)
$$
Using the formula $1+x+\dots+x^n = \frac{x^{n+1}-1}{x-1}$ we get
$$
\begin{gather\*}
\frac1{\sqrt5} \left(\frac{a^{n+1}-1}{a-1}-\frac{b^{n+1}-1}{b-1}\right) = \\
\frac1{\sqrt5} \cdot \frac{(a^{n+1}-1)(b-1)-(b^{n+1}-1)(a-1)}{(a-1)(b-1)} = \\
\frac1{\sqrt5} \cdot \frac{a^{n+1}b-a^{n+1}-b-b^{n+1}a+b^{n+1}+a}{ab-a-b+1} = \\
\frac1{\sqrt5} \cdot \frac{-(a^{n+1}-b^{n+1})+ab(a^n-b^n)+(a-b)}{ab-(a+b)+1} = \\
\frac1{\sqrt5} \cdot \frac{-(a^{n+1}-b^{n+1})-(a^n-b^n)+\sqrt5}{-1-1+1} = \\
\frac{-(a^{n+1}-b^{n+1})-(a^n-b^n)+\sqrt5}{-\sqrt5}= \\
\frac{(a^{n+1}-b^{n+1})+(a^n-b^n)-\sqrt5}{\sqrt5}= \\
\frac{a^{n+1}-b^{n+1}}{\sqrt5}+\frac{a^{n}-b^{n}}{\sqrt5}-\frac{\sqrt5}{\sqrt5} = \\
F\_{n+1}+F\_n-1 = F\_{n+2}-1
\end{gather\*}
$$ |
680,957 | >
> For the Fibonacci sequence $F\_1=F\_2=1$, $F\_{n+2}=F\_n+F\_{n+1}$, prove that $$\sum\_{i=1}^n F\_i= F\_{n+2} - 1$$ for $n\ge 1$.
>
>
>
I don't quite know how to approach this problem.
Can someone help and explain please? | 2014/02/18 | [
"https://math.stackexchange.com/questions/680957",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/124878/"
] | We define $F\_{n + 2} = F\_n + F\_{n + 1}$. From this we see that
$$F\_n = F\_{n + 2} - F\_{n + 1}\\
\sum\_{i = 1}^nF\_n = \sum\_{i = 1}^n \left(F\_{n + 2} - F\_{n + 1}\right)\\
\sum\_{i = 1}^nF\_n = F\_{n + 2} - F\_2\\
\sum\_{i = 1}^nF\_n = F\_{n + 2} - 1$$
We basically hinge upon the large amounts of cancellation that occurs on the right hand side when summing up from $i = 1$ to $n$. | Just for fun, let us try to prove $\sum\limits\_{k=1}^n F\_k= F\_{n+2} - 1$ using [Binet's formula](http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression).
---
Recall that we have
$$F\_n=\frac{a^n-b^n}{\sqrt5}$$
where $a=\frac{1+\sqrt5}2$ and $b=\frac{1-\sqrt5}2$.
A few identities, that are easy to check and which may be useful:
$$
\begin{align\*}
a+b&=1\\
a-b&=\sqrt5\\
ab&=-1\\
1+a&=a^2\\
1+b&=b^2
\end{align\*}
$$
(Most of these identities simply follow from noticing that $a$, $b$ are roots of $x^2-x-1$ and using [Vieta's formulas](http://en.wikipedia.org/wiki/Vieta%27s_formulas)).
---
Now we want to compute
$$\sum\limits\_{k=1}^n F\_k=
\sum\limits\_{k=1}^n \frac{a^k-b^k}{\sqrt5}=
\frac 1{\sqrt5} \left(\sum\limits\_{k=1}^n a^k- \sum\limits\_{k=1}^n b^k\right)
$$
Using the formula $1+x+\dots+x^n = \frac{x^{n+1}-1}{x-1}$ we get
$$
\begin{gather\*}
\frac1{\sqrt5} \left(\frac{a^{n+1}-1}{a-1}-\frac{b^{n+1}-1}{b-1}\right) = \\
\frac1{\sqrt5} \cdot \frac{(a^{n+1}-1)(b-1)-(b^{n+1}-1)(a-1)}{(a-1)(b-1)} = \\
\frac1{\sqrt5} \cdot \frac{a^{n+1}b-a^{n+1}-b-b^{n+1}a+b^{n+1}+a}{ab-a-b+1} = \\
\frac1{\sqrt5} \cdot \frac{-(a^{n+1}-b^{n+1})+ab(a^n-b^n)+(a-b)}{ab-(a+b)+1} = \\
\frac1{\sqrt5} \cdot \frac{-(a^{n+1}-b^{n+1})-(a^n-b^n)+\sqrt5}{-1-1+1} = \\
\frac{-(a^{n+1}-b^{n+1})-(a^n-b^n)+\sqrt5}{-\sqrt5}= \\
\frac{(a^{n+1}-b^{n+1})+(a^n-b^n)-\sqrt5}{\sqrt5}= \\
\frac{a^{n+1}-b^{n+1}}{\sqrt5}+\frac{a^{n}-b^{n}}{\sqrt5}-\frac{\sqrt5}{\sqrt5} = \\
F\_{n+1}+F\_n-1 = F\_{n+2}-1
\end{gather\*}
$$ |
680,957 | >
> For the Fibonacci sequence $F\_1=F\_2=1$, $F\_{n+2}=F\_n+F\_{n+1}$, prove that $$\sum\_{i=1}^n F\_i= F\_{n+2} - 1$$ for $n\ge 1$.
>
>
>
I don't quite know how to approach this problem.
Can someone help and explain please? | 2014/02/18 | [
"https://math.stackexchange.com/questions/680957",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/124878/"
] | **Hint** $\: $ It is straightforward to inductively prove this basic theorem on additive telescopy
$$\rm\ g(n)\ =\ \sum\_{i\: =\: 1}^n\:\ f(i)\ \ \iff\ \ \ g(n) - g(n\!-\!1)\ =\ f(n)\ \ for\ \ n> 1,\,\ \ g(1)=f(1)$$
Your is special case $\rm\ f(n) = F\_n,\ \ g(n) = F\_{n+2}-1,\, $ which is easily checked to satisfy the above: simply notice that $\rm\,g(n)-g(n\!-\!1) = F\_{n+2}-F\_{n+1} = F\_n = f(n),\ $ and $\rm\ g(1) = f(1) $
The [inductive proof](https://math.stackexchange.com/a/286362/242) of the general theorem is easier than that for your special case because the cancellation that occurs is much more obvious at this level of generality, whereas it is usually obfuscated by details of specific instances. Namely, the proof of the general theorem is just a rigorous inductive proof of the following *telescopic* cancellation
$$\rm \underbrace{\overbrace{g(1)}^{\large f(1)}\phantom{-g(1)}}\_{\large =\ 0}\!\!\!\!\!\!\!\!\!\!\!\!\!\overbrace{-\,g(1)\!+\!\phantom{g(2)}}^{\large f(2)}\!\!\!\!\!\!\!\!\! \underbrace{g(2) -g(2)}\_{\large =\ 0}\!\!\!\!\!\!\!\!\!\!\!\!\!\!\overbrace{\phantom{-g(2)}+ g(3)}^{\large f(3)}\!\!\!\!\!\!\!\!\!\!\underbrace{\phantom{g(3)}-g(3)}\_{\large =\ 0}\!+\:\cdots +\!g(n)\ =\ g(n) $$
This theorem reduces the inductive proof to simply verifying the RHS equalities, which is trivial polynomial arithmetic when $f(n),g(n)$ are polynomials in $n$. The above theorem is an example of *telescopy*, also known as the *Fundamental Theorem of Difference Calculus*, depending on context. You can find [many more examples](https://math.stackexchange.com/search?q=user%3A242+telescopy) of telescopy and related results in other answers here. | Just for fun, let us try to prove $\sum\limits\_{k=1}^n F\_k= F\_{n+2} - 1$ using [Binet's formula](http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression).
---
Recall that we have
$$F\_n=\frac{a^n-b^n}{\sqrt5}$$
where $a=\frac{1+\sqrt5}2$ and $b=\frac{1-\sqrt5}2$.
A few identities, that are easy to check and which may be useful:
$$
\begin{align\*}
a+b&=1\\
a-b&=\sqrt5\\
ab&=-1\\
1+a&=a^2\\
1+b&=b^2
\end{align\*}
$$
(Most of these identities simply follow from noticing that $a$, $b$ are roots of $x^2-x-1$ and using [Vieta's formulas](http://en.wikipedia.org/wiki/Vieta%27s_formulas)).
---
Now we want to compute
$$\sum\limits\_{k=1}^n F\_k=
\sum\limits\_{k=1}^n \frac{a^k-b^k}{\sqrt5}=
\frac 1{\sqrt5} \left(\sum\limits\_{k=1}^n a^k- \sum\limits\_{k=1}^n b^k\right)
$$
Using the formula $1+x+\dots+x^n = \frac{x^{n+1}-1}{x-1}$ we get
$$
\begin{gather\*}
\frac1{\sqrt5} \left(\frac{a^{n+1}-1}{a-1}-\frac{b^{n+1}-1}{b-1}\right) = \\
\frac1{\sqrt5} \cdot \frac{(a^{n+1}-1)(b-1)-(b^{n+1}-1)(a-1)}{(a-1)(b-1)} = \\
\frac1{\sqrt5} \cdot \frac{a^{n+1}b-a^{n+1}-b-b^{n+1}a+b^{n+1}+a}{ab-a-b+1} = \\
\frac1{\sqrt5} \cdot \frac{-(a^{n+1}-b^{n+1})+ab(a^n-b^n)+(a-b)}{ab-(a+b)+1} = \\
\frac1{\sqrt5} \cdot \frac{-(a^{n+1}-b^{n+1})-(a^n-b^n)+\sqrt5}{-1-1+1} = \\
\frac{-(a^{n+1}-b^{n+1})-(a^n-b^n)+\sqrt5}{-\sqrt5}= \\
\frac{(a^{n+1}-b^{n+1})+(a^n-b^n)-\sqrt5}{\sqrt5}= \\
\frac{a^{n+1}-b^{n+1}}{\sqrt5}+\frac{a^{n}-b^{n}}{\sqrt5}-\frac{\sqrt5}{\sqrt5} = \\
F\_{n+1}+F\_n-1 = F\_{n+2}-1
\end{gather\*}
$$ |
229,353 | In my main page (call it `index.aspx`) I call
```
<%Html.RenderPartial("_PowerSearch", ViewData.Model);%>
```
Here the `viewdata.model != null`
When I arrive at my partial:
```
<%=ViewData.Model%>
```
Says `viewdata.model == null`
What gives?! | 2008/10/23 | [
"https://Stackoverflow.com/questions/229353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] | Have you tried just passing in ViewData instead of ViewData.Model? This is an abridged version what I use in my helpers (shamelessly stolen from the Storefront series):
```
/// <summary>
/// Renders a LoggingWeb user control.
/// </summary>
/// <param name="helper">Helper to extend.</param>
/// <param name="control">Type of control.</param>
/// <param name="data">ViewData to pass in.</param>
public static void RenderLoggingControl(this System.Web.Mvc.HtmlHelper helper, LoggingControls control, object data)
{
string controlName = string.Format("{0}.ascx", control);
string controlPath = string.Format("~/Controls/{0}", controlName);
string absControlPath = VirtualPathUtility.ToAbsolute(controlPath);
if (data == null)
{
helper.RenderPartial(absControlPath, helper.ViewContext.ViewData);
}
else
{
helper.RenderPartial(absControlPath, data, helper.ViewContext.ViewData);
}
}
```
Note that I pass in the current ViewData and not the Model. | This is untested:
```
<%=Html.RenderPartial("_ColorList.ascx", new ViewDataDictionary(ViewData.Model.Colors));%>
```
Your control view is expecting view data specific to it in this case. If your control wants a property on the model called Colors then perhaps:
```
<%=Html.RenderPartial("_ColorList.ascx", new ViewDataDictionary(new { Colors = ViewData.Model.Colors }));%>
``` |
55,687,308 | Adjust the select box when option value is bigger using element ui
How this is possible please guide
It should not cut the string after selection
```
<template>
<el-select v-model="value" placeholder="Select">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
</div>
```
```js
var Main = {
data() {
return {
options: [{
value: 'OptionFirstWithBigCharacter',
label: 'OptionFirstWithBigCharacter'
}, {
value: 'Option2',
label: 'Option2'
}, {
value: 'Option3',
label: 'Option3'
}, {
value: 'Option4',
label: 'Option4'
}, {
value: 'Option5',
label: 'Option5'
}],
value: ''
}
}
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
```
```css
@import url("//unpkg.com/element-ui@2.7.2/lib/theme-chalk/index.css");
```
```html
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.7.2/lib/index.js"></script>
<div id="app">
<template>
<el-select v-model="value" placeholder="Select">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
</div>
```
"OptionFirstWithBigCharacter" should display properly | 2019/04/15 | [
"https://Stackoverflow.com/questions/55687308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10052353/"
] | Add some padding to the select input as follows :
```
.el-select>.el-input {
display: block;
padding-right: 2px;
}
```
```js
var Main = {
data() {
return {
options: [{
value: 'OptionFirstWithBigCharacter',
label: 'OptionFirstWithBigCharacter'
}, {
value: 'Option2',
label: 'Option2'
}, {
value: 'Option3',
label: 'Option3'
}, {
value: 'Option4',
label: 'Option4'
}, {
value: 'Option5',
label: 'Option5'
}],
value: ''
}
}
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
```
```css
@import url("//unpkg.com/element-ui@2.7.2/lib/theme-chalk/index.css");
.el-select>.el-input {
display: block;
padding-right: 8px;
}
```
```html
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.7.2/lib/index.js"></script>
<div id="app">
<template>
<el-select v-model="value" placeholder="Select">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
</div>
``` | That's an interesting question.
Obviously, the solution would be to calculate the text width of selected value and adjust select to this width, but that's a tricky task.
Under the hood `el-select` uses `<input>` element to show selected item, and `<input>` can't adjust its width based on its value, so we'd need to use another element that can do that. For example, `<span>` is good choice.
Here is what I've got:
```js
Vue.config.productionTip = false;
var Main = {
data() {
return {
options: [{
value: 'OptionFirstWithBigCharacter',
label: 'OptionFirstWithBigCharacter'
}, {
value: 'Option2',
label: 'Option2'
}, {
value: 'Option3',
label: 'Option3'
}, {
value: 'Option4',
label: 'Option4'
}, {
value: 'Option5',
label: 'Option5'
}],
value: ''
}
},
mounted() {
// pass true to make input use its initial width as min-width
this._addShadow();
},
methods: {
_getElements() {
// helper method to fetch input and its shadow span
const input = this.$refs.resizeable.$el.querySelector('.el-input__inner');
const span = input.previousSibling;;
return { input, span };
},
_addShadow(useMinWidth = false) {
// this method adds shadow span to input
// we'll use this span to calculate text width
const { input } = this._getElements();
const span = document.createElement('span');
span.classList.add('resizeable-shadow');
input.parentNode.insertBefore(span, input);
// copy font, padding and border styles from input
const css = input.computedStyleMap();
span.style.font = css.get('font');
span.style.padding = css.get('padding');
span.style.border = css.get('border');
if (useMinWidth) {
span.style.minWidth = `${input.getBoundingClientRect().width}px`;
}
},
_adjustSize() {
this.$nextTick(() => {
const { input, span } = this._getElements();
span.textContent = input.value;
input.style.width = `${span.getBoundingClientRect().width}px`;
});
},
},
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
```
```css
@import url("//unpkg.com/element-ui@2.7.2/lib/theme-chalk/index.css");
span.resizeable-shadow {
display: inline-block;
box-sizing: border-box;
position: absolute;
left: -99999px;
top: -99999px;
}
```
```html
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.7.2/lib/index.js"></script>
<div id="app">
<template>
<el-select v-model="value" placeholder="Select"
ref="resizeable" @change="_adjustSize">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
</div>
```
Code is pretty simple and I've added some comments, so it shouldn't be hard to adjust it to your needs: move it to mixin, add support for multiple selects etc.
Popper works weird in SO snippet, so here is working [jsfiddle](https://jsfiddle.net/iStyx/agpxoL07/). |
13,812 | [*Garry's Mod*](http://www.garrysmod.com/) has a [copy-protection trap that shows this error](http://www.playerattack.com/news/2011/04/12/garrys-mod-catches-pirates-the-fun-way/):
>
> Unable to shade polygon normals
>
>
>
It made me wonder if such a problem could ever *actually* exist. Can polygon normals be shaded? Is a failure to do so detectable and reportable? | 2011/06/17 | [
"https://gamedev.stackexchange.com/questions/13812",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/1966/"
] | "Can a polygon normal be shaded" - No, a normal is a vector which is a 1-d object, so unless you're going to actually draw the normal and shade it, that statement doesn't make much sense.
However, shading polygons (2-d objects) commonly use the polygon normal in their shading calculations for light calculations to control how light or dark they can be.
So, I have no idea what that message is trying to say. | It's 100% not possible to shade a normal at all.
As discussed in [this link](https://www.bit-tech.net/news/gaming/garry-s-mod-traps-pirates-with-error/1/) from the comments, the message was chosen to stop people from being able to research it, to tempt them into asking about it, and outing themselves as pirates.
This was counting on players not knowing what a polygon normal actually was. :) |
13,812 | [*Garry's Mod*](http://www.garrysmod.com/) has a [copy-protection trap that shows this error](http://www.playerattack.com/news/2011/04/12/garrys-mod-catches-pirates-the-fun-way/):
>
> Unable to shade polygon normals
>
>
>
It made me wonder if such a problem could ever *actually* exist. Can polygon normals be shaded? Is a failure to do so detectable and reportable? | 2011/06/17 | [
"https://gamedev.stackexchange.com/questions/13812",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/1966/"
] | Normals in 3D graphics are a 3D vector indicating orientation or direction.
Normals themselves cannot be shades, as how can you shade {.1,0,.4} ?
Normals can be used to shade the polygons themselves. For example, a light source at a certain angle hitting a model made of polygons at a certain angle, the normals of the polygon faces can be used in the shading process to make the light make parts of the model brighter. | It's 100% not possible to shade a normal at all.
As discussed in [this link](https://www.bit-tech.net/news/gaming/garry-s-mod-traps-pirates-with-error/1/) from the comments, the message was chosen to stop people from being able to research it, to tempt them into asking about it, and outing themselves as pirates.
This was counting on players not knowing what a polygon normal actually was. :) |
34,538,343 | 1. If I am correct, a remote-tracking branch can be created when cloning the remote repository. Are there other cases when a remote-tracking branch is created?
2. If I am right, a remote-tracking branch is updated when fetching/pulling from the remote repository. Are there other cases when a remote-tracking branch is updated?
3. As a special case of 2, when `git push` a local branch to the remote repository, if the local branch has an associated remote-tracking branch in the local repository (i.e. if the local branch is a local-tracking branch, defined in Version Control with Git by Loeliger 2ed), does `git push` update the remote-tracking branch , or the remote-tracking branch can be updated only indirectly from the remote repository by running `git fetch` or `git pull` after `git push`?
4. As a special case of 1, if `git push` pushes local non-tracking branches to remote branches (i.e. if there is no corresponding remote branches to the local branches to be pushed), will `git push` create remote-tracking branches associated with the local non-tracking branches and turn them into local tracking ones? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156458/"
] | Let's take these [~~three~~ four](https://people.csail.mit.edu/paulfitz/spanish/script.html) :-) questions in order, more or less:
>
> 1. ... a remote-tracking branch can be created when cloning the remote repository. Are there other cases when a remote-tracking branch is created?
>
>
>
They are; and at least potentially yes, but let's get to that later.
Specifically, when `git clone` is making an initial clone of another repository, it adds a `fetch =` configuration line for the remote. The line added depends on these two options:
* `--origin *name*`: alters the name of the remote. Normally the name is just `origin` and the fetch configuration is `fetch = +refs/heads/*:refs/remotes/origin/*`, but if you change the name of the remote to, say, `zerblatt`, you get `+refs/heads/*:refs/remotes/zerblatt/*`.
* `--mirror`: alters the fetch configuration to read `fetch = +refs/*:refs/*`. Note that in this case there are probably no remote-tracking branches after all, since "remote-tracking branches" is just a weakly abstracted way of saying "references in the `refs/remotes/` name-space" and now we don't have any renaming going on. (If the repository being cloned presents its own remote-tracking branchesβreferences in `refs/remotes/`βthey *will* get copied and we *will* get remote-tracking branches. We might run `git ls-remote` to find out what references they have before we start cloning, in order to find out, although it's a little tricky since if we haven't started cloning, we don't have a repository in which to configure a remote so as to use `git ls-remote`. There is a method though!)
Let's go on to:
>
> 2. If I am right, a remote-tracking branch is updated when fetching/pulling from the remote repository. Are there other cases when a remote-tracking branch is updated?
>
>
>
Yes: in particular a remote-tracking branch (which, again, is just a reference in the `refs/remotes/` name-space) is updated automatically on at least some successful `git push` operations. Exactly which ones depends on your version of git, since `push` didn't always update them: the *documentation* noting this update first appeared in git 1.8.4 although the updates probably went in around git 1.7; and git 1.9 and later also update them in so-called "triangular workflows" (fetch from one remote, push to a different remote).
---
Let me take a little break here and make a few more notes about remote-tracking branches.
As we already noted, a remote-tracking branch is simply a reference whose full name begins with `refs/remotes/`. Git has a "plumbing" command, `git update-ref`, that you (or anyone or any script) can use to update *any* reference. For instance, suppose you've fetched from `origin` fairly recently, then added one commit to your own `master` (that's set with origin/master as its upstream) so that `git status` says you're "ahead 1". If you were to run:
```
git update-ref refs/remotes/origin/master master
```
and then run `git status`, your git would claim that you are now up-to-date. What happened is that you've told your git that "their" master (`origin/master`) points to the same commit as your own, even though you have not pushed your own commit yet. (If you do run this, you can simply run `git fetch origin` to fix `refs/remotes/origin/master`, or of course use `git update-ref` to fix it.)
This exposes the underlying mechanism here: git simply writes, to `refs/remotes/origin/master`, the actual SHA-1 ID of the commit object your git saw when it talked to their (the remote's) git. There is a strong constraint on this: git *can't* put that SHA-1 ID in unless that SHA-1 ID corresponds to an actual object already stored in your own repository. In practice, git "feels" (and is) safe in writing that ID there after a successful fetch or push, since after a successful fetch, you must have the object, and to complete a push, you must have the object, and in both cases git has just seen that ID corresponding to some name on the given remote.
This also shows how `git status` can say "ahead 1" in the first place: it simply counts the commits reachable from your `master` that are not reachable from your master's upstream. That is:
```
ahead=$(git rev-list --count master@{u}..master)
behind=$(git rev-list --count master..master@{u})
echo "branch master is ahead $ahead and behind $behind"
```
This information is as up-to-date (or out-of-date) as the last time the remote-tracking branch was properly updated.
Let's also note, now, that `git clone` can be split up into several separate git commands. Let's assume you're cloning with neither `--origin` nor `--mirror` and that the url is simply `$url` (and that none of these steps fail):
```
mkdir myclone && cd myclone && git init
git remote add origin $url
git fetch origin
git checkout ...
```
(exactly what to `git checkout` is a bit of a mystery; and the `git fetch` command can be skipped if we add `-f` to the `git remote add` line, but I intend to do something in between here for illustration purposes). What does each command do?
* The mkdir + cd + git-init sequence creates a new empty, suitable-for-clone repository.
* The `git remote add` line configures the remote `origin` to fetch from `$url` and adds a `fetch = +refs/heads/*:refs/remotes/origin/*` line.
* The `git fetch origin` command then mostly-completes the cloning process (the missing bit is the final `git checkout`).
Now, suppose that before we run `git fetch origin`, we run other git commands, such as `git config --edit` and mess with the `fetch =` line. We can set things up so that we don't get remote-tracking branches. We can create commits of our own, unrelated to what is on the actual remote, and use `git update-ref` to assign them to remote-tracking branches. We can run `git ls-remote` to find out what branches exist on the remote.
None of these are particularly *useful* but they are all possible. (And if anyone has any *good* reason to do tricky branch-name-mapping things by creating a lot of `fetch =` lines, perhaps they are useful after all.)
(What should we `git checkout`, on that last line? The answer depends on several things, only some of which we have direct control over. If you ran `git clone` with `-b branch`, that's the one we can handle the most easily: we should `git checkout branch`. If there's a `refs/remotes/origin/branch` we'll get a local branch `branch` that has its upstream set to `origin/branch`. If you did not specify a `-b` option, though, then what to check out, to emulate your git's `git clone`, depends on both *your* version of git, and the *remote's* version, as well as what we'd see from `git ls-remote`. Newer gits ask for and receive the branch name. Older gits take the [internal equivalent of the] ls-remote output and compare the SHA-1 the remote git shows for `HEAD` to the SHA-1 the remote git shows for each branch: if there's exactly one match, that's the branch; if there are multiple matches, pick one arbitrarily; if there are no matches at all, use `master`. If a newer git is talking to an older git that does not support the new "tell me the branch by name" option, the newer git falls back to the older method.)
---
Back to your questions:
>
> 3. As a special case of 2, when `git push` a local branch to the remote repository, if the local branch has an associated remote-tracking branch in the local repository (i.e. if the local branch is a local-tracking branch, defined in Version Control with Git by Loeliger 2ed), does `git push` update the remote-tracking branch, or the remote-tracking branch can be updated only indirectly from the remote repository by running `git fetch` or `git pull` after `git push`?
>
>
>
I find this question confusing. There's no special casing involved here. At some point, we know that your `git push` has decided to send remote *`R`* a request that, in effect, says: "please set your `refs/heads/foo` to SHA-1 `1234567890123456789012345678901234567890`" (substitute in the correct `refs/heads/` name and SHA-1 ID as needed). (When using `--force-with-lease` the request has more information in it, and in any case the request also carries the "force" flag. It's up to the remote to decide whether to obey the "force" flag. However, it's important to note here that the request delivers a raw SHA-1, and *not* the name of your branch in your local git repository. The remote git gets just *his* reference-name, and the SHA-1. What this means in practice is that the remote's pre- and post-receive and update hooks cannot see your branch names. [They don't get to see the force flag either, which I consider a minor bug, but that's another issue entirely.])
Their git replies to this request with either a "yes, done" or "no: error: <details>" answer.
Your git then has the option of treating the "yes, done" answer as sufficient to update your remote-tracking branch for remote *`R`*. (Of course a "no" reply means there is nothing to update.) It doesn't matter what local branch, if any, you're on, nor what local branches you have, nor whether any of them have upstreams set. This is in part because this same code allows you to do:
```
git push origin 1234567890123456789012345678901234567890:refs/heads/foo
```
to set their `refs/heads/foo` to that commit (assuming the commit ID is valid; your git will check your repository first, and deliver the commit to their git if necessary, as usual).
The tricky bit for your git, in terms of doing a remote-tracking branch update, is figuring out what name your git should replace `refs/heads/foo` with. This is where the linear vs triangular work-flow stuff comes in, and where we must check which version of git you have. If you are using a triangular work-flow and your git is older than 1.9, your git doesn't know what to update, and updates nothing. If your git is older than about 1.7 or so, it never tries to figure out what to update, and updates nothing. Otherwise it uses the appropriate refspec mapping to translate `refs/heads/foo` to see what to update.
Finally:
>
> 4. As a special case of 1, if git push pushes local non-tracking branches to remote branches (i.e. if there is no corresponding remote branches to the local branches to be pushed), will git push create remote-tracking branches associated with the local non-tracking branches and turn them into local tracking ones?
>
>
>
Pieces of this question still don't make sense to me, but pieces do make sense. Let's consider a concrete example, and ignore both triangular work-flows and weird name translations due to complicated multiple `fetch =` lines, so that we're dealing with simple `git push origin myname:theirname` commands. Let's further assume that the git version is reasonably up-to-date.
Again, your git, given `git push origin myname:theirname`, starts by translating `myname` to a raw SHA-1 ID. If you `git push origin myname` your git also consults your `push.default` to fill in the `theirname` part from the `myname` part, but let's assume you've given an explicit name, `refs/heads/foo` for instance. (This also lets you push by raw SHA-1 ID. In other words, it takes most of the complications away, and leaves us just with the git-to-git "push" session to worry about, for now.)
Your git now phones up their git using the URL for the remote. (If the URL refers to another repository on your own computer, your git plays both "your git" and "their git" roles, as it were, and uses a bunch of shortcuts as well, but let's just consider the over-the-Internet-phone case here.)
After some basic protocol handshaking, your git sends over any objects needed, then sends over all your update proposals, all at once (from each refspec you gave to your `git push`):
```
please set refs/heads/theirname to 123456...
please set refs/heads/anothername to 987654...
```
and so on.
Their git runs these requests through its checking-rules (both the built-in fast-forward checks, and any receive-side hooks: pre-receive and update) to see whether to allow them. Then it either writes the new SHA-1s into its references and says "yes, done" or rejects the update and says "no".
Your git takes all these replies and decides whether to update or create a `refs/remotes/origin/theirname` and/or `refs/remotes/origin/anothername`. (Remember, we're assuming the remote is named `origin`, and that your git is recent, etc.) For any "yes" reply, your git *does* update-or-create that name; for any "no", your git does not.
The update-or-create is done as if your `git fetch` had run `git update-ref` (though it just invokes the actual update directly, rather than using fork/exec or spawn, of course).
Now, once all of *this* is done, there's one more thing your git can do, and it depends on whether you supplied the `-u` (aka `--set-upstream`) flag to `git push` (which of course depends on whether your `git push` is new enough to have the `-u` flag; I forget when it appeared). It also requires that the left hand side of your `push` refspec(s) originally resolved to branch names, rather than raw SHA-1s. In this case your git will still have all the names.
If you specify `-u`, thenβas long as the push succeeds, your git effectively runs `git branch --set-upstream-to` to set or change the upstream for that branch. (Again, it just does this internally, of course.)
Let's put all these together into a fairly complex example. Suppose you have your own local branch `foo` and a remote named `origin`, and you do:
```
$ git fetch origin
[output snipped]
$ git for-each-ref refs/remotes/origin # let's see their branches
biguglysha1 commit refs/remotes/origin/HEAD
biguglysha1 commit refs/remotes/origin/master
# this confirms that they don't have a "refs/heads/theirname"
$ git push -u origin foo:refs/heads/theirname
[output snipped, but assume it says "all done"]
```
The full spelling, `refs/heads/theirname`, is required to cause the branch to get created successfully here (if the branch already exists you can use the short name, but then we have a boring case instead of an interesting one).
Because their git created the branch according to the name you supplied, and your git is new enough and you haven't set up weird name maps, you now have a `refs/remotes/origin/theirname`. Because you specified `-u`, your local branch `foo` now has its upstream set to `origin/theirname` as well. A `git branch -vv` will now show your `foo` as "tracking" `origin/theirname` and up-to-date.
This happened in two parts: when their git accepted the request to set `refs/heads/theirname`, your git created `refs/remotes/origin/theirname`, and figuring out `refs/remotes/origin/theirname` required going through the `fetch =` map; and then when your git applied the `-u` option, your git set your `branch.foo.remote` to `origin` and your `branch.foo.merge` to `refs/heads/theirname`. Interestingly, the second partβapplying the `-u` flagβdoes not need the map at all, since `branch.foo.merge` is set to `refs/heads/theirname`. But for `git branch -vv` to show `origin/theirname`, it has to go through the map. | Answers:
1. After initially cloning a Git repository, whenever somebody pushes up a new branch, a remote-tracking branch will be created for this new branch after a doing routine `fetch` (or `pull`).
2. Not that I'm aware of. Fetching or pulling should be the only two operations that update a remote-tracking branch.
3. Not always. Attempting to push a local branch with a corresponding remote-tracking branch that [cannot be fast-forwarded](https://stackoverflow.com/questions/4684352/what-does-git-push-non-fast-forward-updates-were-rejected-mean) (i.e. the remote-tracking branch contains commits not currently present in a local branch) will result in failure. |
44,280,718 | I have 4 byte data stream, I know at what bite I wanted to split them and assign them to a different variable. keeping in mind the data I receive is in hex format. let's say,
```
P_settings 4bytes p_timeout [6:0]
p_s_detected[7]
p_o_timeout [14:8]
p_o_timeout_set [15]
override_l_lvl [23:16]
l_b_lvl [31:24]
```
above P\_settings is 4 bytes and I wanted to split them byte into bits like `p_timeout [6:0] requires 7 bits of those 4 byte.`
Currently, the implementation I have tried is..for just one byte split into bits.
```
var soch = ((b_data>> 0)& 0x7F ); if i want first 7 bits
```
how do I do it for 4 byte streams | 2017/05/31 | [
"https://Stackoverflow.com/questions/44280718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5073018/"
] | Try code like this. You said input was a stream.
```
public class P_Settings
{
byte p_timeout; //[6:0]
Boolean p_s_detected; //[7]
byte p_o_timeout; // [14:8]
Boolean p_o_timeout_set; // [15]
byte override_l_lvl; //[23:16]
byte l_b_lvl; //[31:24]
public P_Settings(Stream data)
{
byte input = (byte)(data.ReadByte() & 0xff);
p_timeout = (byte)(input & 0x7F);
p_s_detected = (input & 0x80) == 0 ? false : true;
input = (byte)(data.ReadByte() & 0xff);
p_o_timeout = (byte)(input & 0x7F);
p_o_timeout_set = (input & 0x80) == 0 ? false : true;
override_l_lvl = (byte)(data.ReadByte() & 0xff);
l_b_lvl = (byte)(data.ReadByte() & 0xff);
}
}
``` | SO it turns out it much easier that i thought..
1) separate them by single byte and put them in a buffer and & operate them individually and you will get the data. thanks for all the support.
\*\*
```
byte input = (byte)( buffer[10]);//1 byte
var p_timeout = (byte)(input & 0x7F);
var p_s_detected = (input & 0x80) == 0 ? false : true;
input = (byte)( buffer[11]);//1 byte
var p_o_timeout = (byte)(input & 0x7F);
var p_o_timeout_set = (input & 0x80) == 0 ? false : true;
var override_l_lvl = (byte)(buffer[12] & 0xff);//1 byte
var l_b_lvl = (byte)(buffer[13] & 0xff); //1 byte
```
\*\* |
51,558,105 | I have an array consisting of hashes in the following form:
```
array = [
{"id": 1, "items": [{"item_code": 1, "qty": 2},{"item_code": 2, "qty": 2}]},
{"id": 2, "items": [{"item_code": 3, "qty": 2},{"item_code": 4, "qty": 2}]},
{"id": 1, "items": [{"item_code": 5, "qty": 2},{"item_code": 6, "qty": 2}]},
{"id": 2, "items": [{"item_code": 7, "qty": 2},{"item_code": 8, "qty": 2}]}
]
```
Do we have any convenient way to merge items according to ids:
Expected output:
```
array = [
{"id": 1, "items": [
{"item_code": 1, "qty": 2},
{"item_code": 2, "qty": 2},
{"item_code": 5, "qty": 2},
{"item_code": 6, "qty": 2}
]
},
{"id": 2, "items": [
{"item_code": 3, "qty": 2},
{"item_code": 4, "qty": 2},
{"item_code": 7, "qty": 2},
{"item_code": 8, "qty": 2}
]
}
]
```
I tried with group\_by, which doesn't satisfy the output format. | 2018/07/27 | [
"https://Stackoverflow.com/questions/51558105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6166821/"
] | Use [`group_by`](https://apidock.com/rails/Enumerable/group_by) and [`each_with_object`](https://apidock.com/rails/Enumerable/each_with_object):
```
ary.group_by { |elem| elem[:id] }.
each_with_object([]) do |(id, grouped_ary), out|
out << { id: id, items: grouped_ary.map { |h| h[:items] }.reduce(:|) }
end
=> [{:id=>1, :items=>[{:item_code=>1, :qty=>2},
{:item_code=>2, :qty=>2},
{:item_code=>5, :qty=>2},
{:item_code=>6, :qty=>2}]},
{:id=>2, :items=>[{:item_code=>3, :qty=>2},
{:item_code=>4, :qty=>2},
{:item_code=>7, :qty=>2},
{:item_code=>8, :qty=>2}]}]
``` | You can combine `group_by` and `transform_values!` (for the latter you need Ruby 2.4.0 and later, otherwise you can use `each_with_object` as @Jagdeep pointed out)
```
array.group_by { |item| item[:id] }
.transform_values! { |v| v.flat_map { |subitem| subitem[:items] } }
.map { |(id, items)| Hash["id", id, "items", items] }
``` |
51,558,105 | I have an array consisting of hashes in the following form:
```
array = [
{"id": 1, "items": [{"item_code": 1, "qty": 2},{"item_code": 2, "qty": 2}]},
{"id": 2, "items": [{"item_code": 3, "qty": 2},{"item_code": 4, "qty": 2}]},
{"id": 1, "items": [{"item_code": 5, "qty": 2},{"item_code": 6, "qty": 2}]},
{"id": 2, "items": [{"item_code": 7, "qty": 2},{"item_code": 8, "qty": 2}]}
]
```
Do we have any convenient way to merge items according to ids:
Expected output:
```
array = [
{"id": 1, "items": [
{"item_code": 1, "qty": 2},
{"item_code": 2, "qty": 2},
{"item_code": 5, "qty": 2},
{"item_code": 6, "qty": 2}
]
},
{"id": 2, "items": [
{"item_code": 3, "qty": 2},
{"item_code": 4, "qty": 2},
{"item_code": 7, "qty": 2},
{"item_code": 8, "qty": 2}
]
}
]
```
I tried with group\_by, which doesn't satisfy the output format. | 2018/07/27 | [
"https://Stackoverflow.com/questions/51558105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6166821/"
] | Use [`group_by`](https://apidock.com/rails/Enumerable/group_by) and [`each_with_object`](https://apidock.com/rails/Enumerable/each_with_object):
```
ary.group_by { |elem| elem[:id] }.
each_with_object([]) do |(id, grouped_ary), out|
out << { id: id, items: grouped_ary.map { |h| h[:items] }.reduce(:|) }
end
=> [{:id=>1, :items=>[{:item_code=>1, :qty=>2},
{:item_code=>2, :qty=>2},
{:item_code=>5, :qty=>2},
{:item_code=>6, :qty=>2}]},
{:id=>2, :items=>[{:item_code=>3, :qty=>2},
{:item_code=>4, :qty=>2},
{:item_code=>7, :qty=>2},
{:item_code=>8, :qty=>2}]}]
``` | ```
array.each_with_object({}) { |g,h| h.update(g[:id]=>g[:items]) { |_,o,n| o+n } }.
map { |k,v| { id: k, items: v } }
#=> [{:id=>1, :items=>[{:item_code=>1, :qty=>2}, {:item_code=>2, :qty=>2},
# {:item_code=>5, :qty=>2}, {:item_code=>6, :qty=>2}]},
# {:id=>2, :items=>[{:item_code=>3, :qty=>2}, {:item_code=>4, :qty=>2},
# {:item_code=>7, :qty=>2}, {:item_code=>8, :qty=>2}]}]
```
The first step is:
```
array.each_with_object({}) { |g,h| h.update(g[:id]=>g[:items]) { |_,o,n| o+n } }
#=> {1=>[{:item_code=>1, :qty=>2}, {:item_code=>2, :qty=>2},
# {:item_code=>5, :qty=>2}, {:item_code=>6, :qty=>2}],
# 2=>[{:item_code=>3, :qty=>2}, {:item_code=>4, :qty=>2},
# {:item_code=>7, :qty=>2}, {:item_code=>8, :qty=>2}]}
```
This makes use of the form of [Hash#update](http://ruby-doc.org/core-2.4.0/Hash.html#method-i-update) (a.k.a. `merge!`) that employs a block to determine the values of keys that are present in both hashes being merged. See the doc for the definitions of the three block variables.
Alternatively, one could write the following.
```
array.each_with_object({}) { |g,h| h.update(g[:id]=>g) { |_,o,n|
o.merge(n) { |k,oo,nn| k == :items ? oo+nn : oo } } }.values
``` |
51,558,105 | I have an array consisting of hashes in the following form:
```
array = [
{"id": 1, "items": [{"item_code": 1, "qty": 2},{"item_code": 2, "qty": 2}]},
{"id": 2, "items": [{"item_code": 3, "qty": 2},{"item_code": 4, "qty": 2}]},
{"id": 1, "items": [{"item_code": 5, "qty": 2},{"item_code": 6, "qty": 2}]},
{"id": 2, "items": [{"item_code": 7, "qty": 2},{"item_code": 8, "qty": 2}]}
]
```
Do we have any convenient way to merge items according to ids:
Expected output:
```
array = [
{"id": 1, "items": [
{"item_code": 1, "qty": 2},
{"item_code": 2, "qty": 2},
{"item_code": 5, "qty": 2},
{"item_code": 6, "qty": 2}
]
},
{"id": 2, "items": [
{"item_code": 3, "qty": 2},
{"item_code": 4, "qty": 2},
{"item_code": 7, "qty": 2},
{"item_code": 8, "qty": 2}
]
}
]
```
I tried with group\_by, which doesn't satisfy the output format. | 2018/07/27 | [
"https://Stackoverflow.com/questions/51558105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6166821/"
] | There is no need for `group_by`. Go straight with `each_with_object` directly from the scratch.
```
array.
each_with_object({}) do |hash, acc|
acc[hash[:id]] ?
acc[hash[:id]][:items] |= hash[:items] :
acc[hash[:id]] = hash
end.values
#β [{:id=>1, :items=>[{:item_code=>1, :qty=>2},
# {:item_code=>2, :qty=>2},
# {:item_code=>5, :qty=>2},
# {:item_code=>6, :qty=>2}]},
# {:id=>2, :items=>[{:item_code=>3, :qty=>2},
# {:item_code=>4, :qty=>2},
# {:item_code=>7, :qty=>2},
# {:item_code=>8, :qty=>2}]}]
``` | You can combine `group_by` and `transform_values!` (for the latter you need Ruby 2.4.0 and later, otherwise you can use `each_with_object` as @Jagdeep pointed out)
```
array.group_by { |item| item[:id] }
.transform_values! { |v| v.flat_map { |subitem| subitem[:items] } }
.map { |(id, items)| Hash["id", id, "items", items] }
``` |
51,558,105 | I have an array consisting of hashes in the following form:
```
array = [
{"id": 1, "items": [{"item_code": 1, "qty": 2},{"item_code": 2, "qty": 2}]},
{"id": 2, "items": [{"item_code": 3, "qty": 2},{"item_code": 4, "qty": 2}]},
{"id": 1, "items": [{"item_code": 5, "qty": 2},{"item_code": 6, "qty": 2}]},
{"id": 2, "items": [{"item_code": 7, "qty": 2},{"item_code": 8, "qty": 2}]}
]
```
Do we have any convenient way to merge items according to ids:
Expected output:
```
array = [
{"id": 1, "items": [
{"item_code": 1, "qty": 2},
{"item_code": 2, "qty": 2},
{"item_code": 5, "qty": 2},
{"item_code": 6, "qty": 2}
]
},
{"id": 2, "items": [
{"item_code": 3, "qty": 2},
{"item_code": 4, "qty": 2},
{"item_code": 7, "qty": 2},
{"item_code": 8, "qty": 2}
]
}
]
```
I tried with group\_by, which doesn't satisfy the output format. | 2018/07/27 | [
"https://Stackoverflow.com/questions/51558105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6166821/"
] | Firstly I map the ids, then for each id, I make a hash with two keys: the id and a flattened map of each entry's items:
```
result = array.group_by { |e| e[:id] }.map { |id, entries| {id: id, items: entries.flat_map { |entry| entry[:items] }} }
``` | You can combine `group_by` and `transform_values!` (for the latter you need Ruby 2.4.0 and later, otherwise you can use `each_with_object` as @Jagdeep pointed out)
```
array.group_by { |item| item[:id] }
.transform_values! { |v| v.flat_map { |subitem| subitem[:items] } }
.map { |(id, items)| Hash["id", id, "items", items] }
``` |
51,558,105 | I have an array consisting of hashes in the following form:
```
array = [
{"id": 1, "items": [{"item_code": 1, "qty": 2},{"item_code": 2, "qty": 2}]},
{"id": 2, "items": [{"item_code": 3, "qty": 2},{"item_code": 4, "qty": 2}]},
{"id": 1, "items": [{"item_code": 5, "qty": 2},{"item_code": 6, "qty": 2}]},
{"id": 2, "items": [{"item_code": 7, "qty": 2},{"item_code": 8, "qty": 2}]}
]
```
Do we have any convenient way to merge items according to ids:
Expected output:
```
array = [
{"id": 1, "items": [
{"item_code": 1, "qty": 2},
{"item_code": 2, "qty": 2},
{"item_code": 5, "qty": 2},
{"item_code": 6, "qty": 2}
]
},
{"id": 2, "items": [
{"item_code": 3, "qty": 2},
{"item_code": 4, "qty": 2},
{"item_code": 7, "qty": 2},
{"item_code": 8, "qty": 2}
]
}
]
```
I tried with group\_by, which doesn't satisfy the output format. | 2018/07/27 | [
"https://Stackoverflow.com/questions/51558105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6166821/"
] | There is no need for `group_by`. Go straight with `each_with_object` directly from the scratch.
```
array.
each_with_object({}) do |hash, acc|
acc[hash[:id]] ?
acc[hash[:id]][:items] |= hash[:items] :
acc[hash[:id]] = hash
end.values
#β [{:id=>1, :items=>[{:item_code=>1, :qty=>2},
# {:item_code=>2, :qty=>2},
# {:item_code=>5, :qty=>2},
# {:item_code=>6, :qty=>2}]},
# {:id=>2, :items=>[{:item_code=>3, :qty=>2},
# {:item_code=>4, :qty=>2},
# {:item_code=>7, :qty=>2},
# {:item_code=>8, :qty=>2}]}]
``` | ```
array.each_with_object({}) { |g,h| h.update(g[:id]=>g[:items]) { |_,o,n| o+n } }.
map { |k,v| { id: k, items: v } }
#=> [{:id=>1, :items=>[{:item_code=>1, :qty=>2}, {:item_code=>2, :qty=>2},
# {:item_code=>5, :qty=>2}, {:item_code=>6, :qty=>2}]},
# {:id=>2, :items=>[{:item_code=>3, :qty=>2}, {:item_code=>4, :qty=>2},
# {:item_code=>7, :qty=>2}, {:item_code=>8, :qty=>2}]}]
```
The first step is:
```
array.each_with_object({}) { |g,h| h.update(g[:id]=>g[:items]) { |_,o,n| o+n } }
#=> {1=>[{:item_code=>1, :qty=>2}, {:item_code=>2, :qty=>2},
# {:item_code=>5, :qty=>2}, {:item_code=>6, :qty=>2}],
# 2=>[{:item_code=>3, :qty=>2}, {:item_code=>4, :qty=>2},
# {:item_code=>7, :qty=>2}, {:item_code=>8, :qty=>2}]}
```
This makes use of the form of [Hash#update](http://ruby-doc.org/core-2.4.0/Hash.html#method-i-update) (a.k.a. `merge!`) that employs a block to determine the values of keys that are present in both hashes being merged. See the doc for the definitions of the three block variables.
Alternatively, one could write the following.
```
array.each_with_object({}) { |g,h| h.update(g[:id]=>g) { |_,o,n|
o.merge(n) { |k,oo,nn| k == :items ? oo+nn : oo } } }.values
``` |
51,558,105 | I have an array consisting of hashes in the following form:
```
array = [
{"id": 1, "items": [{"item_code": 1, "qty": 2},{"item_code": 2, "qty": 2}]},
{"id": 2, "items": [{"item_code": 3, "qty": 2},{"item_code": 4, "qty": 2}]},
{"id": 1, "items": [{"item_code": 5, "qty": 2},{"item_code": 6, "qty": 2}]},
{"id": 2, "items": [{"item_code": 7, "qty": 2},{"item_code": 8, "qty": 2}]}
]
```
Do we have any convenient way to merge items according to ids:
Expected output:
```
array = [
{"id": 1, "items": [
{"item_code": 1, "qty": 2},
{"item_code": 2, "qty": 2},
{"item_code": 5, "qty": 2},
{"item_code": 6, "qty": 2}
]
},
{"id": 2, "items": [
{"item_code": 3, "qty": 2},
{"item_code": 4, "qty": 2},
{"item_code": 7, "qty": 2},
{"item_code": 8, "qty": 2}
]
}
]
```
I tried with group\_by, which doesn't satisfy the output format. | 2018/07/27 | [
"https://Stackoverflow.com/questions/51558105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6166821/"
] | Firstly I map the ids, then for each id, I make a hash with two keys: the id and a flattened map of each entry's items:
```
result = array.group_by { |e| e[:id] }.map { |id, entries| {id: id, items: entries.flat_map { |entry| entry[:items] }} }
``` | ```
array.each_with_object({}) { |g,h| h.update(g[:id]=>g[:items]) { |_,o,n| o+n } }.
map { |k,v| { id: k, items: v } }
#=> [{:id=>1, :items=>[{:item_code=>1, :qty=>2}, {:item_code=>2, :qty=>2},
# {:item_code=>5, :qty=>2}, {:item_code=>6, :qty=>2}]},
# {:id=>2, :items=>[{:item_code=>3, :qty=>2}, {:item_code=>4, :qty=>2},
# {:item_code=>7, :qty=>2}, {:item_code=>8, :qty=>2}]}]
```
The first step is:
```
array.each_with_object({}) { |g,h| h.update(g[:id]=>g[:items]) { |_,o,n| o+n } }
#=> {1=>[{:item_code=>1, :qty=>2}, {:item_code=>2, :qty=>2},
# {:item_code=>5, :qty=>2}, {:item_code=>6, :qty=>2}],
# 2=>[{:item_code=>3, :qty=>2}, {:item_code=>4, :qty=>2},
# {:item_code=>7, :qty=>2}, {:item_code=>8, :qty=>2}]}
```
This makes use of the form of [Hash#update](http://ruby-doc.org/core-2.4.0/Hash.html#method-i-update) (a.k.a. `merge!`) that employs a block to determine the values of keys that are present in both hashes being merged. See the doc for the definitions of the three block variables.
Alternatively, one could write the following.
```
array.each_with_object({}) { |g,h| h.update(g[:id]=>g) { |_,o,n|
o.merge(n) { |k,oo,nn| k == :items ? oo+nn : oo } } }.values
``` |
70,805,143 | Trying to run Hybrid Configuration Wizard (HCW) - the part where it says "Installing Hybrid Agent", fails with error code 1603 ("Setup terminiated with an Exit Code 1603").
It seems like an installation issue since it appears to be MSI log that has the error in it (see image).
I imagine this could be TLS issue but I ran nartac tool with best practices AND also unchecked tls 1.0 and 1.1 manually. Not sure what to do now.
[](https://i.stack.imgur.com/Qksg0.png) | 2022/01/21 | [
"https://Stackoverflow.com/questions/70805143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6147663/"
] | For HCW to work properly with TLS 1.2, verify the SChannel and .NET Framework registry values are enabled.
Create a .REG file, copy the entire section below, then merge the file to update your entries.
---
>
> Windows Registry Editor Version 5.00
>
>
> [HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft.NETFramework\v2.0.50727]
> "SystemDefaultTlsVersions" = dword:00000001
> "SchUseStrongCrypto" = dword:00000001
>
>
> [HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft.NETFramework\v4.0.30319]
> "SystemDefaultTlsVersions" = dword:00000001
> "SchUseStrongCrypto" = dword:00000001
>
>
> [HKEY\_LOCAL\_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v2.0.50727]
> "SystemDefaultTlsVersions" = dword:00000001
> "SchUseStrongCrypto" = dword:00000001
>
>
> [HKEY\_LOCAL\_MACHINE\SOFTWARE\WOW6432Node\Microsoft.NETFramework\v4.0.30319]
> "SystemDefaultTlsVersions" = dword:00000001
> "SchUseStrongCrypto" = dword:00000001
>
>
> [HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
> 1.2]
>
>
> [HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
> 1.2\Client]
> "DisabledByDefault"=dword:00000000
> "Enabled"=dword:00000001
>
>
> [HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
> 1.2\Server]
> "DisabledByDefault"=dword:00000000
> "Enabled"=dword:00000001
>
>
> | I think the correct key names is "...\Microsoft\.NETFramework..." :-) |
69,735,726 | I am currently tasked to send realtime data that I stored in firestore to telegram. When I watch online tutorials, I mainly see people using realtime database to send data to telegram instead of firestore. I would like to know, is it possible to send data that is stored in firestore to telegram? | 2021/10/27 | [
"https://Stackoverflow.com/questions/69735726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17118274/"
] | There is nothing in the Firebase APIs that automatically sends data in Firestore to Telegram, but since both have Firestore and Telegram have APIs you can build this functionality yourself.
A common approach would be to create this as a Cloud Function, which is a piece of code that automatically gets triggered when you write to Firestore (in this case). In that Cloud Function you then take the data from Firestore and call the Telegram API. When I search for this, there are some promising results [here](https://www.google.com/search?q=cloud+functions+telegram). | So, yes you can do it. Here the simple example on Python language.
Look the all docs here: <https://firebase.google.com/docs/firestore/query-data/get-data> and
<https://firebase.google.com/docs/firestore/quickstart>
```
default_app = firebase_admin.initialize_app()
db = firestore.client()
users_ref = db.collection(u'users')
docs = users_ref.stream()
users=[]
for doc in docs:
doc = doc.to_dict()
a = f'{"Name:", doc.get("name")}'
users.append(a)
print(users)
```
Dont forge to create telegram bot and add code there) |
3,614,050 | It seems like the following scenario shouldn't be uncommon, but I can't figure out how to handle it in FluenNHibernate:
```
public class Product: BaseEntity
{
public Product()
{
Categories = new List<Category>();
}
public virtual IList<Category> Categories { get; set; }
...
}
public enum Categories
{
Classic = 1,
Modern = 2,
Trendy = 3,
...
}
```
So, I need a ProductCategories table that allows me to map one product to many categories, but I don't think NHibernate will handle this unless I have an actual Categories class and a Categories table with a many-to-many relationship specified. There are a number of reasons this is not desirable, not the least of which is that it's overkill.
I'm using AutoMapper - any way I can override to make this work?
Thanks! | 2010/08/31 | [
"https://Stackoverflow.com/questions/3614050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205856/"
] | I had tried the concatenated string in another instance like this, but I really wanted something that didn't need to be transformed every time. As it turns out, I found a very similar question here: [Map to a list of Enums?](https://stackoverflow.com/questions/1423927/map-to-a-list-of-enums). As described there, this override works:
```
public void Override(AutoMapping<Product> mapping)
{
mapping.HasMany(x => x.Categories).KeyColumn("ProductFk").Table("CategoriesProductsMap").Element("Category").AsBag();
}
``` | There are a few ways to do this, none of them as straightforward as you might expect. While NHibernate and Fluent NHibernate do quite well with a single `enum`, a collection is significantly more troublesom.
Here are a couple of approaches:
1. Persist the collection to a single `nvarchar(?)` column by concatenating the members.
2. Mark the `enum` with the `Flags` attribute and collapse the list as a bitmask (this will require just one integer column)
In either case, you can have NHibernate access a field that contains the "collapsed" values; the getters of the public properties will transform the collapsed values to collections. The getter of the collapsed value will transform the collection into a single string (1) or integer (2).
You'd have to map `Product` explicitly:
```
public class ProductMap : ClassMap<Product>
{
public ProductMap()
{
Id(x => x.Id);
Map(Reveal.Member<Product>("_categories"))
.Access.Field();
}
}
```
So although `Product` exposes an `IList<Category>`, NHibernate will only get and set the value of the `_categories` field; |
3,614,050 | It seems like the following scenario shouldn't be uncommon, but I can't figure out how to handle it in FluenNHibernate:
```
public class Product: BaseEntity
{
public Product()
{
Categories = new List<Category>();
}
public virtual IList<Category> Categories { get; set; }
...
}
public enum Categories
{
Classic = 1,
Modern = 2,
Trendy = 3,
...
}
```
So, I need a ProductCategories table that allows me to map one product to many categories, but I don't think NHibernate will handle this unless I have an actual Categories class and a Categories table with a many-to-many relationship specified. There are a number of reasons this is not desirable, not the least of which is that it's overkill.
I'm using AutoMapper - any way I can override to make this work?
Thanks! | 2010/08/31 | [
"https://Stackoverflow.com/questions/3614050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205856/"
] | [This accepted answer](https://stackoverflow.com/questions/3614050/fluentnhibernate-how-to-handle-one-to-many-values-when-the-many-is-a-simple-enum/3622023#3622023) worked for me, however the enum was mapped as in int.
To get it to map as a string (my preference) I adapted the mapping as follows:
```
public void Override(AutoMapping<Account> mapping)
{
mapping
.HasMany(x => x.Categories)
.Table("CategoriesProductsMap")
.Element("Category", e => e.Type<NHibernate.Type.EnumStringType<Category>>())
.AsSet();
}
``` | There are a few ways to do this, none of them as straightforward as you might expect. While NHibernate and Fluent NHibernate do quite well with a single `enum`, a collection is significantly more troublesom.
Here are a couple of approaches:
1. Persist the collection to a single `nvarchar(?)` column by concatenating the members.
2. Mark the `enum` with the `Flags` attribute and collapse the list as a bitmask (this will require just one integer column)
In either case, you can have NHibernate access a field that contains the "collapsed" values; the getters of the public properties will transform the collapsed values to collections. The getter of the collapsed value will transform the collection into a single string (1) or integer (2).
You'd have to map `Product` explicitly:
```
public class ProductMap : ClassMap<Product>
{
public ProductMap()
{
Id(x => x.Id);
Map(Reveal.Member<Product>("_categories"))
.Access.Field();
}
}
```
So although `Product` exposes an `IList<Category>`, NHibernate will only get and set the value of the `_categories` field; |
3,614,050 | It seems like the following scenario shouldn't be uncommon, but I can't figure out how to handle it in FluenNHibernate:
```
public class Product: BaseEntity
{
public Product()
{
Categories = new List<Category>();
}
public virtual IList<Category> Categories { get; set; }
...
}
public enum Categories
{
Classic = 1,
Modern = 2,
Trendy = 3,
...
}
```
So, I need a ProductCategories table that allows me to map one product to many categories, but I don't think NHibernate will handle this unless I have an actual Categories class and a Categories table with a many-to-many relationship specified. There are a number of reasons this is not desirable, not the least of which is that it's overkill.
I'm using AutoMapper - any way I can override to make this work?
Thanks! | 2010/08/31 | [
"https://Stackoverflow.com/questions/3614050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205856/"
] | I had tried the concatenated string in another instance like this, but I really wanted something that didn't need to be transformed every time. As it turns out, I found a very similar question here: [Map to a list of Enums?](https://stackoverflow.com/questions/1423927/map-to-a-list-of-enums). As described there, this override works:
```
public void Override(AutoMapping<Product> mapping)
{
mapping.HasMany(x => x.Categories).KeyColumn("ProductFk").Table("CategoriesProductsMap").Element("Category").AsBag();
}
``` | At work, while it did not concern a collection of enum value, we created a custom type (by implementing `IUserType` to store a `IDictionary<CultureInfo, string>`.
We converted the dictionary into a xml document (XDocument) and we stored the data in an Xml column in Sql Server, although any string column could store the value.
You can see [this site](http://intellect.dk/post/Implementing-custom-types-in-nHibernate.aspx) for information about implementing `IUserType`. |
3,614,050 | It seems like the following scenario shouldn't be uncommon, but I can't figure out how to handle it in FluenNHibernate:
```
public class Product: BaseEntity
{
public Product()
{
Categories = new List<Category>();
}
public virtual IList<Category> Categories { get; set; }
...
}
public enum Categories
{
Classic = 1,
Modern = 2,
Trendy = 3,
...
}
```
So, I need a ProductCategories table that allows me to map one product to many categories, but I don't think NHibernate will handle this unless I have an actual Categories class and a Categories table with a many-to-many relationship specified. There are a number of reasons this is not desirable, not the least of which is that it's overkill.
I'm using AutoMapper - any way I can override to make this work?
Thanks! | 2010/08/31 | [
"https://Stackoverflow.com/questions/3614050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205856/"
] | [This accepted answer](https://stackoverflow.com/questions/3614050/fluentnhibernate-how-to-handle-one-to-many-values-when-the-many-is-a-simple-enum/3622023#3622023) worked for me, however the enum was mapped as in int.
To get it to map as a string (my preference) I adapted the mapping as follows:
```
public void Override(AutoMapping<Account> mapping)
{
mapping
.HasMany(x => x.Categories)
.Table("CategoriesProductsMap")
.Element("Category", e => e.Type<NHibernate.Type.EnumStringType<Category>>())
.AsSet();
}
``` | At work, while it did not concern a collection of enum value, we created a custom type (by implementing `IUserType` to store a `IDictionary<CultureInfo, string>`.
We converted the dictionary into a xml document (XDocument) and we stored the data in an Xml column in Sql Server, although any string column could store the value.
You can see [this site](http://intellect.dk/post/Implementing-custom-types-in-nHibernate.aspx) for information about implementing `IUserType`. |
24,527,478 | I have a `UIView` defined in a .xib file. I need to set `translatesAutoresizingMaskIntoConstraints = NO`. This means that the frame is not translated to constraints so I need to set the size constraints by myself.
I have created a working category method for a `UIView`:
```
-(NSArray*)setSizeConstraints:(CGSize)size
{
NSLayoutConstraint* height = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:size.height];
NSLayoutConstraint* width = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:size.width];
[self addConstraint:height];
[self addConstraint:width];
return [NSArray arrayWithObjects:height, width, nil];
}
```
But I would like to set these constraints from the Xcode interface builder, but all my AutoLayout controls are greyed out:

Is there a way to do this in the interface builder? | 2014/07/02 | [
"https://Stackoverflow.com/questions/24527478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1118969/"
] | This actually is possible.
--------------------------
Simply put the view you'd like to constrain into another view, like the highlighted view here.
[](https://i.stack.imgur.com/PPoyc.png)
Then, add your desired constraints.
Finally, pull the view you just added constraints to **out** of its parent view. You can now add constraints to that view.
[](https://i.stack.imgur.com/zMuy1.png) | As you've surely found out by now, it looks like there's currently no way to set Autolayout constraints at the main `UIView` level from Interface Builder.
I had a similar problem here ([Launch Screen XIB: Missing Width / Height Constraints (Xcode 6)](https://stackoverflow.com/questions/28219842/launch-screen-xib-missing-width-height-constraints)), while working with the launch screen of my app.
The only workarounds I found, if you want to keep working with IB, are:
* Using a `UIViewController` and its `UIView` inside the XIB, instead of just a `UIView`
* Working only with Storyboards (and, once again, `UIViewController`)
However, I understand these approaches may not be ideal or "clean", especially if you simply have a subclass of `UIView` and you want to draw its interface in a good old XIB. |
17,509,479 | I am writing a simple program which takes the arguments form the user and process them.
I have the arguments in the argv which is two dimensional array. But when i ran the program, i get the garbage value and the segmentation fault error. I have tried with using argc as terminating condition and it works. But i want to do it using the pointer only.
What am doing wrong with pointer here.
```
#include<stdio.h>
int main( int argc, char *argv[])
{
while (++(*argv))
{
if ( **argv == '-' )
{
switch (*argv[1])
{
default:
printf("Unknown option -%c\n\n", (*argv)[1]);
break;
case 'h':
printf("\n option h is found");
break;
case 'v':
printf("option V is found");
break;
case 'd':
printf("\n option d is found");
break;
}
}
printf("\n outside while : %s", *argv);
}
}
```
program run as:
```
./a.out -h -v -d
```
Thank you | 2013/07/07 | [
"https://Stackoverflow.com/questions/17509479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1930329/"
] | * If you want to iterate through program arguments looking for the terminating null pointer, your outer cycle should be
```
while (*++argv)
```
not the
```
while (++*argv) // <- incorrect!
```
that you have in your code.
* Your `switch` expression is written incorrectly. While your intent is clear, your implementation ignores operator precedence.
This
```
switch (*argv[1]) { // <- incorrect!
```
should actually be
```
switch ((*argv)[1]) {
```
* The previous `if`
```
if (**argv == '-')
```
is fine, but since it is equivalent to
```
if ((*argv)[0] == '-') // <- better
```
maybe you should rewrite it that way as well, just for consistency with `switch`. | Your ultimate problem is operator precedence. Don't try to be clever when it's unnecessary. The `*` operator does not work as you think it does. I've rewritten your code using `[0]` instead, and now it works:
```
#include <stdio.h>
int main(int argc, char *argv[])
{
while ((++argv)[0])
{
if (argv[0][0] == '-' )
{
switch (argv[0][1]) {
default:
printf("Unknown option -%c\n\n", argv[0][1]);
break;
case 'h':
printf("\n option h is found");
break;
case 'v':
printf("option V is found");
break;
case 'd':
printf("\n option d is found");
break;
}
}
printf("\n outside while : %s", argv[0]);
}
}
``` |
17,509,479 | I am writing a simple program which takes the arguments form the user and process them.
I have the arguments in the argv which is two dimensional array. But when i ran the program, i get the garbage value and the segmentation fault error. I have tried with using argc as terminating condition and it works. But i want to do it using the pointer only.
What am doing wrong with pointer here.
```
#include<stdio.h>
int main( int argc, char *argv[])
{
while (++(*argv))
{
if ( **argv == '-' )
{
switch (*argv[1])
{
default:
printf("Unknown option -%c\n\n", (*argv)[1]);
break;
case 'h':
printf("\n option h is found");
break;
case 'v':
printf("option V is found");
break;
case 'd':
printf("\n option d is found");
break;
}
}
printf("\n outside while : %s", *argv);
}
}
```
program run as:
```
./a.out -h -v -d
```
Thank you | 2013/07/07 | [
"https://Stackoverflow.com/questions/17509479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1930329/"
] | * If you want to iterate through program arguments looking for the terminating null pointer, your outer cycle should be
```
while (*++argv)
```
not the
```
while (++*argv) // <- incorrect!
```
that you have in your code.
* Your `switch` expression is written incorrectly. While your intent is clear, your implementation ignores operator precedence.
This
```
switch (*argv[1]) { // <- incorrect!
```
should actually be
```
switch ((*argv)[1]) {
```
* The previous `if`
```
if (**argv == '-')
```
is fine, but since it is equivalent to
```
if ((*argv)[0] == '-') // <- better
```
maybe you should rewrite it that way as well, just for consistency with `switch`. | `argv` is an array of strings. `argv[0]` is the program name which in your case is `a.out`. Your options start from `argv[1]`. So you need to iterate `argv` from 1 to `argc-1` to get the options.
Also see here: [Parsing Program Arguments](http://www.gnu.org/software/libc/manual/html_node/Parsing-Program-Arguments.html) |
17,509,479 | I am writing a simple program which takes the arguments form the user and process them.
I have the arguments in the argv which is two dimensional array. But when i ran the program, i get the garbage value and the segmentation fault error. I have tried with using argc as terminating condition and it works. But i want to do it using the pointer only.
What am doing wrong with pointer here.
```
#include<stdio.h>
int main( int argc, char *argv[])
{
while (++(*argv))
{
if ( **argv == '-' )
{
switch (*argv[1])
{
default:
printf("Unknown option -%c\n\n", (*argv)[1]);
break;
case 'h':
printf("\n option h is found");
break;
case 'v':
printf("option V is found");
break;
case 'd':
printf("\n option d is found");
break;
}
}
printf("\n outside while : %s", *argv);
}
}
```
program run as:
```
./a.out -h -v -d
```
Thank you | 2013/07/07 | [
"https://Stackoverflow.com/questions/17509479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1930329/"
] | Your ultimate problem is operator precedence. Don't try to be clever when it's unnecessary. The `*` operator does not work as you think it does. I've rewritten your code using `[0]` instead, and now it works:
```
#include <stdio.h>
int main(int argc, char *argv[])
{
while ((++argv)[0])
{
if (argv[0][0] == '-' )
{
switch (argv[0][1]) {
default:
printf("Unknown option -%c\n\n", argv[0][1]);
break;
case 'h':
printf("\n option h is found");
break;
case 'v':
printf("option V is found");
break;
case 'd':
printf("\n option d is found");
break;
}
}
printf("\n outside while : %s", argv[0]);
}
}
``` | `argv` is an array of strings. `argv[0]` is the program name which in your case is `a.out`. Your options start from `argv[1]`. So you need to iterate `argv` from 1 to `argc-1` to get the options.
Also see here: [Parsing Program Arguments](http://www.gnu.org/software/libc/manual/html_node/Parsing-Program-Arguments.html) |
24,609,357 | This is my code for generating random numbers from 1-99, but it's only generating same set of numbers (15 numbers) every time. I'm storing those numbers in an `NSArray` and getting output in `NSLog` properly. It's ok, but I want different set of random numbers with no repeated number whenever I call this random method. Can any one help me please?
```
-(void) randoms
{
myset=[[NSArray alloc]init];
int D[20];
BOOL flag;
for (int i=0; i<15; i++)
{
int randum= random()%100;
flag= true;
int size= (sizeof D);
for (int x=0; x<size; x++)
{
if (randum == D[x])
{
i--;
flag= false;
break;
}
}
if (flag) D[i]=randum;
}
for (int j=0; j<15; j++)
{
myset=[myset arrayByAddingObject:[NSNumber numberWithInt:D[j]]];
}
NSLog(@"first set..%@",myset.description);
}
``` | 2014/07/07 | [
"https://Stackoverflow.com/questions/24609357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208986/"
] | You have to seed the generator before using it. If you want to skip the seeding, you can use **arc4random\_uniform()**. It's a different algorithm and takes care of the seeding process on its own. Other than that, you can use it in your code almost exactly like you used **random()**. You'll just have to specify the upper bound as a parameter, instead of using modulo:
```
-(void) randoms
{
myset=[[NSArray alloc]init];
int D[20];
BOOL flag;
for (int i=0; i<15; i++)
{
int randum= arc4random_uniform(100);
flag= true;
int size= (sizeof D);
for (int x=0; x<size; x++)
{
if (randum == D[x])
{
i--;
flag= false;
break;
}
}
if (flag) D[i]=randum;
}
for (int j=0; j<15; j++)
{
myset=[myset arrayByAddingObject:[NSNumber numberWithInt:D[j]]];
}
NSLog(@"first set..%@",myset.description);
}
``` | Try this command before starting your arc4random
```
srand(time(NULL));
``` |
24,609,357 | This is my code for generating random numbers from 1-99, but it's only generating same set of numbers (15 numbers) every time. I'm storing those numbers in an `NSArray` and getting output in `NSLog` properly. It's ok, but I want different set of random numbers with no repeated number whenever I call this random method. Can any one help me please?
```
-(void) randoms
{
myset=[[NSArray alloc]init];
int D[20];
BOOL flag;
for (int i=0; i<15; i++)
{
int randum= random()%100;
flag= true;
int size= (sizeof D);
for (int x=0; x<size; x++)
{
if (randum == D[x])
{
i--;
flag= false;
break;
}
}
if (flag) D[i]=randum;
}
for (int j=0; j<15; j++)
{
myset=[myset arrayByAddingObject:[NSNumber numberWithInt:D[j]]];
}
NSLog(@"first set..%@",myset.description);
}
``` | 2014/07/07 | [
"https://Stackoverflow.com/questions/24609357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208986/"
] | You have to seed the generator before using it. If you want to skip the seeding, you can use **arc4random\_uniform()**. It's a different algorithm and takes care of the seeding process on its own. Other than that, you can use it in your code almost exactly like you used **random()**. You'll just have to specify the upper bound as a parameter, instead of using modulo:
```
-(void) randoms
{
myset=[[NSArray alloc]init];
int D[20];
BOOL flag;
for (int i=0; i<15; i++)
{
int randum= arc4random_uniform(100);
flag= true;
int size= (sizeof D);
for (int x=0; x<size; x++)
{
if (randum == D[x])
{
i--;
flag= false;
break;
}
}
if (flag) D[i]=randum;
}
for (int j=0; j<15; j++)
{
myset=[myset arrayByAddingObject:[NSNumber numberWithInt:D[j]]];
}
NSLog(@"first set..%@",myset.description);
}
``` | If I understand you correctly you want a set containing 15 random numbers between 1-99. You can use the following:
```
- (NSSet *)randomSetOfSize:(int)size lowerBound:(int)lowerBound upperBound:(int)upperBound {
NSMutableSet *randomSet=[NSMutableSet new];
while (randomSet.count <size) {
int randomInt=arc4random_uniform(upperBound-lowerBound)+lowerBound;
NSNumber *randomNumber=[NSNumber numberWithInt:randomInt];
[randomSet addObject:randomNumber];
}
return randomSet;
}
```
and call it with
```
NSSet *myRandomSet=[self randomSetOfSize:14 lowerBound:1 upperBound:99];
``` |
32,261,091 | I have a static image which will expire in 9 minutes.
It has following headers set by the server:
Cache-control: max0age=523
Expires: Thu, 27 Aug 2015 23:28:14 GMT (in 5 minutes)
Last-Modified:Wed, 12 Nov 2014 08:06:06 GMT
When I refresh the page browser makes request to server instead of serving it from the cache. As expected it gets 304 from server.
Screenshot from Chrome dev tools below:
[](https://i.stack.imgur.com/dyf4y.png)
I compared it with resource cached with same headers (max-age and last-modified) and seeing that content gets served directly from cache:
[](https://i.stack.imgur.com/CE83V.png)
So basically I have two questions:
1. Why Chrome does not serve image from cache and validates it against server?
2. Why same not applies to my second example with js file from Bing.com and it served directly from cache? Is it because "public" specified in cache-control or aggressive expiration date?
Some clarifications:
1. I'm refreshing the page in both examples.
2. I am not doing hard refresh (Crtl+R or Ctrl+F5).
3. It is not because of dev tools opened, I tried to close dev tools and I'm seeing same in Fiddler. | 2015/08/27 | [
"https://Stackoverflow.com/questions/32261091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250849/"
] | Referencing an answer from here: [puma initializer does not work with rails 4.2](https://stackoverflow.com/questions/32259490/puma-initializer-does-not-work-with-rails-4-2)
Put the `puma.rb` file in `config/` not `config/initializers/` | you need to use foreman <https://github.com/ddollar/foreman> to run the `Procfile`. That is how heroku will spool up the app. once installed `foreman start` should do the trick. this just fooled me for a bit and I ran across your question. |
68,146,769 | So I've been struggling with the following problem for a while. I achieved this (John's example):
[](https://i.stack.imgur.com/EnvfU.png)
But what I'm trying to do is to force the hour to **always** be shown directly after the text, and if the text is too long - overflow the text. So Jane Doe's example is perfect, same as Jack Doe's (but in Jack's case **that's all a dummy text**).
And I can't really figure out what I'm doing wrong.
That's the piece of code I wrote:
```
Row(modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 7.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
// there's another Row printing the name
}
Spacer(Modifier.height(5.dp))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start) {
Row(modifier = Modifier.wrapContentWidth(), horizontalArrangement = Arrangement.Start) {
Text(
text = item.message,
style = MaterialTheme.typography.subtitle1,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start) {
Circle() // that's my function which just shows the circle
Text(
text = dateString,
style = MaterialTheme.typography.subtitle1,
maxLines = 1,
modifier = Modifier.padding(horizontal = 4.dp)
)
}
}
}
}
```
I'll be really grateful for any kind of help. | 2021/06/26 | [
"https://Stackoverflow.com/questions/68146769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13505425/"
] | Something like this?
```kotlin
@Preview(showBackground = true)
@Composable
fun Test() {
Column {
Message(message = "short message")
Message(message = "short")
Message(message = "very long message")
}
}
@Composable
fun Message(message: String) {
Text("John Doe")
Row(horizontalArrangement = Arrangement.SpaceBetween) {
Text(
message,
modifier = Modifier.weight(1F, fill = false),
overflow = TextOverflow.Ellipsis,
maxLines = 1,
)
Text("8:35PM")
}
}
```
[](https://i.stack.imgur.com/QuNAN.png) | You can achieve this with a `Layout` and using `IntrinsicWidth`. You can build on this example as it only uses 2 `Text`s for the children, but this should get you on the right path.
```
@Composable
fun MyRow(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Layout(
content = content,
modifier = modifier,
) { measurables, constraints ->
check(measurables.size == 2) { "This composable requires 2 children" }
val first = measurables.first()
val second = measurables[1]
val looseConstraints = constraints.copy(
minWidth = 0,
minHeight = 0,
)
val secondMeasurable = second.measure(looseConstraints)
val maxHeight = secondMeasurable.height
val availableWidth = constraints.maxWidth - secondMeasurable.width
val maxWidth = first.maxIntrinsicWidth(maxHeight).coerceAtMost(availableWidth)
val firstMeasurable = first.measure(
Constraints(
minWidth = maxWidth,
maxWidth = maxWidth,
minHeight = 0,
maxHeight = maxHeight
)
)
layout(
constraints.maxWidth,
maxHeight,
) {
firstMeasurable.place(0, 0)
secondMeasurable.place(maxWidth, 0)
}
}
}
@Composable
@Preview
fun MyRowPreview() {
SampleTheme {
Surface(modifier = Modifier.width(320.dp)) {
Column(modifier = Modifier.fillMaxWidth()) {
Text(
text = "John Doe",
style = MaterialTheme.typography.h5,
)
MyRow(modifier = Modifier.fillMaxWidth()) {
Text(
text = "Short Label",
style = MaterialTheme.typography.body1,
modifier = Modifier.padding(end = 8.dp),
overflow = TextOverflow.Ellipsis,
maxLines = 1,
)
Text(
text = "8:35 PM",
style = MaterialTheme.typography.body1,
modifier = Modifier.padding(start = 8.dp),
)
}
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "John Doe",
style = MaterialTheme.typography.h5,
)
MyRow(modifier = Modifier.fillMaxWidth()) {
Text(
text = "A long label that will require truncation goes here",
style = MaterialTheme.typography.body1,
modifier = Modifier.padding(end = 8.dp),
overflow = TextOverflow.Ellipsis,
maxLines = 1,
)
Text(
text = "8:35 PM",
style = MaterialTheme.typography.body1,
modifier = Modifier.padding(start = 8.dp),
)
}
}
}
}
}
```
[](https://i.stack.imgur.com/OB8sB.png) |
22,988,271 | I am getting error when I try to connect database
**Error:com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to
Ptakip.Connection**
* Ptakip is my Package
* Connection is my Class
Here is the Connection Class Code ;
```
import java.sql.*;
public class Connection {
private Connection cn;
public Connection connector( )
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost\\MyServer:
1433;databaseName=TEST;user=Glassfish;password=pass;");
System.out.println("connected");
}
catch(Exception ex) {
System.out.println("Error:" + ex.getMessage());
System.out.println(cn);
}
return cn;
}
}
``` | 2014/04/10 | [
"https://Stackoverflow.com/questions/22988271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3498019/"
] | I'm not sure I completely understand, but I will try to give you some information. Like David said It may seem that the first request is the last one responding, but that will vary under many circumstances. There are different ways you could do this to control the outcome or order of the requests.
1) Upon success of the first request you could initiate the second request. I don't recommend this for speed purposes as your requests aren't running in parallel.
```
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
// $("#duplicate").html(returnhtml);
// $("#loadingimg").hide();
alert("b");
}
});
alert ("a");
// $("#result").html(returnhtml);
// $("#loadingimg").hide();
}
});
```
2) If you need to have both requests responses at the same time, the preferred method would likely be jQuery deferred. This will make both requests run in parallel, and once both responses are received you can proceed as you would have.
Something Like this:
```
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
});
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
});
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
```
Check out:
<https://api.jquery.com/jQuery.when/>
<http://api.jquery.com/deferred.then/>
<https://api.jquery.com/deferred.done/>
I hope this helps! | ```
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
});
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
});
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
``` |
22,988,271 | I am getting error when I try to connect database
**Error:com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to
Ptakip.Connection**
* Ptakip is my Package
* Connection is my Class
Here is the Connection Class Code ;
```
import java.sql.*;
public class Connection {
private Connection cn;
public Connection connector( )
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost\\MyServer:
1433;databaseName=TEST;user=Glassfish;password=pass;");
System.out.println("connected");
}
catch(Exception ex) {
System.out.println("Error:" + ex.getMessage());
System.out.println(cn);
}
return cn;
}
}
``` | 2014/04/10 | [
"https://Stackoverflow.com/questions/22988271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3498019/"
] | Gaurav, you have an error, at the end of the 1st $.ajax it must end as `),` and 2nd as `)`.
You can't end with `;`
```js
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
}),
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
})
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
``` | I'm not sure I completely understand, but I will try to give you some information. Like David said It may seem that the first request is the last one responding, but that will vary under many circumstances. There are different ways you could do this to control the outcome or order of the requests.
1) Upon success of the first request you could initiate the second request. I don't recommend this for speed purposes as your requests aren't running in parallel.
```
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
// $("#duplicate").html(returnhtml);
// $("#loadingimg").hide();
alert("b");
}
});
alert ("a");
// $("#result").html(returnhtml);
// $("#loadingimg").hide();
}
});
```
2) If you need to have both requests responses at the same time, the preferred method would likely be jQuery deferred. This will make both requests run in parallel, and once both responses are received you can proceed as you would have.
Something Like this:
```
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
});
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
});
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
```
Check out:
<https://api.jquery.com/jQuery.when/>
<http://api.jquery.com/deferred.then/>
<https://api.jquery.com/deferred.done/>
I hope this helps! |
22,988,271 | I am getting error when I try to connect database
**Error:com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to
Ptakip.Connection**
* Ptakip is my Package
* Connection is my Class
Here is the Connection Class Code ;
```
import java.sql.*;
public class Connection {
private Connection cn;
public Connection connector( )
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost\\MyServer:
1433;databaseName=TEST;user=Glassfish;password=pass;");
System.out.println("connected");
}
catch(Exception ex) {
System.out.println("Error:" + ex.getMessage());
System.out.println(cn);
}
return cn;
}
}
``` | 2014/04/10 | [
"https://Stackoverflow.com/questions/22988271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3498019/"
] | I'm not sure I completely understand, but I will try to give you some information. Like David said It may seem that the first request is the last one responding, but that will vary under many circumstances. There are different ways you could do this to control the outcome or order of the requests.
1) Upon success of the first request you could initiate the second request. I don't recommend this for speed purposes as your requests aren't running in parallel.
```
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
// $("#duplicate").html(returnhtml);
// $("#loadingimg").hide();
alert("b");
}
});
alert ("a");
// $("#result").html(returnhtml);
// $("#loadingimg").hide();
}
});
```
2) If you need to have both requests responses at the same time, the preferred method would likely be jQuery deferred. This will make both requests run in parallel, and once both responses are received you can proceed as you would have.
Something Like this:
```
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
});
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
});
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
```
Check out:
<https://api.jquery.com/jQuery.when/>
<http://api.jquery.com/deferred.then/>
<https://api.jquery.com/deferred.done/>
I hope this helps! | Or use `server_response` in your code. The script begin with condition:
```
if (recherche1.length>1) {
$.ajax({ // First Request
type :"GET",
url : "result.php",
data: data,
cache: false,
success: function(server_response){
$('.price1').html(server_response).show();
}
}),
$.ajax({ //Seconds Request
type :"GET",
url : "result2.php",
data: data,
cache: false,
success: function(server_response){
$('.price2').html(server_response).show();
}
});
}
``` |
22,988,271 | I am getting error when I try to connect database
**Error:com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to
Ptakip.Connection**
* Ptakip is my Package
* Connection is my Class
Here is the Connection Class Code ;
```
import java.sql.*;
public class Connection {
private Connection cn;
public Connection connector( )
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost\\MyServer:
1433;databaseName=TEST;user=Glassfish;password=pass;");
System.out.println("connected");
}
catch(Exception ex) {
System.out.println("Error:" + ex.getMessage());
System.out.println(cn);
}
return cn;
}
}
``` | 2014/04/10 | [
"https://Stackoverflow.com/questions/22988271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3498019/"
] | Gaurav, you have an error, at the end of the 1st $.ajax it must end as `),` and 2nd as `)`.
You can't end with `;`
```js
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
}),
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
})
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
``` | ```
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
});
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
});
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
``` |
22,988,271 | I am getting error when I try to connect database
**Error:com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to
Ptakip.Connection**
* Ptakip is my Package
* Connection is my Class
Here is the Connection Class Code ;
```
import java.sql.*;
public class Connection {
private Connection cn;
public Connection connector( )
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost\\MyServer:
1433;databaseName=TEST;user=Glassfish;password=pass;");
System.out.println("connected");
}
catch(Exception ex) {
System.out.println("Error:" + ex.getMessage());
System.out.println(cn);
}
return cn;
}
}
``` | 2014/04/10 | [
"https://Stackoverflow.com/questions/22988271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3498019/"
] | Or use `server_response` in your code. The script begin with condition:
```
if (recherche1.length>1) {
$.ajax({ // First Request
type :"GET",
url : "result.php",
data: data,
cache: false,
success: function(server_response){
$('.price1').html(server_response).show();
}
}),
$.ajax({ //Seconds Request
type :"GET",
url : "result2.php",
data: data,
cache: false,
success: function(server_response){
$('.price2').html(server_response).show();
}
});
}
``` | ```
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
});
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
});
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
``` |
22,988,271 | I am getting error when I try to connect database
**Error:com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to
Ptakip.Connection**
* Ptakip is my Package
* Connection is my Class
Here is the Connection Class Code ;
```
import java.sql.*;
public class Connection {
private Connection cn;
public Connection connector( )
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost\\MyServer:
1433;databaseName=TEST;user=Glassfish;password=pass;");
System.out.println("connected");
}
catch(Exception ex) {
System.out.println("Error:" + ex.getMessage());
System.out.println(cn);
}
return cn;
}
}
``` | 2014/04/10 | [
"https://Stackoverflow.com/questions/22988271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3498019/"
] | Gaurav, you have an error, at the end of the 1st $.ajax it must end as `),` and 2nd as `)`.
You can't end with `;`
```js
var result1;
var result2;
$.when(
$.ajax({ // First Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result1 = returnhtml;
}
}),
$.ajax({ //Seconds Request
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
result2 = returnhtml;
}
})
).then(function() {
$('#result1').html(result1);
$('#result2').html(result2);
});
``` | Or use `server_response` in your code. The script begin with condition:
```
if (recherche1.length>1) {
$.ajax({ // First Request
type :"GET",
url : "result.php",
data: data,
cache: false,
success: function(server_response){
$('.price1').html(server_response).show();
}
}),
$.ajax({ //Seconds Request
type :"GET",
url : "result2.php",
data: data,
cache: false,
success: function(server_response){
$('.price2').html(server_response).show();
}
});
}
``` |
30,766,766 | GitHub repo: <https://github.com/Yorkshireman/mywordlist>
I've googled the hell out of this one. I'm sure there's a way, possibly requiring some code inside a html options hash, but I can't work it out. Any ideas?
When visiting the \_edit\_word\_form.html.erb partial for a Word that DOES have one or more categories, the Categories checkboxes are all unchecked, requiring the user to select them again, even if they don't want to change the Categories.
The text fields for the :title and :description ARE pre-populated (thankfully).
\_edit\_word\_form.html.erb:
```
<%= form_for(@word) do %>
<%= fields_for :word, @word do |word_form| %>
<div class="field form-group">
<%= word_form.label(:title, "Word:") %><br>
<%= word_form.text_field(:title, id: "new_word", required: true, autofocus: true, class: "form-control") %>
</div>
<div class="field form-group">
<%= word_form.label(:description, "Definition:") %><br>
<%= word_form.text_area(:description, class: "form-control") %>
</div>
<% end %>
<%= fields_for :category, @category do |category_form| %>
<% if current_user.word_list.categories.count > 0 %>
<div class="field form-group">
<%= category_form.label(:title, "Choose from existing Categories:") %><br>
<%= category_form.collection_check_boxes(:category_ids, current_user.word_list.categories.all, :id, :title) do |b| %>
<%= b.label(class: "checkbox-inline") { b.check_box + b.text } %>
<% end %>
</div>
<% end %>
<h4>AND/OR...</h4>
<div class="field form-group">
<%= category_form.label(:title, "Create and Use a New Category:") %><br>
<%= category_form.text_field(:title, class: "form-control") %>
</div>
<% end %>
<div class="actions">
<%= submit_tag("Update!", class: "btn btn-block btn-primary btn-lg") %>
</div>
<% end %>
```
Relevant part of the words/index.html.erb:
```
<% current_user.word_list.words.alphabetical_order_asc.each do |word| %>
<tr>
<td>
<%= link_to edit_word_path(word) do %>
<%= word.title %>
<span class="glyphicon glyphicon-pencil"></span>
<% end %>
</td>
<td><%= word.description %></td>
<td>
<% word.categories.alphabetical_order_asc.each do |category| %>
<a class="btn btn-info btn-sm", role="button">
<%= category.title %>
</a>
<% end %>
</td>
<td>
<%= link_to word, method: :delete, data: { confirm: 'Are you sure?' } do %>
<span class="glyphicon glyphicon-remove"></span>
<% end %>
</td>
</tr>
<% end %>
```
words\_controller.rb:
```
class WordsController < ApplicationController
before_action :set_word, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# GET /words
# GET /words.json
def index
@words = Word.all
@quotes = Quote.all
end
# GET /words/1
# GET /words/1.json
def show
end
# GET /words/new
def new
@word = current_user.word_list.words.build
end
# GET /words/1/edit
def edit
end
# POST /words
# POST /words.json
def create
@word = Word.new(word_params)
respond_to do |format|
if @word.save
format.html { redirect_to @word, notice: 'Word was successfully created.' }
format.json { render :show, status: :created, location: @word }
else
format.html { render :new }
format.json { render json: @word.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /words/1
# PATCH/PUT /words/1.json
def update
#need to first remove categories from the word
@word.categories.each do |category|
@word.categories.delete category
end
#then push categories in from the category_params
if params["category"].include?(:category_ids)
(params["category"])["category_ids"].each do |i|
next if i.to_i == 0
@word.categories << Category.find(i.to_i) unless @word.categories.include?(Category.find(i.to_i))
end
end
if category_params.include?(:title) && ((params["category"])["title"]) != ""
@word.categories << current_user.word_list.categories.build(title: (params["category"])["title"])
end
respond_to do |format|
if @word.update(word_params)
format.html { redirect_to words_path, notice: 'Word was successfully updated.' }
format.json { render :show, status: :ok, location: @word }
else
format.html { render :edit }
format.json { render json: @word.errors, status: :unprocessable_entity }
end
end
end
# DELETE /words/1
# DELETE /words/1.json
def destroy
@word.destroy
respond_to do |format|
format.html { redirect_to words_url, notice: 'Word was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_word
@word = Word.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def word_params
params.require(:word).permit(:title, :description, :category_ids)
end
def category_params
params.require(:category).permit(:title, :category_ids, :category_id)
end
end
```
categories\_controller.rb:
```
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update, :destroy]
# GET /categories
# GET /categories.json
def index
@categories = Category.all
end
# GET /categories/1
# GET /categories/1.json
def show
end
# GET /categories/new
def new
@category = current_user.word_list.categories.build
end
# GET /categories/1/edit
def edit
end
# POST /categories
# POST /categories.json
def create
@category = Category.new(category_params)
respond_to do |format|
if @category.save
format.html { redirect_to @category, notice: 'Category was successfully created.' }
format.json { render :show, status: :created, location: @category }
else
format.html { render :new }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /categories/1
# PATCH/PUT /categories/1.json
def update
respond_to do |format|
if @category.update(category_params)
format.html { redirect_to @category, notice: 'Category was successfully updated.' }
format.json { render :show, status: :ok, location: @category }
else
format.html { render :edit }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /categories/1
# DELETE /categories/1.json
def destroy
@category.destroy
respond_to do |format|
format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_category
@category = Category.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def category_params
params.require(:category).permit(:title, :word_list_id, :category_ids)
end
end
```
word\_lists\_controller.rb:
```
class WordListsController < ApplicationController
before_action :set_word_list, only: [:show, :edit, :update, :destroy]
def from_category
@selected = current_user.word_list.words.joins(:categories).where( categories: {id: (params[:category_id])} )
respond_to do |format|
format.js
end
end
def all_words
respond_to do |format|
format.js
end
end
# GET /word_lists
# GET /word_lists.json
def index
@word_lists = WordList.all
end
# GET /word_lists/1
# GET /word_lists/1.json
def show
@words = Word.all
@word_list = WordList.find(params[:id])
end
# GET /word_lists/new
def new
@word_list = WordList.new
end
# GET /word_lists/1/edit
def edit
end
# POST /word_lists
# POST /word_lists.json
def create
@word_list = WordList.new(word_list_params)
respond_to do |format|
if @word_list.save
format.html { redirect_to @word_list, notice: 'Word list was successfully created.' }
format.json { render :show, status: :created, location: @word_list }
else
format.html { render :new }
format.json { render json: @word_list.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /word_lists/1
# PATCH/PUT /word_lists/1.json
def update
respond_to do |format|
if @word_list.update(word_list_params)
format.html { redirect_to @word_list, notice: 'Word list was successfully updated.' }
format.json { render :show, status: :ok, location: @word_list }
else
format.html { render :edit }
format.json { render json: @word_list.errors, status: :unprocessable_entity }
end
end
end
# DELETE /word_lists/1
# DELETE /word_lists/1.json
def destroy
@word_list.destroy
respond_to do |format|
format.html { redirect_to word_lists_url, notice: 'Word list was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_word_list
@word_list = WordList.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def word_list_params
params[:word_list]
end
end
```
word\_list.rb:
```
class WordList < ActiveRecord::Base
belongs_to :user
has_many :words
has_many :categories
end
```
word.rb:
```
class Word < ActiveRecord::Base
belongs_to :word_list
has_and_belongs_to_many :categories
validates :title, presence: true
scope :alphabetical_order_asc, -> { order("title ASC") }
end
```
category.rb:
```
class Category < ActiveRecord::Base
has_and_belongs_to_many :words
belongs_to :word_list
validates :title, presence: true
scope :alphabetical_order_asc, -> { order("title ASC") }
end
```
schema.rb:
```
ActiveRecord::Schema.define(version: 20150609234013) do
create_table "categories", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "word_list_id"
end
add_index "categories", ["word_list_id"], name: "index_categories_on_word_list_id"
create_table "categories_words", id: false, force: :cascade do |t|
t.integer "category_id"
t.integer "word_id"
end
add_index "categories_words", ["category_id"], name: "index_categories_words_on_category_id"
add_index "categories_words", ["word_id"], name: "index_categories_words_on_word_id"
create_table "quotes", force: :cascade do |t|
t.text "content"
t.string "author"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
create_table "word_lists", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end
create_table "words", force: :cascade do |t|
t.string "title"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "word_list_id"
end
add_index "words", ["word_list_id"], name: "index_words_on_word_list_id"
end
```
routes.rb:
```
Rails.application.routes.draw do
resources :quotes
resources :categories
resources :words
devise_for :users, controllers: { registrations: "users/registrations" }
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
root 'pages#home'
post 'create_word_and_category' => 'new_word#create_word_and_category'
end
``` | 2015/06/10 | [
"https://Stackoverflow.com/questions/30766766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111480/"
] | The discussion might not be active anymore but I'll share my answer for the future visitors.
Adding "{ checked: @array.map(&:to\_param) }" option as the last argument of collection\_check\_boxes may resolve your problem. Refer this [link](https://github.com/bootstrap-ruby/rails-bootstrap-forms/issues/151).
Example:
Suppose you have Software model and Platform(OS) model and want to choose one or more OS that support your software.
```
#views/softwares/edit.html.erb
<%= form_for @software do |f| %>
...
<%= f.label :supported_platform %>
<%= f.collection_check_boxes(:platform_ids, @platforms, :id, :platform_name, { checked: @software.platform_ids.map(&:to_param) }) %>
...
<%= f.submit "Save", class: 'btn btn-success' %>
<% end %>
```
note:
@software.platform\_ids should be an array. If you are using SQLite, you have to convert string into array when you pull the data out. I tested it with SQLite and confirmed working as well. See [my post](http://www.letmefix-it.com/2017/08/11/how-to-use-collection_check_boxes-ruby-on-rails/) for more detail. | This should be closer to what you were looking for:
```
<%= b.label(class: "checkbox-inline", :"data-value" => b.value) { b.check_box + b.text } %>
``` |
30,766,766 | GitHub repo: <https://github.com/Yorkshireman/mywordlist>
I've googled the hell out of this one. I'm sure there's a way, possibly requiring some code inside a html options hash, but I can't work it out. Any ideas?
When visiting the \_edit\_word\_form.html.erb partial for a Word that DOES have one or more categories, the Categories checkboxes are all unchecked, requiring the user to select them again, even if they don't want to change the Categories.
The text fields for the :title and :description ARE pre-populated (thankfully).
\_edit\_word\_form.html.erb:
```
<%= form_for(@word) do %>
<%= fields_for :word, @word do |word_form| %>
<div class="field form-group">
<%= word_form.label(:title, "Word:") %><br>
<%= word_form.text_field(:title, id: "new_word", required: true, autofocus: true, class: "form-control") %>
</div>
<div class="field form-group">
<%= word_form.label(:description, "Definition:") %><br>
<%= word_form.text_area(:description, class: "form-control") %>
</div>
<% end %>
<%= fields_for :category, @category do |category_form| %>
<% if current_user.word_list.categories.count > 0 %>
<div class="field form-group">
<%= category_form.label(:title, "Choose from existing Categories:") %><br>
<%= category_form.collection_check_boxes(:category_ids, current_user.word_list.categories.all, :id, :title) do |b| %>
<%= b.label(class: "checkbox-inline") { b.check_box + b.text } %>
<% end %>
</div>
<% end %>
<h4>AND/OR...</h4>
<div class="field form-group">
<%= category_form.label(:title, "Create and Use a New Category:") %><br>
<%= category_form.text_field(:title, class: "form-control") %>
</div>
<% end %>
<div class="actions">
<%= submit_tag("Update!", class: "btn btn-block btn-primary btn-lg") %>
</div>
<% end %>
```
Relevant part of the words/index.html.erb:
```
<% current_user.word_list.words.alphabetical_order_asc.each do |word| %>
<tr>
<td>
<%= link_to edit_word_path(word) do %>
<%= word.title %>
<span class="glyphicon glyphicon-pencil"></span>
<% end %>
</td>
<td><%= word.description %></td>
<td>
<% word.categories.alphabetical_order_asc.each do |category| %>
<a class="btn btn-info btn-sm", role="button">
<%= category.title %>
</a>
<% end %>
</td>
<td>
<%= link_to word, method: :delete, data: { confirm: 'Are you sure?' } do %>
<span class="glyphicon glyphicon-remove"></span>
<% end %>
</td>
</tr>
<% end %>
```
words\_controller.rb:
```
class WordsController < ApplicationController
before_action :set_word, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# GET /words
# GET /words.json
def index
@words = Word.all
@quotes = Quote.all
end
# GET /words/1
# GET /words/1.json
def show
end
# GET /words/new
def new
@word = current_user.word_list.words.build
end
# GET /words/1/edit
def edit
end
# POST /words
# POST /words.json
def create
@word = Word.new(word_params)
respond_to do |format|
if @word.save
format.html { redirect_to @word, notice: 'Word was successfully created.' }
format.json { render :show, status: :created, location: @word }
else
format.html { render :new }
format.json { render json: @word.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /words/1
# PATCH/PUT /words/1.json
def update
#need to first remove categories from the word
@word.categories.each do |category|
@word.categories.delete category
end
#then push categories in from the category_params
if params["category"].include?(:category_ids)
(params["category"])["category_ids"].each do |i|
next if i.to_i == 0
@word.categories << Category.find(i.to_i) unless @word.categories.include?(Category.find(i.to_i))
end
end
if category_params.include?(:title) && ((params["category"])["title"]) != ""
@word.categories << current_user.word_list.categories.build(title: (params["category"])["title"])
end
respond_to do |format|
if @word.update(word_params)
format.html { redirect_to words_path, notice: 'Word was successfully updated.' }
format.json { render :show, status: :ok, location: @word }
else
format.html { render :edit }
format.json { render json: @word.errors, status: :unprocessable_entity }
end
end
end
# DELETE /words/1
# DELETE /words/1.json
def destroy
@word.destroy
respond_to do |format|
format.html { redirect_to words_url, notice: 'Word was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_word
@word = Word.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def word_params
params.require(:word).permit(:title, :description, :category_ids)
end
def category_params
params.require(:category).permit(:title, :category_ids, :category_id)
end
end
```
categories\_controller.rb:
```
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update, :destroy]
# GET /categories
# GET /categories.json
def index
@categories = Category.all
end
# GET /categories/1
# GET /categories/1.json
def show
end
# GET /categories/new
def new
@category = current_user.word_list.categories.build
end
# GET /categories/1/edit
def edit
end
# POST /categories
# POST /categories.json
def create
@category = Category.new(category_params)
respond_to do |format|
if @category.save
format.html { redirect_to @category, notice: 'Category was successfully created.' }
format.json { render :show, status: :created, location: @category }
else
format.html { render :new }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /categories/1
# PATCH/PUT /categories/1.json
def update
respond_to do |format|
if @category.update(category_params)
format.html { redirect_to @category, notice: 'Category was successfully updated.' }
format.json { render :show, status: :ok, location: @category }
else
format.html { render :edit }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /categories/1
# DELETE /categories/1.json
def destroy
@category.destroy
respond_to do |format|
format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_category
@category = Category.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def category_params
params.require(:category).permit(:title, :word_list_id, :category_ids)
end
end
```
word\_lists\_controller.rb:
```
class WordListsController < ApplicationController
before_action :set_word_list, only: [:show, :edit, :update, :destroy]
def from_category
@selected = current_user.word_list.words.joins(:categories).where( categories: {id: (params[:category_id])} )
respond_to do |format|
format.js
end
end
def all_words
respond_to do |format|
format.js
end
end
# GET /word_lists
# GET /word_lists.json
def index
@word_lists = WordList.all
end
# GET /word_lists/1
# GET /word_lists/1.json
def show
@words = Word.all
@word_list = WordList.find(params[:id])
end
# GET /word_lists/new
def new
@word_list = WordList.new
end
# GET /word_lists/1/edit
def edit
end
# POST /word_lists
# POST /word_lists.json
def create
@word_list = WordList.new(word_list_params)
respond_to do |format|
if @word_list.save
format.html { redirect_to @word_list, notice: 'Word list was successfully created.' }
format.json { render :show, status: :created, location: @word_list }
else
format.html { render :new }
format.json { render json: @word_list.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /word_lists/1
# PATCH/PUT /word_lists/1.json
def update
respond_to do |format|
if @word_list.update(word_list_params)
format.html { redirect_to @word_list, notice: 'Word list was successfully updated.' }
format.json { render :show, status: :ok, location: @word_list }
else
format.html { render :edit }
format.json { render json: @word_list.errors, status: :unprocessable_entity }
end
end
end
# DELETE /word_lists/1
# DELETE /word_lists/1.json
def destroy
@word_list.destroy
respond_to do |format|
format.html { redirect_to word_lists_url, notice: 'Word list was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_word_list
@word_list = WordList.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def word_list_params
params[:word_list]
end
end
```
word\_list.rb:
```
class WordList < ActiveRecord::Base
belongs_to :user
has_many :words
has_many :categories
end
```
word.rb:
```
class Word < ActiveRecord::Base
belongs_to :word_list
has_and_belongs_to_many :categories
validates :title, presence: true
scope :alphabetical_order_asc, -> { order("title ASC") }
end
```
category.rb:
```
class Category < ActiveRecord::Base
has_and_belongs_to_many :words
belongs_to :word_list
validates :title, presence: true
scope :alphabetical_order_asc, -> { order("title ASC") }
end
```
schema.rb:
```
ActiveRecord::Schema.define(version: 20150609234013) do
create_table "categories", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "word_list_id"
end
add_index "categories", ["word_list_id"], name: "index_categories_on_word_list_id"
create_table "categories_words", id: false, force: :cascade do |t|
t.integer "category_id"
t.integer "word_id"
end
add_index "categories_words", ["category_id"], name: "index_categories_words_on_category_id"
add_index "categories_words", ["word_id"], name: "index_categories_words_on_word_id"
create_table "quotes", force: :cascade do |t|
t.text "content"
t.string "author"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
create_table "word_lists", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end
create_table "words", force: :cascade do |t|
t.string "title"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "word_list_id"
end
add_index "words", ["word_list_id"], name: "index_words_on_word_list_id"
end
```
routes.rb:
```
Rails.application.routes.draw do
resources :quotes
resources :categories
resources :words
devise_for :users, controllers: { registrations: "users/registrations" }
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
root 'pages#home'
post 'create_word_and_category' => 'new_word#create_word_and_category'
end
``` | 2015/06/10 | [
"https://Stackoverflow.com/questions/30766766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111480/"
] | The discussion might not be active anymore but I'll share my answer for the future visitors.
Adding "{ checked: @array.map(&:to\_param) }" option as the last argument of collection\_check\_boxes may resolve your problem. Refer this [link](https://github.com/bootstrap-ruby/rails-bootstrap-forms/issues/151).
Example:
Suppose you have Software model and Platform(OS) model and want to choose one or more OS that support your software.
```
#views/softwares/edit.html.erb
<%= form_for @software do |f| %>
...
<%= f.label :supported_platform %>
<%= f.collection_check_boxes(:platform_ids, @platforms, :id, :platform_name, { checked: @software.platform_ids.map(&:to_param) }) %>
...
<%= f.submit "Save", class: 'btn btn-success' %>
<% end %>
```
note:
@software.platform\_ids should be an array. If you are using SQLite, you have to convert string into array when you pull the data out. I tested it with SQLite and confirmed working as well. See [my post](http://www.letmefix-it.com/2017/08/11/how-to-use-collection_check_boxes-ruby-on-rails/) for more detail. | Try changing your `_edit_word_form.html.erb` like this
```
<%= form_for(@word) do |f| %>
<div class="field form-group">
<%= f.label(:title, "Word:") %><br>
<%= f.text_field(:title, id: "new_word", required: true, autofocus: true, class: "form-control") %>
</div>
<div class="field form-group">
<%= f.label(:description, "Definition:") %><br>
<%= f.text_area(:description, class: "form-control") %>
</div>
<%= f.fields_for :category do |category_form| %>
<% if current_user.word_list.categories.count > 0 %>
<div class="field form-group">
<%= category_form.label(:title, "Choose from existing Categories:") %><br>
<%= category_form.collection_check_boxes(:category_ids, current_user.word_list.categories.all, :id, :title) do |b| %>
<%= b.label(class: "checkbox-inline") { b.check_box + b.text } %>
<% end %>
</div>
<% end %>
<h4>AND/OR...</h4>
<div class="field form-group">
<%= category_form.label(:title, "Create and Use a New Category:") %><br>
<%= category_form.text_field(:title, class: "form-control") %>
</div>
<% end %>
<div class="actions">
<%= f.submit("Update!", class: "btn btn-block btn-primary btn-lg") %>
</div>
<% end %>
``` |
30,766,766 | GitHub repo: <https://github.com/Yorkshireman/mywordlist>
I've googled the hell out of this one. I'm sure there's a way, possibly requiring some code inside a html options hash, but I can't work it out. Any ideas?
When visiting the \_edit\_word\_form.html.erb partial for a Word that DOES have one or more categories, the Categories checkboxes are all unchecked, requiring the user to select them again, even if they don't want to change the Categories.
The text fields for the :title and :description ARE pre-populated (thankfully).
\_edit\_word\_form.html.erb:
```
<%= form_for(@word) do %>
<%= fields_for :word, @word do |word_form| %>
<div class="field form-group">
<%= word_form.label(:title, "Word:") %><br>
<%= word_form.text_field(:title, id: "new_word", required: true, autofocus: true, class: "form-control") %>
</div>
<div class="field form-group">
<%= word_form.label(:description, "Definition:") %><br>
<%= word_form.text_area(:description, class: "form-control") %>
</div>
<% end %>
<%= fields_for :category, @category do |category_form| %>
<% if current_user.word_list.categories.count > 0 %>
<div class="field form-group">
<%= category_form.label(:title, "Choose from existing Categories:") %><br>
<%= category_form.collection_check_boxes(:category_ids, current_user.word_list.categories.all, :id, :title) do |b| %>
<%= b.label(class: "checkbox-inline") { b.check_box + b.text } %>
<% end %>
</div>
<% end %>
<h4>AND/OR...</h4>
<div class="field form-group">
<%= category_form.label(:title, "Create and Use a New Category:") %><br>
<%= category_form.text_field(:title, class: "form-control") %>
</div>
<% end %>
<div class="actions">
<%= submit_tag("Update!", class: "btn btn-block btn-primary btn-lg") %>
</div>
<% end %>
```
Relevant part of the words/index.html.erb:
```
<% current_user.word_list.words.alphabetical_order_asc.each do |word| %>
<tr>
<td>
<%= link_to edit_word_path(word) do %>
<%= word.title %>
<span class="glyphicon glyphicon-pencil"></span>
<% end %>
</td>
<td><%= word.description %></td>
<td>
<% word.categories.alphabetical_order_asc.each do |category| %>
<a class="btn btn-info btn-sm", role="button">
<%= category.title %>
</a>
<% end %>
</td>
<td>
<%= link_to word, method: :delete, data: { confirm: 'Are you sure?' } do %>
<span class="glyphicon glyphicon-remove"></span>
<% end %>
</td>
</tr>
<% end %>
```
words\_controller.rb:
```
class WordsController < ApplicationController
before_action :set_word, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# GET /words
# GET /words.json
def index
@words = Word.all
@quotes = Quote.all
end
# GET /words/1
# GET /words/1.json
def show
end
# GET /words/new
def new
@word = current_user.word_list.words.build
end
# GET /words/1/edit
def edit
end
# POST /words
# POST /words.json
def create
@word = Word.new(word_params)
respond_to do |format|
if @word.save
format.html { redirect_to @word, notice: 'Word was successfully created.' }
format.json { render :show, status: :created, location: @word }
else
format.html { render :new }
format.json { render json: @word.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /words/1
# PATCH/PUT /words/1.json
def update
#need to first remove categories from the word
@word.categories.each do |category|
@word.categories.delete category
end
#then push categories in from the category_params
if params["category"].include?(:category_ids)
(params["category"])["category_ids"].each do |i|
next if i.to_i == 0
@word.categories << Category.find(i.to_i) unless @word.categories.include?(Category.find(i.to_i))
end
end
if category_params.include?(:title) && ((params["category"])["title"]) != ""
@word.categories << current_user.word_list.categories.build(title: (params["category"])["title"])
end
respond_to do |format|
if @word.update(word_params)
format.html { redirect_to words_path, notice: 'Word was successfully updated.' }
format.json { render :show, status: :ok, location: @word }
else
format.html { render :edit }
format.json { render json: @word.errors, status: :unprocessable_entity }
end
end
end
# DELETE /words/1
# DELETE /words/1.json
def destroy
@word.destroy
respond_to do |format|
format.html { redirect_to words_url, notice: 'Word was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_word
@word = Word.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def word_params
params.require(:word).permit(:title, :description, :category_ids)
end
def category_params
params.require(:category).permit(:title, :category_ids, :category_id)
end
end
```
categories\_controller.rb:
```
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update, :destroy]
# GET /categories
# GET /categories.json
def index
@categories = Category.all
end
# GET /categories/1
# GET /categories/1.json
def show
end
# GET /categories/new
def new
@category = current_user.word_list.categories.build
end
# GET /categories/1/edit
def edit
end
# POST /categories
# POST /categories.json
def create
@category = Category.new(category_params)
respond_to do |format|
if @category.save
format.html { redirect_to @category, notice: 'Category was successfully created.' }
format.json { render :show, status: :created, location: @category }
else
format.html { render :new }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /categories/1
# PATCH/PUT /categories/1.json
def update
respond_to do |format|
if @category.update(category_params)
format.html { redirect_to @category, notice: 'Category was successfully updated.' }
format.json { render :show, status: :ok, location: @category }
else
format.html { render :edit }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /categories/1
# DELETE /categories/1.json
def destroy
@category.destroy
respond_to do |format|
format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_category
@category = Category.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def category_params
params.require(:category).permit(:title, :word_list_id, :category_ids)
end
end
```
word\_lists\_controller.rb:
```
class WordListsController < ApplicationController
before_action :set_word_list, only: [:show, :edit, :update, :destroy]
def from_category
@selected = current_user.word_list.words.joins(:categories).where( categories: {id: (params[:category_id])} )
respond_to do |format|
format.js
end
end
def all_words
respond_to do |format|
format.js
end
end
# GET /word_lists
# GET /word_lists.json
def index
@word_lists = WordList.all
end
# GET /word_lists/1
# GET /word_lists/1.json
def show
@words = Word.all
@word_list = WordList.find(params[:id])
end
# GET /word_lists/new
def new
@word_list = WordList.new
end
# GET /word_lists/1/edit
def edit
end
# POST /word_lists
# POST /word_lists.json
def create
@word_list = WordList.new(word_list_params)
respond_to do |format|
if @word_list.save
format.html { redirect_to @word_list, notice: 'Word list was successfully created.' }
format.json { render :show, status: :created, location: @word_list }
else
format.html { render :new }
format.json { render json: @word_list.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /word_lists/1
# PATCH/PUT /word_lists/1.json
def update
respond_to do |format|
if @word_list.update(word_list_params)
format.html { redirect_to @word_list, notice: 'Word list was successfully updated.' }
format.json { render :show, status: :ok, location: @word_list }
else
format.html { render :edit }
format.json { render json: @word_list.errors, status: :unprocessable_entity }
end
end
end
# DELETE /word_lists/1
# DELETE /word_lists/1.json
def destroy
@word_list.destroy
respond_to do |format|
format.html { redirect_to word_lists_url, notice: 'Word list was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_word_list
@word_list = WordList.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def word_list_params
params[:word_list]
end
end
```
word\_list.rb:
```
class WordList < ActiveRecord::Base
belongs_to :user
has_many :words
has_many :categories
end
```
word.rb:
```
class Word < ActiveRecord::Base
belongs_to :word_list
has_and_belongs_to_many :categories
validates :title, presence: true
scope :alphabetical_order_asc, -> { order("title ASC") }
end
```
category.rb:
```
class Category < ActiveRecord::Base
has_and_belongs_to_many :words
belongs_to :word_list
validates :title, presence: true
scope :alphabetical_order_asc, -> { order("title ASC") }
end
```
schema.rb:
```
ActiveRecord::Schema.define(version: 20150609234013) do
create_table "categories", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "word_list_id"
end
add_index "categories", ["word_list_id"], name: "index_categories_on_word_list_id"
create_table "categories_words", id: false, force: :cascade do |t|
t.integer "category_id"
t.integer "word_id"
end
add_index "categories_words", ["category_id"], name: "index_categories_words_on_category_id"
add_index "categories_words", ["word_id"], name: "index_categories_words_on_word_id"
create_table "quotes", force: :cascade do |t|
t.text "content"
t.string "author"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
create_table "word_lists", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end
create_table "words", force: :cascade do |t|
t.string "title"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "word_list_id"
end
add_index "words", ["word_list_id"], name: "index_words_on_word_list_id"
end
```
routes.rb:
```
Rails.application.routes.draw do
resources :quotes
resources :categories
resources :words
devise_for :users, controllers: { registrations: "users/registrations" }
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
root 'pages#home'
post 'create_word_and_category' => 'new_word#create_word_and_category'
end
``` | 2015/06/10 | [
"https://Stackoverflow.com/questions/30766766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111480/"
] | The discussion might not be active anymore but I'll share my answer for the future visitors.
Adding "{ checked: @array.map(&:to\_param) }" option as the last argument of collection\_check\_boxes may resolve your problem. Refer this [link](https://github.com/bootstrap-ruby/rails-bootstrap-forms/issues/151).
Example:
Suppose you have Software model and Platform(OS) model and want to choose one or more OS that support your software.
```
#views/softwares/edit.html.erb
<%= form_for @software do |f| %>
...
<%= f.label :supported_platform %>
<%= f.collection_check_boxes(:platform_ids, @platforms, :id, :platform_name, { checked: @software.platform_ids.map(&:to_param) }) %>
...
<%= f.submit "Save", class: 'btn btn-success' %>
<% end %>
```
note:
@software.platform\_ids should be an array. If you are using SQLite, you have to convert string into array when you pull the data out. I tested it with SQLite and confirmed working as well. See [my post](http://www.letmefix-it.com/2017/08/11/how-to-use-collection_check_boxes-ruby-on-rails/) for more detail. | So user is editing a word from their word list, but you want to show checkboxes for all categories for all the words in their word list, checking those categories attached to the word being editing. Is that correct?
It looks like you're missing out the first parameter in #collection\_check\_boxes, which should be the object you call :category\_ids on.
If the object is the user's word\_list, then something like:
```
<%= category_form.collection_check_boxes(current_user.word_list, :category_ids, current_user.word_list.categories.all, :id, :title) do |b| %>
```
May not be the exact answer--I can't test it--but hope it gives you something to go on. |
30,766,766 | GitHub repo: <https://github.com/Yorkshireman/mywordlist>
I've googled the hell out of this one. I'm sure there's a way, possibly requiring some code inside a html options hash, but I can't work it out. Any ideas?
When visiting the \_edit\_word\_form.html.erb partial for a Word that DOES have one or more categories, the Categories checkboxes are all unchecked, requiring the user to select them again, even if they don't want to change the Categories.
The text fields for the :title and :description ARE pre-populated (thankfully).
\_edit\_word\_form.html.erb:
```
<%= form_for(@word) do %>
<%= fields_for :word, @word do |word_form| %>
<div class="field form-group">
<%= word_form.label(:title, "Word:") %><br>
<%= word_form.text_field(:title, id: "new_word", required: true, autofocus: true, class: "form-control") %>
</div>
<div class="field form-group">
<%= word_form.label(:description, "Definition:") %><br>
<%= word_form.text_area(:description, class: "form-control") %>
</div>
<% end %>
<%= fields_for :category, @category do |category_form| %>
<% if current_user.word_list.categories.count > 0 %>
<div class="field form-group">
<%= category_form.label(:title, "Choose from existing Categories:") %><br>
<%= category_form.collection_check_boxes(:category_ids, current_user.word_list.categories.all, :id, :title) do |b| %>
<%= b.label(class: "checkbox-inline") { b.check_box + b.text } %>
<% end %>
</div>
<% end %>
<h4>AND/OR...</h4>
<div class="field form-group">
<%= category_form.label(:title, "Create and Use a New Category:") %><br>
<%= category_form.text_field(:title, class: "form-control") %>
</div>
<% end %>
<div class="actions">
<%= submit_tag("Update!", class: "btn btn-block btn-primary btn-lg") %>
</div>
<% end %>
```
Relevant part of the words/index.html.erb:
```
<% current_user.word_list.words.alphabetical_order_asc.each do |word| %>
<tr>
<td>
<%= link_to edit_word_path(word) do %>
<%= word.title %>
<span class="glyphicon glyphicon-pencil"></span>
<% end %>
</td>
<td><%= word.description %></td>
<td>
<% word.categories.alphabetical_order_asc.each do |category| %>
<a class="btn btn-info btn-sm", role="button">
<%= category.title %>
</a>
<% end %>
</td>
<td>
<%= link_to word, method: :delete, data: { confirm: 'Are you sure?' } do %>
<span class="glyphicon glyphicon-remove"></span>
<% end %>
</td>
</tr>
<% end %>
```
words\_controller.rb:
```
class WordsController < ApplicationController
before_action :set_word, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# GET /words
# GET /words.json
def index
@words = Word.all
@quotes = Quote.all
end
# GET /words/1
# GET /words/1.json
def show
end
# GET /words/new
def new
@word = current_user.word_list.words.build
end
# GET /words/1/edit
def edit
end
# POST /words
# POST /words.json
def create
@word = Word.new(word_params)
respond_to do |format|
if @word.save
format.html { redirect_to @word, notice: 'Word was successfully created.' }
format.json { render :show, status: :created, location: @word }
else
format.html { render :new }
format.json { render json: @word.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /words/1
# PATCH/PUT /words/1.json
def update
#need to first remove categories from the word
@word.categories.each do |category|
@word.categories.delete category
end
#then push categories in from the category_params
if params["category"].include?(:category_ids)
(params["category"])["category_ids"].each do |i|
next if i.to_i == 0
@word.categories << Category.find(i.to_i) unless @word.categories.include?(Category.find(i.to_i))
end
end
if category_params.include?(:title) && ((params["category"])["title"]) != ""
@word.categories << current_user.word_list.categories.build(title: (params["category"])["title"])
end
respond_to do |format|
if @word.update(word_params)
format.html { redirect_to words_path, notice: 'Word was successfully updated.' }
format.json { render :show, status: :ok, location: @word }
else
format.html { render :edit }
format.json { render json: @word.errors, status: :unprocessable_entity }
end
end
end
# DELETE /words/1
# DELETE /words/1.json
def destroy
@word.destroy
respond_to do |format|
format.html { redirect_to words_url, notice: 'Word was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_word
@word = Word.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def word_params
params.require(:word).permit(:title, :description, :category_ids)
end
def category_params
params.require(:category).permit(:title, :category_ids, :category_id)
end
end
```
categories\_controller.rb:
```
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update, :destroy]
# GET /categories
# GET /categories.json
def index
@categories = Category.all
end
# GET /categories/1
# GET /categories/1.json
def show
end
# GET /categories/new
def new
@category = current_user.word_list.categories.build
end
# GET /categories/1/edit
def edit
end
# POST /categories
# POST /categories.json
def create
@category = Category.new(category_params)
respond_to do |format|
if @category.save
format.html { redirect_to @category, notice: 'Category was successfully created.' }
format.json { render :show, status: :created, location: @category }
else
format.html { render :new }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /categories/1
# PATCH/PUT /categories/1.json
def update
respond_to do |format|
if @category.update(category_params)
format.html { redirect_to @category, notice: 'Category was successfully updated.' }
format.json { render :show, status: :ok, location: @category }
else
format.html { render :edit }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /categories/1
# DELETE /categories/1.json
def destroy
@category.destroy
respond_to do |format|
format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_category
@category = Category.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def category_params
params.require(:category).permit(:title, :word_list_id, :category_ids)
end
end
```
word\_lists\_controller.rb:
```
class WordListsController < ApplicationController
before_action :set_word_list, only: [:show, :edit, :update, :destroy]
def from_category
@selected = current_user.word_list.words.joins(:categories).where( categories: {id: (params[:category_id])} )
respond_to do |format|
format.js
end
end
def all_words
respond_to do |format|
format.js
end
end
# GET /word_lists
# GET /word_lists.json
def index
@word_lists = WordList.all
end
# GET /word_lists/1
# GET /word_lists/1.json
def show
@words = Word.all
@word_list = WordList.find(params[:id])
end
# GET /word_lists/new
def new
@word_list = WordList.new
end
# GET /word_lists/1/edit
def edit
end
# POST /word_lists
# POST /word_lists.json
def create
@word_list = WordList.new(word_list_params)
respond_to do |format|
if @word_list.save
format.html { redirect_to @word_list, notice: 'Word list was successfully created.' }
format.json { render :show, status: :created, location: @word_list }
else
format.html { render :new }
format.json { render json: @word_list.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /word_lists/1
# PATCH/PUT /word_lists/1.json
def update
respond_to do |format|
if @word_list.update(word_list_params)
format.html { redirect_to @word_list, notice: 'Word list was successfully updated.' }
format.json { render :show, status: :ok, location: @word_list }
else
format.html { render :edit }
format.json { render json: @word_list.errors, status: :unprocessable_entity }
end
end
end
# DELETE /word_lists/1
# DELETE /word_lists/1.json
def destroy
@word_list.destroy
respond_to do |format|
format.html { redirect_to word_lists_url, notice: 'Word list was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_word_list
@word_list = WordList.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def word_list_params
params[:word_list]
end
end
```
word\_list.rb:
```
class WordList < ActiveRecord::Base
belongs_to :user
has_many :words
has_many :categories
end
```
word.rb:
```
class Word < ActiveRecord::Base
belongs_to :word_list
has_and_belongs_to_many :categories
validates :title, presence: true
scope :alphabetical_order_asc, -> { order("title ASC") }
end
```
category.rb:
```
class Category < ActiveRecord::Base
has_and_belongs_to_many :words
belongs_to :word_list
validates :title, presence: true
scope :alphabetical_order_asc, -> { order("title ASC") }
end
```
schema.rb:
```
ActiveRecord::Schema.define(version: 20150609234013) do
create_table "categories", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "word_list_id"
end
add_index "categories", ["word_list_id"], name: "index_categories_on_word_list_id"
create_table "categories_words", id: false, force: :cascade do |t|
t.integer "category_id"
t.integer "word_id"
end
add_index "categories_words", ["category_id"], name: "index_categories_words_on_category_id"
add_index "categories_words", ["word_id"], name: "index_categories_words_on_word_id"
create_table "quotes", force: :cascade do |t|
t.text "content"
t.string "author"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
create_table "word_lists", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end
create_table "words", force: :cascade do |t|
t.string "title"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "word_list_id"
end
add_index "words", ["word_list_id"], name: "index_words_on_word_list_id"
end
```
routes.rb:
```
Rails.application.routes.draw do
resources :quotes
resources :categories
resources :words
devise_for :users, controllers: { registrations: "users/registrations" }
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
root 'pages#home'
post 'create_word_and_category' => 'new_word#create_word_and_category'
end
``` | 2015/06/10 | [
"https://Stackoverflow.com/questions/30766766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111480/"
] | The discussion might not be active anymore but I'll share my answer for the future visitors.
Adding "{ checked: @array.map(&:to\_param) }" option as the last argument of collection\_check\_boxes may resolve your problem. Refer this [link](https://github.com/bootstrap-ruby/rails-bootstrap-forms/issues/151).
Example:
Suppose you have Software model and Platform(OS) model and want to choose one or more OS that support your software.
```
#views/softwares/edit.html.erb
<%= form_for @software do |f| %>
...
<%= f.label :supported_platform %>
<%= f.collection_check_boxes(:platform_ids, @platforms, :id, :platform_name, { checked: @software.platform_ids.map(&:to_param) }) %>
...
<%= f.submit "Save", class: 'btn btn-success' %>
<% end %>
```
note:
@software.platform\_ids should be an array. If you are using SQLite, you have to convert string into array when you pull the data out. I tested it with SQLite and confirmed working as well. See [my post](http://www.letmefix-it.com/2017/08/11/how-to-use-collection_check_boxes-ruby-on-rails/) for more detail. | ### What's wrong
When you are calling `category_form.collection_check_boxes(:category_ids, current_user.word_list.categories.all, :id, :title)` within the `fields_for :category`, you are saying there is a method on `@word.category` called `category_ids` which will return the ids of the categories related to `@word.category`. The checkbox will be checked if there is a matching id both in `category_ids` results and in `current_user.word_list.categories.all`.
I don't think there is a `@word.category` or a `@word.category.category_ids`. I think there's `@word.categories` though.
### How to fix it
That being said, my instinct tells me that you need to use something like:
```
<%= form_for(@word) do |f| %>
<div class="field form-group">
<%= f.label(:title, "Word:") %><br>
<%= f.text_field(:title, id: "new_word", required: true, autofocus: true, class: "form-control") %>
</div>
<div class="field form-group">
<%= f.label(:description, "Definition:") %><br>
<%= f.text_area(:description, class: "form-control") %>
</div>
<% if current_user.word_list.categories.count > 0 %>
<div class="field form-group">
<%= f.label(:categories, "Choose from existing Categories:") %><br>
<%= f.collection_check_boxes(:category_ids, current_user.word_list.categories.all, :id, :title) %>
</div>
<% end %>
<div class="actions">
<%= f.submit("Update!", class: "btn btn-block btn-primary btn-lg") %>
</div>
<% end %>
```
Note that I've moved the `collection_check_boxes` to the `@word`'s form builder, as you are hoping to build the "categories" value for the current `@word`. I think this should be a step in the right direction anyway. |
33,551,559 | I want to ignore the punctuation.So, I'm trying to make a program that counts all the appearences of every word in my text but without taking in consideration the punctuation marks.
So my program is:
```
static void Main(string[] args)
{
string text = "This my world. World, world,THIS WORLD ! Is this - the world .";
IDictionary<string, int> wordsCount =
new SortedDictionary<string, int>();
text=text.ToLower();
text = text.replaceAll("[^0-9a-zA-Z\text]", "X");
string[] words = text.Split(' ',',','-','!','.');
foreach (string word in words)
{
int count = 1;
if (wordsCount.ContainsKey(word))
count = wordsCount[word] + 1;
wordsCount[word] = count;
}
var items = from pair in wordsCount
orderby pair.Value ascending
select pair;
foreach (var p in items)
{
Console.WriteLine("{0} -> {1}", p.Key, p.Value);
}
}
```
The output is:
```
is->1
my->1
the->1
this->3
world->5
(here is nothing) -> 8
```
How can I remove the punctuation here? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33551559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
string[] words = text.Split(new char[]{' ',',','-','!','.'}, StringSplitOPtions.RemoveEmptyItems);
``` | It is simple - first step is to remove undesired punctuation with function `Replace` and then continue with splitting as you have it. |
33,551,559 | I want to ignore the punctuation.So, I'm trying to make a program that counts all the appearences of every word in my text but without taking in consideration the punctuation marks.
So my program is:
```
static void Main(string[] args)
{
string text = "This my world. World, world,THIS WORLD ! Is this - the world .";
IDictionary<string, int> wordsCount =
new SortedDictionary<string, int>();
text=text.ToLower();
text = text.replaceAll("[^0-9a-zA-Z\text]", "X");
string[] words = text.Split(' ',',','-','!','.');
foreach (string word in words)
{
int count = 1;
if (wordsCount.ContainsKey(word))
count = wordsCount[word] + 1;
wordsCount[word] = count;
}
var items = from pair in wordsCount
orderby pair.Value ascending
select pair;
foreach (var p in items)
{
Console.WriteLine("{0} -> {1}", p.Key, p.Value);
}
}
```
The output is:
```
is->1
my->1
the->1
this->3
world->5
(here is nothing) -> 8
```
How can I remove the punctuation here? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33551559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You should try specifying `StringSplitOptions.RemoveEmptyEntries`:
```
string[] words = text.Split(" ,-!.".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
```
Note that instead of manually creating a `char[]` with all the punctuation characters, you may create a `string` and call `ToCharArray()` to get the array of characters.
I find it easier to read and to modify later on. | It is simple - first step is to remove undesired punctuation with function `Replace` and then continue with splitting as you have it. |
33,551,559 | I want to ignore the punctuation.So, I'm trying to make a program that counts all the appearences of every word in my text but without taking in consideration the punctuation marks.
So my program is:
```
static void Main(string[] args)
{
string text = "This my world. World, world,THIS WORLD ! Is this - the world .";
IDictionary<string, int> wordsCount =
new SortedDictionary<string, int>();
text=text.ToLower();
text = text.replaceAll("[^0-9a-zA-Z\text]", "X");
string[] words = text.Split(' ',',','-','!','.');
foreach (string word in words)
{
int count = 1;
if (wordsCount.ContainsKey(word))
count = wordsCount[word] + 1;
wordsCount[word] = count;
}
var items = from pair in wordsCount
orderby pair.Value ascending
select pair;
foreach (var p in items)
{
Console.WriteLine("{0} -> {1}", p.Key, p.Value);
}
}
```
The output is:
```
is->1
my->1
the->1
this->3
world->5
(here is nothing) -> 8
```
How can I remove the punctuation here? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33551559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You should try specifying `StringSplitOptions.RemoveEmptyEntries`:
```
string[] words = text.Split(" ,-!.".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
```
Note that instead of manually creating a `char[]` with all the punctuation characters, you may create a `string` and call `ToCharArray()` to get the array of characters.
I find it easier to read and to modify later on. | ```
string[] words = text.Split(new char[]{' ',',','-','!','.'}, StringSplitOPtions.RemoveEmptyItems);
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.