qid
int64 | question
string | date
string | metadata
list | response_j
string | response_k
string |
|---|---|---|---|---|---|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
I want to specifically address the first question in a way that it hasn't been yet.
>
> Q 1. What is the difference between a bisexual and a pansexual?
>
>
>
*Bisexualism* works only in a context where gender is binary. It assumes that people are only one of two possible genders—and that if you are bisexual you are attracted to both. But gender neutrality eliminates this dichotomy altogether.
(Note, too, that the distinction we now make between *sex* and *gender* is something only relatively recent.)
There are people who positively identify as gender-neutral (or as a non-binary gender). They do not consider themselves to be either gender. And while some *may* identify with various components on a sliding scale or spectrum (with one gender at one end and another gender at the other end), others consider themselves to have no gender identity at all, and still others consider themselves to have an identity that is simply "outside" any such binary scale.
In other words, some people who are gender neutral reject not only two possible genders but also the idea of a defining spectrum *between* two genders. (At least with respect to themselves.)
From an interesting article called "[10 things you always wanted to know about being non-binary but were afraid to ask](http://www.cbc.ca/news/canada/prince-edward-island/pei-non-binary-gender-sexuality-rory-starkman-russell-louder-1.4495208)":
>
> If you're looking at gender on a spectrum from male to female, *non-binary could be anywhere outside of that spectrum* [emphasis mine] or in between the male and female.
>
>
>
So, coming back to *pansexualism*, it *may* be somewhat misleading to say that somebody who is pansexual is attracted to all people "regardless of where they fit on a spectrum" (unless you also include everybody who isn't on that spectrum). Instead, I would say that they are simply attracted to people period, regardless of gender identity or non-identity.
---
Here is some additional information, as pulled from comments.
Although Dictionary.com says that a *bissexual* is attracted *to people of various gender identities*, both Merriam-Webster and Oxford continue to explicitly use a binary definition for the word. At least traditionally, a bisexual is attracted to both men and women. But (by some definitions), they would not be attracted to somebody who doesn't identify as male or female.
Practically speaking, *bisexualism* might amount to the same thing as *pansexualism*. But still, there is a logical distinction between "I like all colours" and "colour is irrelevant."
The definition of pansexual provided in the question states (the emphasis is mine) that: "Pansexual people may refer to themselves as **gender-blind**, asserting that **gender and sex are not determining factors in their romantic or sexual attraction to others**."
Somebody who is colour blind is literally not influenced by the choice of those colours they can't distinguish—except intellectually. That's what's meant by "gender blind" when it comes to pansexuality. Bisexuals can differentiate between genders (although they are attracted to both); but pansexuals simply don't differentiate between them at all (aside from intellectually).
To reuse an analogy from a different answer, I like steak and I like pasta. But when I go to a restaurant that has both on the menu, I decide which of those I want to eat on that particular night—which one I'm more in the mood for. However, for somebody without taste buds (somebody who is "taste blind") the flavour of those two menu items will have no bearing on their choice. For them, based on taste alone, the two are indistinguishable, and they might as well be contemplating the same thing. They will make their decision based on other factors (price, calories, size, and so on).
Similarly, consider a bisexual who's presented with a choice between a man and a woman. While they are attracted to both, they might be feeling more *partial* to one gender. It likely won't be the only factor in their choice of partner, but it will be at least *a* factor.
For a pansexual, who is "gender blind," it won't be a factor at all. They won't feel any more *partial* to a particular gender than any other at any given time, simply because it's not part of their perception. They are simply unaware of gender in any way—aside from intellectually. For them, their choice in partner is only (and always) about all of the non-gender factors.
---
As for the second question, this culture, and the terminology behind it, is so new that language and attitudes haven't yet had time to "shake out" into a cohesive consensus yet. That there is no agreement comes down to the timing of adoption.
(It was only in 2017 that both *The Chicago Manual of Style* and the *Associated Press Stylebook* acknowledged the use of *they* and *their* (and even *themself*) as an acceptable form of gender-neutral third-person pronoun if required—but *in particular* when used in the context of people who use it as part of their identify as having a non-binary gender.)
|
* Bisexuality *sensu lato* (in the broad sense) means that one is sexually attracted to both males and females; it makes no distinction as to whether or not one is sexually attracted to persons who are neither male nor female.
+ Bisexuality *sensu stricto* (in the narrow sense) means that one is sexually attracted to males and females, but *not* to non-male non-female persons.
+ Pansexuality means that one is sexually attracted to persons of all genders.
If gender is regarded as a spectrum, with more possible values than just MALE and FEMALE, a pansexual person would be bisexual *senso lato*, due to being sexually attracted to both males and females, but would not be bisexual *senso stricto*, due to also being attracted to non-male non-females.
If gender is regarded as strictly binary, with the only possible values being MALE and FEMALE, the distinction between the two subcategories of bisexuality *sensu lato* disappears, and bisexuality and pansexuality become synonymous.
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
I want to specifically address the first question in a way that it hasn't been yet.
>
> Q 1. What is the difference between a bisexual and a pansexual?
>
>
>
*Bisexualism* works only in a context where gender is binary. It assumes that people are only one of two possible genders—and that if you are bisexual you are attracted to both. But gender neutrality eliminates this dichotomy altogether.
(Note, too, that the distinction we now make between *sex* and *gender* is something only relatively recent.)
There are people who positively identify as gender-neutral (or as a non-binary gender). They do not consider themselves to be either gender. And while some *may* identify with various components on a sliding scale or spectrum (with one gender at one end and another gender at the other end), others consider themselves to have no gender identity at all, and still others consider themselves to have an identity that is simply "outside" any such binary scale.
In other words, some people who are gender neutral reject not only two possible genders but also the idea of a defining spectrum *between* two genders. (At least with respect to themselves.)
From an interesting article called "[10 things you always wanted to know about being non-binary but were afraid to ask](http://www.cbc.ca/news/canada/prince-edward-island/pei-non-binary-gender-sexuality-rory-starkman-russell-louder-1.4495208)":
>
> If you're looking at gender on a spectrum from male to female, *non-binary could be anywhere outside of that spectrum* [emphasis mine] or in between the male and female.
>
>
>
So, coming back to *pansexualism*, it *may* be somewhat misleading to say that somebody who is pansexual is attracted to all people "regardless of where they fit on a spectrum" (unless you also include everybody who isn't on that spectrum). Instead, I would say that they are simply attracted to people period, regardless of gender identity or non-identity.
---
Here is some additional information, as pulled from comments.
Although Dictionary.com says that a *bissexual* is attracted *to people of various gender identities*, both Merriam-Webster and Oxford continue to explicitly use a binary definition for the word. At least traditionally, a bisexual is attracted to both men and women. But (by some definitions), they would not be attracted to somebody who doesn't identify as male or female.
Practically speaking, *bisexualism* might amount to the same thing as *pansexualism*. But still, there is a logical distinction between "I like all colours" and "colour is irrelevant."
The definition of pansexual provided in the question states (the emphasis is mine) that: "Pansexual people may refer to themselves as **gender-blind**, asserting that **gender and sex are not determining factors in their romantic or sexual attraction to others**."
Somebody who is colour blind is literally not influenced by the choice of those colours they can't distinguish—except intellectually. That's what's meant by "gender blind" when it comes to pansexuality. Bisexuals can differentiate between genders (although they are attracted to both); but pansexuals simply don't differentiate between them at all (aside from intellectually).
To reuse an analogy from a different answer, I like steak and I like pasta. But when I go to a restaurant that has both on the menu, I decide which of those I want to eat on that particular night—which one I'm more in the mood for. However, for somebody without taste buds (somebody who is "taste blind") the flavour of those two menu items will have no bearing on their choice. For them, based on taste alone, the two are indistinguishable, and they might as well be contemplating the same thing. They will make their decision based on other factors (price, calories, size, and so on).
Similarly, consider a bisexual who's presented with a choice between a man and a woman. While they are attracted to both, they might be feeling more *partial* to one gender. It likely won't be the only factor in their choice of partner, but it will be at least *a* factor.
For a pansexual, who is "gender blind," it won't be a factor at all. They won't feel any more *partial* to a particular gender than any other at any given time, simply because it's not part of their perception. They are simply unaware of gender in any way—aside from intellectually. For them, their choice in partner is only (and always) about all of the non-gender factors.
---
As for the second question, this culture, and the terminology behind it, is so new that language and attitudes haven't yet had time to "shake out" into a cohesive consensus yet. That there is no agreement comes down to the timing of adoption.
(It was only in 2017 that both *The Chicago Manual of Style* and the *Associated Press Stylebook* acknowledged the use of *they* and *their* (and even *themself*) as an acceptable form of gender-neutral third-person pronoun if required—but *in particular* when used in the context of people who use it as part of their identify as having a non-binary gender.)
|
The difference between Pansexual and Bisexual can be explained like this.
Not all heterosexuals focus on lust when selecting a spouse. For some people, hetero, gay and pan, the emphasis is on being in love, and in a committed "forever" relationship. Many do not consumate their relationships sexually until vows are exchanged. People who are head over heels in love, may glimpse the Pan reality... Would you be less in love if your special darling was born a different gender?
By comparison, many people seek sexual relationships... or relationships that begin with sex. For these people, regardless of sexual orientation; desire, attraction and lust, are what it's all about. The physicality is important. Sometimes gender, colour, stature, size, clothing, muscle tone and even hairlessness can be some of the physical attributes that are judged in the selection of a partner. What prospective mates physically look like, is a huge priority. Bisexual people are sexually attracted to/by either/both/all genders.
Pan people are far less likely to be put off someone because of any physical trait, including a lack of genitalia.
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
>
> Q2. Why is there no agreement in the LGTBQ community for a single, simple term to express this gender and sexual preference?
>
>
>
A2. Because the LGTBQ is not a single speech community, that's why.
A speech community -- a bunch of people who talk (mostly) with one another -- is where agreements on single terms take place subliminally, and they have already taken place in the various real speech communities that constitute the membership of a brand-new sociopolitical merger so diverse that we need a five-letter acronym for it.
All over the world there are local L,G,T,B, and Q speech communities (sometimes not formally united, or simply not socially connected, into LGTBQ. Yet.) And they have been there for a long time. Many speak English. They have their own speech terms and their own meanings to go with them and their own histories and mythologies. These things don't blend together coherently very fast, especially under social pressure.
So it's unlikely that there **are** -- or even could be -- any single, simple terms so early. At this stage of development the norm is evanescent pansemantic trans/meaning-fluid terms.
|
Regarding question 1:
I think it's a matter of carefully reading the definitions. Bisexual means to be attracted to both men and women. Pansexual means to be attracted to people regardless of sex or gender identity.
To illustrate the difference, let's use food (because it's more relatable). Suppose you like pizza and pasta specifically then you could say you like both of those foods (possibly for different reasons). You could also like pizza and pasta **because** they are Italian food, you don't care about their difference, the mere fact that it's Italian does it for you.
The first example could be compared to bisexuality, they like both men and woman, possibly for different reasons. The term pansexual emphasises that they like both without emphasis on the gender. Think of the statement 'I like all Italian food', if you consider pizza and pasta Italian, then you like both of the specific examples. Having said that, the first is a subset of the latter. All pansexuals are also bisexual, but not all bisexuals have to be pansexuals.
Regarding question 2:
You already mentioned the term community, which is a good start for an answer. The community, in this case, is not organised like a government with one view point. To compare it with politics: take conservatives in the UK, they have mostly the same view points and are pressured to follow the party line.
Now look at the broader community, all conservatives in the world, they you could identify many sub-communities (the Conservative Party in the UK, the Republicans in the US, and so on for all the different countries, perhaps even multiple communities for a single country). As an outsider, two conservatives are just two conservatives, but on closer inspection they might turn out to have widely varying views.
The same goes for the LGBTQ community (or any other group of people defined by one thing: men, women, Americans, politicians, environmentalists, liberals, children, the elderly). In fact, I think you'll have difficulty finding any subset of people defined by one thing who almost unanimously agree on anything (why that is might be better suited for psychology.se, biology.se, or philosophy.se but even then you might not get all of them to agree on one answer ;) ).
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
>
> Q2. Why is there no agreement in the LGTBQ community for a single, simple term to express this gender and sexual preference?
>
>
>
A2. Because the LGTBQ is not a single speech community, that's why.
A speech community -- a bunch of people who talk (mostly) with one another -- is where agreements on single terms take place subliminally, and they have already taken place in the various real speech communities that constitute the membership of a brand-new sociopolitical merger so diverse that we need a five-letter acronym for it.
All over the world there are local L,G,T,B, and Q speech communities (sometimes not formally united, or simply not socially connected, into LGTBQ. Yet.) And they have been there for a long time. Many speak English. They have their own speech terms and their own meanings to go with them and their own histories and mythologies. These things don't blend together coherently very fast, especially under social pressure.
So it's unlikely that there **are** -- or even could be -- any single, simple terms so early. At this stage of development the norm is evanescent pansemantic trans/meaning-fluid terms.
|
The difference between Pansexual and Bisexual can be explained like this.
Not all heterosexuals focus on lust when selecting a spouse. For some people, hetero, gay and pan, the emphasis is on being in love, and in a committed "forever" relationship. Many do not consumate their relationships sexually until vows are exchanged. People who are head over heels in love, may glimpse the Pan reality... Would you be less in love if your special darling was born a different gender?
By comparison, many people seek sexual relationships... or relationships that begin with sex. For these people, regardless of sexual orientation; desire, attraction and lust, are what it's all about. The physicality is important. Sometimes gender, colour, stature, size, clothing, muscle tone and even hairlessness can be some of the physical attributes that are judged in the selection of a partner. What prospective mates physically look like, is a huge priority. Bisexual people are sexually attracted to/by either/both/all genders.
Pan people are far less likely to be put off someone because of any physical trait, including a lack of genitalia.
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
The other answers are well-taken. To attempt a tl;dr:
>
> **Q1.** What *is* the difference between a bisexual and a pansexual?
>
>
>
The people? **Probably nothing**. But the difference between the ***terms*** '[bisexual](http://www.oed.com/view/Entry/19448)' and '[pansexual](http://www.oed.com/view/Entry/136944)' is that the former **implicitly assumes** two genders ('binary gender') or attraction to only two genders while the latter implies that there are more (possibly many more) than 'male' and 'female'. People who identify as pansexual may not have issues with bisexuals *per se* but probably consider their own terminology *more inclusive* of the [genderqueer](http://www.oed.com/view/Entry/77468?redirectedFrom=genderqueer#eid237081402).
>
> **Q2.** Why is there no agreement in the LGTBQ community for a single, simple term to express this gender and sexual preference?
>
>
>
**1st**, because people disagree about language choices *all the time* for no good reason at all. All the moreso when so many neologisms are dealing so closely with identity, sexuality, and politics. **2nd**, because 'the LGTBQ community' is *an expression*, not an actual gang that has regular conferences with a steering committee to hash out things in the interim. **3rd**, because those terms, especially as self-applied, are not precisely overlapping and do not imply a new set third gender but an openness to either conceiving of more than two or personally ignoring them, whatever and however many they are.
|
The difference between Pansexual and Bisexual can be explained like this.
Not all heterosexuals focus on lust when selecting a spouse. For some people, hetero, gay and pan, the emphasis is on being in love, and in a committed "forever" relationship. Many do not consumate their relationships sexually until vows are exchanged. People who are head over heels in love, may glimpse the Pan reality... Would you be less in love if your special darling was born a different gender?
By comparison, many people seek sexual relationships... or relationships that begin with sex. For these people, regardless of sexual orientation; desire, attraction and lust, are what it's all about. The physicality is important. Sometimes gender, colour, stature, size, clothing, muscle tone and even hairlessness can be some of the physical attributes that are judged in the selection of a partner. What prospective mates physically look like, is a huge priority. Bisexual people are sexually attracted to/by either/both/all genders.
Pan people are far less likely to be put off someone because of any physical trait, including a lack of genitalia.
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
Regarding question 1:
I think it's a matter of carefully reading the definitions. Bisexual means to be attracted to both men and women. Pansexual means to be attracted to people regardless of sex or gender identity.
To illustrate the difference, let's use food (because it's more relatable). Suppose you like pizza and pasta specifically then you could say you like both of those foods (possibly for different reasons). You could also like pizza and pasta **because** they are Italian food, you don't care about their difference, the mere fact that it's Italian does it for you.
The first example could be compared to bisexuality, they like both men and woman, possibly for different reasons. The term pansexual emphasises that they like both without emphasis on the gender. Think of the statement 'I like all Italian food', if you consider pizza and pasta Italian, then you like both of the specific examples. Having said that, the first is a subset of the latter. All pansexuals are also bisexual, but not all bisexuals have to be pansexuals.
Regarding question 2:
You already mentioned the term community, which is a good start for an answer. The community, in this case, is not organised like a government with one view point. To compare it with politics: take conservatives in the UK, they have mostly the same view points and are pressured to follow the party line.
Now look at the broader community, all conservatives in the world, they you could identify many sub-communities (the Conservative Party in the UK, the Republicans in the US, and so on for all the different countries, perhaps even multiple communities for a single country). As an outsider, two conservatives are just two conservatives, but on closer inspection they might turn out to have widely varying views.
The same goes for the LGBTQ community (or any other group of people defined by one thing: men, women, Americans, politicians, environmentalists, liberals, children, the elderly). In fact, I think you'll have difficulty finding any subset of people defined by one thing who almost unanimously agree on anything (why that is might be better suited for psychology.se, biology.se, or philosophy.se but even then you might not get all of them to agree on one answer ;) ).
|
The difference between Pansexual and Bisexual can be explained like this.
Not all heterosexuals focus on lust when selecting a spouse. For some people, hetero, gay and pan, the emphasis is on being in love, and in a committed "forever" relationship. Many do not consumate their relationships sexually until vows are exchanged. People who are head over heels in love, may glimpse the Pan reality... Would you be less in love if your special darling was born a different gender?
By comparison, many people seek sexual relationships... or relationships that begin with sex. For these people, regardless of sexual orientation; desire, attraction and lust, are what it's all about. The physicality is important. Sometimes gender, colour, stature, size, clothing, muscle tone and even hairlessness can be some of the physical attributes that are judged in the selection of a partner. What prospective mates physically look like, is a huge priority. Bisexual people are sexually attracted to/by either/both/all genders.
Pan people are far less likely to be put off someone because of any physical trait, including a lack of genitalia.
|
448,216
|
There's a risk of me potentially offending someone but I am an outsider trying to get to grips with this terminology. Online, I read someone who identified themself as a
>
> *pansexual trans/gender-fluid person*
>
>
>
I'd like to know if my understanding of the following terms is generally correct.
I just about get the difference between a *transsexual* and a *transgender*. The former is someone who has undergone a sex change that matches their personality and psychological identity, whereas a transgender does not necessarily have their sexual organs altered by surgery to match the sex they feel is theirs from birth.
I believe that a *gender fluid* person is someone who can fluctuate between feeling male or female, or they perceive to have the characteristics of both sexes within themselves and as such, they do not assign themselves a specific sex.
However, I'm not entirely sure what a pansexual is. Online research suggests it is someone who is sexually attracted and has sexual intercourse with either sex, i.e. male and female persons. But isn't that the same as a bisexual?
(*pansexual* in [Wikipedia](https://en.wikipedia.org/wiki/Pansexuality))
>
> **Pansexuality**, or omnisexuality, is the sexual, romantic or emotional attraction towards people regardless of their sex or gender identity. Pansexual people may refer to themselves as gender-blind, asserting that gender and sex are not determining factors in their romantic or sexual attraction to others.
>
>
>
And [Oxford Dictionaries](https://en.oxforddictionaries.com/definition/pansexual) define ***pansexual*** as
>
> *adjective*
>
> Not limited in sexual choice with regard to biological sex, gender, or gender identity.
>
>
>
The term *pansexual* has its origin in 1917 and is a compound of *pan-* meaning "all" and *-sexual*, of or related to sex.
Yet, the definition of the older term *[bisexual](https://www.etymonline.com/word/bisexual)*, first recorded in 1815–25 **but whose meaning of "attracted to both sexes" is from 1914**, is very similar to that of *pansexual*.
From [Dictionary.com](http://www.dictionary.com/browse/bisexual?s=t) and Oxford Dictionaries:
>
> **bisexual**
>
> noun 4. a person who is romantically or sexually attracted to both men and women, or to people of various gender identities; ambisexual.
>
>
>
***[bisexual](https://en.oxforddictionaries.com/definition/bisexual)***
>
> • *adjective* Sexually attracted not exclusively to people of one particular gender; attracted to both men and women.
>
> • *noun* A person who is sexually attracted not exclusively to people of one particular gender.
>
>
>
**Q 1.** What *is* the difference between a *bisexual* and a *pansexual*?
**Q 2.** I understand that the term *gender-fluid* was created for those who do not want to be defined as a man or woman, but *gender-fluid* has many derivatives: *agender*, *nongendered*, *genderless*, and *genderfree*. Why is there no agreement in the [LGTBQ](http://languageofinclusion.com/what-does-lbtbq-mean-the-l-q-of-lgtbq/) community for a single, simple term to express this gender and sexual preference?
|
2018/05/29
|
[
"https://english.stackexchange.com/questions/448216",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/44619/"
] |
* Bisexuality *sensu lato* (in the broad sense) means that one is sexually attracted to both males and females; it makes no distinction as to whether or not one is sexually attracted to persons who are neither male nor female.
+ Bisexuality *sensu stricto* (in the narrow sense) means that one is sexually attracted to males and females, but *not* to non-male non-female persons.
+ Pansexuality means that one is sexually attracted to persons of all genders.
If gender is regarded as a spectrum, with more possible values than just MALE and FEMALE, a pansexual person would be bisexual *senso lato*, due to being sexually attracted to both males and females, but would not be bisexual *senso stricto*, due to also being attracted to non-male non-females.
If gender is regarded as strictly binary, with the only possible values being MALE and FEMALE, the distinction between the two subcategories of bisexuality *sensu lato* disappears, and bisexuality and pansexuality become synonymous.
|
The difference between Pansexual and Bisexual can be explained like this.
Not all heterosexuals focus on lust when selecting a spouse. For some people, hetero, gay and pan, the emphasis is on being in love, and in a committed "forever" relationship. Many do not consumate their relationships sexually until vows are exchanged. People who are head over heels in love, may glimpse the Pan reality... Would you be less in love if your special darling was born a different gender?
By comparison, many people seek sexual relationships... or relationships that begin with sex. For these people, regardless of sexual orientation; desire, attraction and lust, are what it's all about. The physicality is important. Sometimes gender, colour, stature, size, clothing, muscle tone and even hairlessness can be some of the physical attributes that are judged in the selection of a partner. What prospective mates physically look like, is a huge priority. Bisexual people are sexually attracted to/by either/both/all genders.
Pan people are far less likely to be put off someone because of any physical trait, including a lack of genitalia.
|
46,159,310
|
I'm trying to format the footer of my app, and there are 3 things I want along the footer, all hyperlinks that I'd like on the same line.
```
<p><a href="mailto:me@myemail.com">© 2017 - My Name, Section 4</a>
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></p>
```
I'd like the About and Contact hyperlinks to align on the right side of the footer, like this.
[](https://i.stack.imgur.com/UTnvY.png)
But the code I wrote produces this:
[](https://i.stack.imgur.com/Ed53e.png)
I tried float and text-align but I may have done it incorrectly.
|
2017/09/11
|
[
"https://Stackoverflow.com/questions/46159310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7800355/"
] |
Just add a class and float it right with some padding:
<https://jsfiddle.net/cx5m40wu/>
```
<p><a href="mailto:me@myemail.com">© 2017 - My Name, Section 4</a>
<a asp-area="" asp-controller="Home" asp-action="Contact" class="alignRight">Contact</a>
<a asp-area="" asp-controller="Home" asp-action="About" class="alignRight">About</a></p>
.alignRight{
float: right;
padding-left: 15px;
}
```
|
I would recommend a different approach for the markup.
Use an `<ul>` (unordered list) inside a `<footer>` tag. Then, use `<li>` (list items) for each `<a>` anchor tag. This will be better for semantics and accessibility.
After having a proper HTML markup, you can proceed to style it with any method you like:
**Flexbox (recommended):**
```css
/* Unordered list */
.footer {
padding: 0;
margin: 0;
list-style-type: none;
display: flex;
}
/* List item */
.footer__item {
padding: 0 .5em;
}
/* Select the second item from last to first in case you add more items */
.footer__item:nth-last-child(2) {
margin-left: auto;
}
```
```html
<footer>
<ul class="footer">
<li class="footer__item">
<a href="mailto:me@myemail.com">© 2017 - My Name, Section 4</a>
</li>
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
</li>
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a>
</li>
</ul>
</footer>
```
**CSS Grid:**
```css
/* Unordered list */
.footer {
padding: 0;
margin: 0;
list-style-type: none;
display: grid;
grid-gap: 0 .5em;
grid-template-columns: repeat(3, auto);
}
/* Select the second item from last to first */
.footer__item:nth-last-child(2) {
margin-left: auto;
}
```
```html
<footer>
<ul class="footer">
<li class="footer__item">
<a href="mailto:me@myemail.com">© 2017 - My Name, Section 4</a>
</li>
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
</li>
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a>
</li>
</ul>
</footer>
```
**Floats:**
```css
/* Unordered lists */
.footer,
.footer__section {
padding: 0;
margin: 0;
list-style-type: none;
}
/* List item */
.footer__item {
float: left;
padding: 0 .5em;
}
/* Nested unordered list */
.footer__section {
float: right;
}
```
```html
<footer>
<ul class="footer">
<li class="footer__item">
<a href="mailto:me@myemail.com">© 2017 - My Name, Section 4</a>
</li>
<!-- Requires extra markup -->
<ul class="footer__section">
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
</li>
<li class="footer__item">
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a>
</li>
</ul>
</ul>
</footer>
```
|
46,159,310
|
I'm trying to format the footer of my app, and there are 3 things I want along the footer, all hyperlinks that I'd like on the same line.
```
<p><a href="mailto:me@myemail.com">© 2017 - My Name, Section 4</a>
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></p>
```
I'd like the About and Contact hyperlinks to align on the right side of the footer, like this.
[](https://i.stack.imgur.com/UTnvY.png)
But the code I wrote produces this:
[](https://i.stack.imgur.com/Ed53e.png)
I tried float and text-align but I may have done it incorrectly.
|
2017/09/11
|
[
"https://Stackoverflow.com/questions/46159310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7800355/"
] |
Just add a class and float it right with some padding:
<https://jsfiddle.net/cx5m40wu/>
```
<p><a href="mailto:me@myemail.com">© 2017 - My Name, Section 4</a>
<a asp-area="" asp-controller="Home" asp-action="Contact" class="alignRight">Contact</a>
<a asp-area="" asp-controller="Home" asp-action="About" class="alignRight">About</a></p>
.alignRight{
float: right;
padding-left: 15px;
}
```
|
Flexbox can do that:
```css
p {
display: flex;
}
p a:first-of-type {
margin-right: auto;
}
```
```html
<p><a href="mailto:me@myemail.com">© 2017 - My Name, Section 4</a>
<a asp-area="" asp-controller="Home" asp-action="About">About</a>
<a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></p>
```
|
20,897,236
|
So I am able to retrieve the images from instagram but I want the individual images to go into my gallery container div which I got a problem with. I have directed the images to the class "html5gallery" but the images does not goes in like other image urls :
```
<!-- Reference to html5gallery.js -->
<script type="text/javascript" src="../html5gallery/html5gallery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script>
(function ($) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
var imgURL = '';
for (var i = 0; i < numDisplay; i++) {
var gallery = document.getElementById("html5gallery");
var img = new Image();
img.onload = function() {
document.getElementById('gallery').appendChild(img);
};
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
alert(imgURL);
}
});
})(jQuery);
</script>
<div style="display:none;margin:0 auto; " class="html5gallery" data-skin="horizontal" data-width="1200" data-height="680" >
<!-- Add images to Gallery -->
<a href="#" onload="javascript:document.img.src='data.data[i].images.low_resolution.url'">
<a href="images/Tulip_large.jpg"><img src="images/Tulip_small.jpg" alt="Tulips"></a>
<a href="images/Colourful_Tulip_large.jpg"><img src="images/Colourful_Tulip_small.jpg" alt="Colourful Tulips"></a>
<a href="images/Swan_large.jpg"><img src="images/Swan_small.jpg" alt="Swan on Lake"></a>
<a href="images/Red_Tulip_large.jpg"><img src="images/Red_Tulip_small.jpg" alt="Red Tulips"></a>
<a href="images/Sakura_Tree_large.jpg"><img src="images/Sakura_Tree_small.jpg" alt="Sakura Trees"></a>
<a href="http://www.youtube.com/embed/1oHWvFrpocY?autoplay=1"><img src="http://img.youtube.com/vi/1oHWvFrpocY/2.jpg" alt="Youtube Video"> </a>
<!-- Add Youtube video to Gallery -->
<a href="http://www.youtube.com/embed/ofr5EE9GsUs?autoplay=1"><img src="http://img.youtube.com/vi/ofr5EE9GsUs/2.jpg" alt="Youtube Video"></a>
<!-- Add Youtube video to Gallery -->
<a href="http://www.youtube.com/embed/9bZkp7q19f0?autoplay=1"><img src="http://img.youtube.com/vi/9bZkp7q19f0/2.jpg" alt="Youtube Video"></a>
</div>
```
|
2014/01/03
|
[
"https://Stackoverflow.com/questions/20897236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3152558/"
] |
Change the class attribute to id or add the id attribute `id="html5gallery"`
```
<div style="display:none;margin:0 auto; "
class="html5gallery" id="html5gallery"
data-skin="horizontal" data-width="1200"
data-height="680" >
```
**EDIT:**
Try this to append image
```
var imgURL = '';
var gallery = $("#html5gallery");
for (var i = 0; i < numDisplay; i++) {
var img = new Image();
img.onload = (function(im) {
return function () {
gallery.append(im);
}
})(img);
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
```
|
I've never used the instagram API before, but I think this is what you want to achieve (code below). I've included both a Vanilla Javascript method as well as a jQuery method (so you can pick and use whichever one you prefer - vanilla is faster of course)
```
(function ($, window) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
// Define the gallery variable outside the for loop (performance)
// Vanilla JS
var galleryHTML = document.getElementById("html5gallery");
// jQuery
var $galleryHTML = $('#html5gallery');
// Moved the gallery outside of the for loop (performance, again)
var gallery = document.getElementById('gallery');
var insta = $('.insta');
// or var insta = document.getElementsByClassName('insta')[0] for vanilla JS
// create a function to do the fancy ajax
var fetchInstagram = function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
for (var i = 0; i < numDisplay; i++) {
// I don't think you need the onload function here
// img.onload = function() {
// document.getElementById('gallery').appendChild(img);
// };
// Not sure what this is, but I don't think you need it (for what you want to do)
// $(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
// Create the new image object
var newImage = document.createElement('img');
newImage.src = data.data[i].images.low_resolution.url;
// Insert the images into html5gallery
// Vanilla Javascript Way
// galleryHTML.appendChild(newImage);
// jQuery Way
// var $newImage = $(newImage);
// $galleryHTML.append($newImage);
}
}
});
};
// Making the function available in window for global use
window.fetchInstagram = fetchInstagram;
})(jQuery, window);
// Initiate the function
fetchInstagram();
// You can bind the function to other stuff like.. if you click a button
// $('#load-more').on('click', fetchInstagram);
```
I was able to get the 4 images to load in a div with the id of html5gallery on my end. Hope this helps!
|
20,897,236
|
So I am able to retrieve the images from instagram but I want the individual images to go into my gallery container div which I got a problem with. I have directed the images to the class "html5gallery" but the images does not goes in like other image urls :
```
<!-- Reference to html5gallery.js -->
<script type="text/javascript" src="../html5gallery/html5gallery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script>
(function ($) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
var imgURL = '';
for (var i = 0; i < numDisplay; i++) {
var gallery = document.getElementById("html5gallery");
var img = new Image();
img.onload = function() {
document.getElementById('gallery').appendChild(img);
};
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
alert(imgURL);
}
});
})(jQuery);
</script>
<div style="display:none;margin:0 auto; " class="html5gallery" data-skin="horizontal" data-width="1200" data-height="680" >
<!-- Add images to Gallery -->
<a href="#" onload="javascript:document.img.src='data.data[i].images.low_resolution.url'">
<a href="images/Tulip_large.jpg"><img src="images/Tulip_small.jpg" alt="Tulips"></a>
<a href="images/Colourful_Tulip_large.jpg"><img src="images/Colourful_Tulip_small.jpg" alt="Colourful Tulips"></a>
<a href="images/Swan_large.jpg"><img src="images/Swan_small.jpg" alt="Swan on Lake"></a>
<a href="images/Red_Tulip_large.jpg"><img src="images/Red_Tulip_small.jpg" alt="Red Tulips"></a>
<a href="images/Sakura_Tree_large.jpg"><img src="images/Sakura_Tree_small.jpg" alt="Sakura Trees"></a>
<a href="http://www.youtube.com/embed/1oHWvFrpocY?autoplay=1"><img src="http://img.youtube.com/vi/1oHWvFrpocY/2.jpg" alt="Youtube Video"> </a>
<!-- Add Youtube video to Gallery -->
<a href="http://www.youtube.com/embed/ofr5EE9GsUs?autoplay=1"><img src="http://img.youtube.com/vi/ofr5EE9GsUs/2.jpg" alt="Youtube Video"></a>
<!-- Add Youtube video to Gallery -->
<a href="http://www.youtube.com/embed/9bZkp7q19f0?autoplay=1"><img src="http://img.youtube.com/vi/9bZkp7q19f0/2.jpg" alt="Youtube Video"></a>
</div>
```
|
2014/01/03
|
[
"https://Stackoverflow.com/questions/20897236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3152558/"
] |
Change the class attribute to id or add the id attribute `id="html5gallery"`
```
<div style="display:none;margin:0 auto; "
class="html5gallery" id="html5gallery"
data-skin="horizontal" data-width="1200"
data-height="680" >
```
**EDIT:**
Try this to append image
```
var imgURL = '';
var gallery = $("#html5gallery");
for (var i = 0; i < numDisplay; i++) {
var img = new Image();
img.onload = (function(im) {
return function () {
gallery.append(im);
}
})(img);
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
```
|
If the human eye can only see 24fps or 30fps or more when playing a game or watching tv, I believe a programer can use less DIVs in HTML within the screen size, with a Javascript array of 3 million colors for a couple of DIVs and cheat it's position(because of our human eyes), based in a timer event with a bunch of frames per second than the ones I mentioned, example 1 millisecond. In my opinion this is something which I would like to test, if it's the question that drives us let the answer be our destination.
This is the fiddle so far: [DEMO](http://jsfiddle.net/jobson111/h6FPX/)
```
<html>
<head>
<title></title>
<style>#placeDiv{position:absolute;left:0px;width:100px;height:100px;}
#placeDiv1{position:absolute;left:100px;width:100px;height:100px;}
#placeDiv2{position:absolute;left:200px;width:100px;height:100px;}
#b1{position:absolute;top:100px;left:0px}
#b2{position:absolute;top:100px;left:80px}
#b3{position:absolute;top:100px;left:170px}
#b4{position:absolute;top:100px;left:270px}
#b5{position:absolute;top:100px;left:320px}
</style>
</head>
<body>
<div id = "placeDiv">ok</div><div id = "placeDiv1">ok</div><div id = "placeDiv2">ok</div>
<button id="b1" onclick="forward()">Forward</button>
<button id="b2" onclick="backward()">Backward</button>
<button id="b3" onclick="skip2()">skip2</button>
<button id="b4" onclick="automatic()">auto</button>
<button id="b5" onclick="stop()">stop</button>
<script>
var myArray = ["black","yellow","green","red","blue","blue","black","gray"];
var myArray1 = ["yellow","blue","green","red","green","blue","black","gray"];
var myArray2 = ["yellow","blue","green","red","green","blue","black","gray"];
var i = 0;
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
forward=function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
}; skip2=function(){
if(i == myArray.length-4)
{i+=2;alert("This is the iterator "+i)}else if(i==7){i=0}else{i=i+1;};
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
};
backward=function(){
if(i == 0)
{i=myArray.length-1;i=myArray1.length-1;}
else
{
i=i-1;
}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
//
}
var m=null;
automatic=function(){
clearInterval(m)
m = setInterval(function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
},1);
function b(x,y){
var a =setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if (x==100){d();clearInterval(a);}},10);
function d(){var z = setInterval(function(){document.getElementById("placeDiv").style.left=x--+"px";if (x==0){c();clearInterval(z);}},10);}
function c(){var g = setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if(x==100){d();clearInterval(g)}},10)};
//Aqui uma copia.
var v =setInterval(function(){document.getElementById("placeDiv").style.top=y+++"px";if (y==100){h();clearInterval(v);}},10);
function h(){var l = setInterval(function( {document.getElementById("placeDiv").style.top=y--+"px";if (y==0){ok();clearInterval(l);}},10);}
function ok(){var ja = setInterval(function( {document.getElementById("placeDiv").style.top=y+++"px";if(y==100 {h();clearInterval(ja)}},10)};
}
b(0,0);
stop=function(){clearInterval(m)};
};
</script>
</body>
</html>
```
|
248,161
|
Let $z\_1 , z\_2 $ be two complex numbers that satisfy:
$\dfrac{z\_2 } {\bar{z\_1}}= \frac{3}{8} \big(\cos(75^{\circ})+i\sin(75^{\circ})\big) $ ,
$z\_1 z\_2 ^2 = \frac{1}{3} \big(\cos(120^{\circ}) + i\sin(120^{\circ}) \big) $ .
How can I determine with of the following can be a possible value for $ \sqrt{z\_1} $ ?
(a) $ \frac{2}{\sqrt{3}} \mbox{cis}(135^{\circ}) $
(b) $ \frac{2}{3} \mbox{cis}(155^{\circ})$
(c) $ \frac{2}{\sqrt{3}} \mbox{cis}(195^{\circ}) $
(d) $ \frac{2}{\sqrt{3}} \mbox{cis}(175^{\circ}) $
(e) $ \frac{2}{3} \mbox{cis}(215^{\circ})$
thanks !!!
|
2012/11/30
|
[
"https://math.stackexchange.com/questions/248161",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/50436/"
] |
Assuming that each week is independent, we know that if $N$ is the number of employees taken on in a particular week, then $N$ has distribution:
$P(N=k) = e^{-0.1} \frac{0.1^k}{k!}$
So that,
$p:=P(N=0)=e^{-0.1}$,
which I'm calling $p$. Now, assuming we have an unlimited number of weeks, how can we not take on employees for exactly $Y$ weeks, no more no less.? Well we have to not take on employees for each week, a total of $Y$ weeks, but then take on at least one employee on the $Y+1$ week. The probability that we have 0 employees after $Y$ weeks is simply:
$P(\mbox{no employees after }Y\mbox{ weeks})=P(N=0)^Y=p^Y$
and the probability that we take on at least one employee on the $Y+1$ week is $1-P(N=0)=1-p$, so
$P(Y=n)=p^n(1-p)$
which is a geometric random variable, so that
$E(Y) = p/(1-p)$
|
Alex has answered part of the question.
The probability that more than one new employee is hired in a given week is $1$ minus the probability that only $0$ or $1$ new employees are hired. Thus it is
$$
1- \frac{0.1^0 e^{-0.1}}{0!} - \frac{0.1^1 e^{-0.1}}{1!} = 1 - e^{-0.1} - 0.1e^{-0.1}.
$$
Call this number $p$. Then we're looking for the probability of $1$ success in $50$ trials with probability $p$ of success on each trial --- thus a binomial distribution. The probability is
$$
\binom{50}{1} p^1 (1-p)^{50-1}.
$$
|
2,484,538
|
Let $A$ and $B$ from $M\_n(\mathbb{R})$ with $AB=BA$ and $\det(A+B) \geq 0$
Prove that $ \forall n \in \mathbb{N^{\*}} $, $\det (A^n + B^n) \geq 0 $
---
I tried to use induction but I got stuck.
|
2017/10/22
|
[
"https://math.stackexchange.com/questions/2484538",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/201437/"
] |
HINT:
You could use complex numbers. Consider the factorization
$$(X^n + 1) = \prod\_{\omega^n +1 = 0}( X- \omega)$$
The roots of the equation $X^n+1 = 0$ are complex, distinct, and conjugate in pairs, if $n$ is even, or $-1$, and $\frac{n-1}{2}$ pairs of conjugate roots, if $n$ is odd.
Since $A$, $B$ commute, we can write the equality in $M\_n(\mathbb{C})$
$$A^n + B^n = \prod\_{\omega^n + 1 = 0} (A - \omega B)$$
For $n$ even we get
$$A^n + B^n = \prod\_{\omega^n + 1= 0, \Re \omega >0}( A - \omega B) (A - \bar \omega B)$$ while for $n$ odd we get
$$A^n + B^n = (A+B) \cdot \prod\_{\omega^n + 1= 0, \Re \omega >0}( A - \omega B) (A - \bar \omega B)$$
Now take determinants and notice that
$$\det(A- \omega B) \det (A- \bar \omega B) = |\det(A- \omega B)|^2 \ge 0$$
|
Ok, I really like the answer by orangeskid.
However, I want to understand the solution outlined by Giuseppe Negro.
As he already noted, commuting diagonalizable matrices are simultaneously diagonalizable. So let us assume that $A=diag(a\_1, a\_2, \ldots a\_n)$ and $B=diag(b\_1, b\_2, \ldots b\_n)$. Then $$\det(A+B)=\prod\_{i=1}^n (a\_i+b\_i)$$ and $$\det(A^k+B^k)=\prod\_{i=1}^n (a\_i^k+b\_i^k)$$
So we have to prove that $\prod\_{i=1}^n (a\_i+b\_i) \geq0 $ implies $\prod\_{i=1}^n (a\_i^k+b\_i^k) \geq 0$.
If $n$ is even this is true for any $a\_i$ and $b\_i$ even without the assumption since any even power is non-negative.
If $n$ is odd then consider two cases. If $a\_i+b\_i =0$ for some k, then $a\_i^k+b\_i^k=0$ as well, so the implication is true. Let us consider case when $a\_i+b\_i \neq 0$ for any $i$. It is suffice to prove that $a\_i+b\_i$ have the same sign as $a\_i^k+b\_i^k$. If $a\_i$ and $b\_i$ have the same sign it is clear. If they have different signs then the sign of a sum is determined by maximum absolute value of a summands.
**Ok, how should we continue to get full solution?**
I have some very vague ideas about density, Zariski topology, and the fact that value of continuous (and thus polynomial) function is determined by its values on a dense subset, but I do not see if it is a good path.
First of all, I can prove that diagonalisable matrixes are dense it $M\_n(\mathbb{C})$, but I can not do it for $M\_n(\mathbb{R})$. Is it even true for $M\_n(\mathbb{R})$?
Second, we have the inequality and not the polynomial identity.
So please help me to finish the solution, I hope it will be useful for learning community.
Thanks a lot!!!
**Update**
I am able to prove that diagonalisable matrixes are **not** dense it $M\_n(\mathbb{R})$, so now this approach does not look promising, so please post your ideas!
|
878,022
|
I have the following data structure:
```
typedef vector< vector<int> > MxInt2d;
typedef vector< vector<double> > MxDouble2d;
class QSweep{
public:
....
static MxDouble2d myPoints_;
MxInt2d myEdges_;
MxInt2d sweepEvents;
class order{
public:
bool operator() (const vector<int>& edge1, const vector<int>& edge2){
return (myPoints_[edge1[0]][0]<myPoints_[edge2[0]][0])||
(myPoints_[edge1[0]][0]==myPoints_[edge2[0]][0]&&
myPoints_[edge1[0]][1]<myPoints_[edge2[0]][1])
||
(myPoints_[edge1[0]][0]==myPoints_[edge2[0]][0]&&
myPoints_[edge1[0]][1]==myPoints_[edge2[0]][1]&&
getSlope(myPoints_[edge1[0]][0],myPoints_[edge1[0][1],
myPoints_[edge1[1]][0],myPoints_[edge1[1]][1])
<
getSlope(myPoints_[edge2[0][0],myPoints_[edge2[0][1],
myPoints_[edge2[1]][0],myPoints_[edge2[1]][1]));
}
};
static double getSlope(double a, double b, double c, double d);
static double computeDet(double a, double b, double c, double d, double x, double y);
```
};
I use the functor for order() when defining the constructor in the following way:
```
QSweep::QSweep(const MxDouble2d& myPoints, const MxInt2d& myEdges){
....
//code here for initializing myPoints_, myEdges_
sort(myEdges_.begin(),myEdges_.end(),order());
}
```
In this way my data myEdges\_ are arranged when initialized using the functor order().
Now I want to arrange the data sweepEvents (which has the same type as myEdges\_ using the predefined data type from C++ vector) using a totally different criteria, that is I do not want to use the function getSlope(...) but the function computeDet(...) for sweepEvents.
So I was thinking I still need other functor for redefining the < of sort() for the vector data type right? So I would have to write a new functor order1() in which I use the data computed with computeDet(...) and then I call the sort on my sweepEvents data types:
```
sort(sweepEvents.begin(),sweepEvents.end(),order1());
```
I am not sure if this is the good solution? can I redefine in several ways < if I use different names for the functor?
Is someone has some suggestions I would be really grateful.
Thank you in advance,
madalina
No the two functors does not use any common code.
I have written the second functor insede the QSweep class as this:
```
class orderDet{
public:
bool operator() (const vector<int>& edgeSW1, const vector<int>& edgeSW2
,const vector<int>& edgeC){
return
(
computeDet(myPoints_[edgeSW1[0]],myPoints_[edgeSW1[1]],myPoints_[edgeC[0]])
<
computeDet(myPoints_[edgeSW2[0]],myPoints_[edgeSW2[1]],myPoints_[edgeC[0]])
);
}}
```
and I called it like:
```
sort(sweepEvents.begin(), sweepEvents.end(), orderDet());
```
But I got the following compilation error:
```
error: no match for call to '(QSweepComplete::orderDet) (std::vector<int,
std::allocator<int> >&, std::vector<int, std::allocator<int> >&)'
./QSweepComplete.h:68: note: candidates are: bool
QSweepComplete::orderDet::operator()(const std::vector<int, std::allocator<int>>&,
const std::vector<int, std::allocator<int> >&, const std::vector<int,
std::allocator<int> >&)
```
I am guessing the parameter do not match, as the third parameter of orderDet(...., edgeC) is not part of sweepEvents list as the others are but is part of the variable myEdges\_...
Maybe one can give me some suggestions on how to implement this functor?
thank you in advance.
best wishes,
madalina
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82475/"
] |
If you have 2 different criteria for sorting then you should have 2 different functors.
Give them meaningful names such as:
OrderBySlopes and OrderByXYZ
If the 2 functors use some common code, you can refactor this out. i.e. into a base class
|
What [Glen](https://stackoverflow.com/questions/878022/several-functors-for-redefining-order-for-sort-function-of-vector/878046#878046) said.
If you really really insist on having one function do double duty, you can rely on having different parameter types to overload two versions of operator().
|
878,022
|
I have the following data structure:
```
typedef vector< vector<int> > MxInt2d;
typedef vector< vector<double> > MxDouble2d;
class QSweep{
public:
....
static MxDouble2d myPoints_;
MxInt2d myEdges_;
MxInt2d sweepEvents;
class order{
public:
bool operator() (const vector<int>& edge1, const vector<int>& edge2){
return (myPoints_[edge1[0]][0]<myPoints_[edge2[0]][0])||
(myPoints_[edge1[0]][0]==myPoints_[edge2[0]][0]&&
myPoints_[edge1[0]][1]<myPoints_[edge2[0]][1])
||
(myPoints_[edge1[0]][0]==myPoints_[edge2[0]][0]&&
myPoints_[edge1[0]][1]==myPoints_[edge2[0]][1]&&
getSlope(myPoints_[edge1[0]][0],myPoints_[edge1[0][1],
myPoints_[edge1[1]][0],myPoints_[edge1[1]][1])
<
getSlope(myPoints_[edge2[0][0],myPoints_[edge2[0][1],
myPoints_[edge2[1]][0],myPoints_[edge2[1]][1]));
}
};
static double getSlope(double a, double b, double c, double d);
static double computeDet(double a, double b, double c, double d, double x, double y);
```
};
I use the functor for order() when defining the constructor in the following way:
```
QSweep::QSweep(const MxDouble2d& myPoints, const MxInt2d& myEdges){
....
//code here for initializing myPoints_, myEdges_
sort(myEdges_.begin(),myEdges_.end(),order());
}
```
In this way my data myEdges\_ are arranged when initialized using the functor order().
Now I want to arrange the data sweepEvents (which has the same type as myEdges\_ using the predefined data type from C++ vector) using a totally different criteria, that is I do not want to use the function getSlope(...) but the function computeDet(...) for sweepEvents.
So I was thinking I still need other functor for redefining the < of sort() for the vector data type right? So I would have to write a new functor order1() in which I use the data computed with computeDet(...) and then I call the sort on my sweepEvents data types:
```
sort(sweepEvents.begin(),sweepEvents.end(),order1());
```
I am not sure if this is the good solution? can I redefine in several ways < if I use different names for the functor?
Is someone has some suggestions I would be really grateful.
Thank you in advance,
madalina
No the two functors does not use any common code.
I have written the second functor insede the QSweep class as this:
```
class orderDet{
public:
bool operator() (const vector<int>& edgeSW1, const vector<int>& edgeSW2
,const vector<int>& edgeC){
return
(
computeDet(myPoints_[edgeSW1[0]],myPoints_[edgeSW1[1]],myPoints_[edgeC[0]])
<
computeDet(myPoints_[edgeSW2[0]],myPoints_[edgeSW2[1]],myPoints_[edgeC[0]])
);
}}
```
and I called it like:
```
sort(sweepEvents.begin(), sweepEvents.end(), orderDet());
```
But I got the following compilation error:
```
error: no match for call to '(QSweepComplete::orderDet) (std::vector<int,
std::allocator<int> >&, std::vector<int, std::allocator<int> >&)'
./QSweepComplete.h:68: note: candidates are: bool
QSweepComplete::orderDet::operator()(const std::vector<int, std::allocator<int>>&,
const std::vector<int, std::allocator<int> >&, const std::vector<int,
std::allocator<int> >&)
```
I am guessing the parameter do not match, as the third parameter of orderDet(...., edgeC) is not part of sweepEvents list as the others are but is part of the variable myEdges\_...
Maybe one can give me some suggestions on how to implement this functor?
thank you in advance.
best wishes,
madalina
|
2009/05/18
|
[
"https://Stackoverflow.com/questions/878022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82475/"
] |
If you have 2 different criteria for sorting then you should have 2 different functors.
Give them meaningful names such as:
OrderBySlopes and OrderByXYZ
If the 2 functors use some common code, you can refactor this out. i.e. into a base class
|
Your `orderDet::operator()` takes three arguments. The `std::sort` wants only two to compare two values.
A solution may be to add the edges vector as a member of your functor:
```
struct orderDet {
const vector<int>& edges;
orderDet( const vector<int>& edges ):edges(edges){};
bool operator()( const vector<int>& v1, const vector<int>& v2 ) const {
....
}
};
```
By the way, if you want people to understand your code when they read it, I rather think you should use a typedef for your inner vector than for the outer one.
Next to that, it's better to define a struct containing a 'first' and 'second' point, than a very generic vector which you use only the first two points of. It will make your code more readable, too.
Regards.
|
49,020,629
|
I have:
```
a = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
b = [['-'] * 3] * 3 # => [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
a == b #=> true
```
Seems correct.
```
a[0][0] = 'X'
a # => [["X", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
b[0][0] = 'X'
b # => [["X", "-", "-"], ["X", "-", "-"], ["X", "-", "-"]]
a == b # => false
```
What? Why does `b[0][0] = 'X'` change values in three places?
I also found it doesn't work this way:
```
b = [%w[- - -]] * 3 # => [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
b[0][0] = 'X'
b # => [["X", "-", "-"], ["X", "-", "-"], ["X", "-", "-"]]
```
|
2018/02/28
|
[
"https://Stackoverflow.com/questions/49020629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236353/"
] |
This:
```
[object]*3
```
will create an array with 3 references to the same object so changing one of them changes all of them like this:
```
a = [[1]]*3 #=> [[1], [1], [1]]
a[0][0] = 2 #=> [[2], [2], [2]]
```
If you wish to create an array of length 3 with 3 different objects, do this:
```
a = 3.times.map {[1]} #=> [[1], [1], [1]]
a[0][0] = 2 #=> [[2], [1], [1]]
```
|
I found it has to be done this way:
```
irb(main):001:0> b = Array.new(3) { Array.new(3) { '-' } }
=> [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
irb(main):002:0> b[0][0] = 'X'
=> "X"
irb(main):003:0> b
=> [["X", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
```
|
49,020,629
|
I have:
```
a = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
b = [['-'] * 3] * 3 # => [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
a == b #=> true
```
Seems correct.
```
a[0][0] = 'X'
a # => [["X", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
b[0][0] = 'X'
b # => [["X", "-", "-"], ["X", "-", "-"], ["X", "-", "-"]]
a == b # => false
```
What? Why does `b[0][0] = 'X'` change values in three places?
I also found it doesn't work this way:
```
b = [%w[- - -]] * 3 # => [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
b[0][0] = 'X'
b # => [["X", "-", "-"], ["X", "-", "-"], ["X", "-", "-"]]
```
|
2018/02/28
|
[
"https://Stackoverflow.com/questions/49020629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236353/"
] |
This:
```
[object]*3
```
will create an array with 3 references to the same object so changing one of them changes all of them like this:
```
a = [[1]]*3 #=> [[1], [1], [1]]
a[0][0] = 2 #=> [[2], [2], [2]]
```
If you wish to create an array of length 3 with 3 different objects, do this:
```
a = 3.times.map {[1]} #=> [[1], [1], [1]]
a[0][0] = 2 #=> [[2], [1], [1]]
```
|
The first initialization you created 3 arrays nested in 1.
```
a = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
# [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
# ARRAY a ARRAY b ARRAY c
```
The second initialization you created 1 array, and then pointed the same array 3 times.
```
b = [['-'] * 3] * 3
# [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
# ARRAY x ARRAY x ARRAY x
```
Thinking in this way if you change b[0][0] is going to alter only one array, however you can have the impression that is changing more arrays because it's being referenced many times.
You can check it by yourself printing the addresses of them.
```
puts a[0].object_id # 47369457807480
puts a[1].object_id # 47369457807320
puts a[2].object_id # 47369457807200
puts b[0].object_id # 47369457807070
puts b[1].object_id # 47369457807070
puts b[2].object_id # 47369457807070
```
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
Just add @JvmStatic annotation above field (as said in this documentation <https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields>)
So, your code should be like this:
```
class SingleKotlin private constructor(){
companion object {
@JvmStatic
val instance by lazy {
SingleKotlin()
}
}
}
```
And now you can call it like
```
SingleKotlin.instance
```
|
In addition to [@YuriiKyrylchuk](https://stackoverflow.com/users/2793494/yurii-kyrylchuk)'s answer: another option (and the only option if you don't have control over the Kotlin code) is to refer to `MyClass.Companion` from Java. Example:
```
class MyClass {
companion object {
val x: Int = 0
}
}
```
And in Java:
```
MyClass.Companion.getX();
```
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
Just add @JvmStatic annotation above field (as said in this documentation <https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields>)
So, your code should be like this:
```
class SingleKotlin private constructor(){
companion object {
@JvmStatic
val instance by lazy {
SingleKotlin()
}
}
}
```
And now you can call it like
```
SingleKotlin.instance
```
|
If your `SingleKotlin` object has a single private constructor without parameters, you can use `object` instead:
```
object SingleKotlin {
// some members of SingleKotlin
val x = 42
}
```
Then in Java you reference it through the `INSTANCE` static field:
```
SingleKotlin single = SingleKotlin.INSTANCE;
// or
SingleKotlin.INSTANCE.getX();
```
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
Just add @JvmStatic annotation above field (as said in this documentation <https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields>)
So, your code should be like this:
```
class SingleKotlin private constructor(){
companion object {
@JvmStatic
val instance by lazy {
SingleKotlin()
}
}
}
```
And now you can call it like
```
SingleKotlin.instance
```
|
You need to call the method from Java like this:
`AppUIUtils.Companion.yourMethod()`
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
Just add @JvmStatic annotation above field (as said in this documentation <https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields>)
So, your code should be like this:
```
class SingleKotlin private constructor(){
companion object {
@JvmStatic
val instance by lazy {
SingleKotlin()
}
}
}
```
And now you can call it like
```
SingleKotlin.instance
```
|
In additional to Ilya answer you can use @JvmStatic annotation
```
object SingleKotlin {
// some members of SingleKotlin
@JvmStatic val x = 42
}
```
Then in Java
```
SingleKotlin.getX();
```
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
In addition to [@YuriiKyrylchuk](https://stackoverflow.com/users/2793494/yurii-kyrylchuk)'s answer: another option (and the only option if you don't have control over the Kotlin code) is to refer to `MyClass.Companion` from Java. Example:
```
class MyClass {
companion object {
val x: Int = 0
}
}
```
And in Java:
```
MyClass.Companion.getX();
```
|
You need to call the method from Java like this:
`AppUIUtils.Companion.yourMethod()`
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
In addition to [@YuriiKyrylchuk](https://stackoverflow.com/users/2793494/yurii-kyrylchuk)'s answer: another option (and the only option if you don't have control over the Kotlin code) is to refer to `MyClass.Companion` from Java. Example:
```
class MyClass {
companion object {
val x: Int = 0
}
}
```
And in Java:
```
MyClass.Companion.getX();
```
|
In additional to Ilya answer you can use @JvmStatic annotation
```
object SingleKotlin {
// some members of SingleKotlin
@JvmStatic val x = 42
}
```
Then in Java
```
SingleKotlin.getX();
```
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
If your `SingleKotlin` object has a single private constructor without parameters, you can use `object` instead:
```
object SingleKotlin {
// some members of SingleKotlin
val x = 42
}
```
Then in Java you reference it through the `INSTANCE` static field:
```
SingleKotlin single = SingleKotlin.INSTANCE;
// or
SingleKotlin.INSTANCE.getX();
```
|
You need to call the method from Java like this:
`AppUIUtils.Companion.yourMethod()`
|
41,860,373
|
I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files
```
class SingleKotlin private constructor(){
companion object {
val instance by lazy {
SingleKotlin()
}
}
}
```
However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance'
I don't understand why, anybody can explian and how can I solve this problem?
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41860373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3239558/"
] |
If your `SingleKotlin` object has a single private constructor without parameters, you can use `object` instead:
```
object SingleKotlin {
// some members of SingleKotlin
val x = 42
}
```
Then in Java you reference it through the `INSTANCE` static field:
```
SingleKotlin single = SingleKotlin.INSTANCE;
// or
SingleKotlin.INSTANCE.getX();
```
|
In additional to Ilya answer you can use @JvmStatic annotation
```
object SingleKotlin {
// some members of SingleKotlin
@JvmStatic val x = 42
}
```
Then in Java
```
SingleKotlin.getX();
```
|
19,321,047
|
I am using this query:
```
SELECT ts as "TimeStamp",
stat as "Status"
FROM myTable
WHERE stat = 'O'
AND source = 'Source1'
AND ts BETWEEN TO_TIMESTAMP('2013-10-05','yyyy-mm-dd') AND
TO_TIMESTAMP('2013-10-06','yyyy-mm-dd')
```
And also tried:
```
SELECT ts as "TimeStamp",
stat as "Status"
FROM myTable
WHERE stat = 'O'
AND source = 'Source1'
AND ts >= TO_TIMESTAMP('2013-10-05','yyyy-mm-dd') AND ts <
TO_TIMESTAMP('2013-10-06','yyyy-mm-dd')
```
It returns 0 records, but if I do
```
SELECT ts as "TimeStamp",
stat as "Status"
FROM myTable
WHERE stat = 'O'
```
I can clearly identify 5 records. Apparently the `TO_TIMESTAMP` is not working properly I am hoping someone might be able to help identify the proper fix
**Edit: To clarify, I only want the timeframe for 10/5 not including 10/6**
Sorry pasted wrong results
Also the field is of type TIMESTAMP(6)
|
2013/10/11
|
[
"https://Stackoverflow.com/questions/19321047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1342249/"
] |
Because the TO time stamp has time even though you're not specifying. So it is selecting only up to the very beginning of the lat day. Either specify time 23:59:59 and subseconds as required, or do less than the next day.
```
...
AND ts >= TO_TIMESTAMP('2013-10-05','yyyy-mm-dd')
AND ts < TO_TIMESTAMP('2013-10-07','yyyy-mm-dd')
```
|
Try:
AND ts BETWEEN TO\_DATE('2013-10-05','YYYY-MM-DD') AND
TO\_DATE('2013-10-06','YYYY-MM-DD')
And mind that it will get you results from the 10-05 at 00:00:00 to the 10-06 at 00:00:00 If you don't specify the HH MI SS mask.
Date masks are case sensitivve and TO\_DATE will work better.
|
55,785,574
|
I want to assign the total number of rows to a variable named **"@row\_count"**.
```
DECLARE @row_count int
SET @row_count = SELECT COUNT(*) FROM information
```
I know. I'm doing **wrong**. But I haven't found anything on how to do it.
---
I want to do something like that:
```
CREATE PROC add_person
(
@id tinyint,
@name nvarchar(max),
@surname nvarchar(max),
@salary int,
@job nvarchar(max)
)
AS
BEGIN
INSERT INTO information
VALUES(@id,@name,@surname,@salary,@job)
END
DECLARE @row_count nvarchar(max)
SET @row_count = SELECT COUNT(*) FROM information
BEGIN TRAN
add_person 34,'asdf','asdf',3000,'asdf'
IF @row_count > 33
ROLLBACK TRAN
ELSE
COMMIT TRAN
GO;
```
**My goal:** to prevent the addition of new people if the number of people exceeds thirty-four.
|
2019/04/21
|
[
"https://Stackoverflow.com/questions/55785574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
It's not possible to blur other apps in the background.
<https://www.electronjs.org/docs/api/frameless-window#limitations>
>
> The blur filter only applies to the web page, so there is no way to
> apply blur effect to the content below the window (i.e. other
> applications open on the user's system).
>
>
>
|
Electron does not allow you to blur on anything running behind it. It only allows you to blur the content on your webpage/app. Anything in your css styling will only be applied to the foreground contents. I know because I too have tried and failed.
|
55,785,574
|
I want to assign the total number of rows to a variable named **"@row\_count"**.
```
DECLARE @row_count int
SET @row_count = SELECT COUNT(*) FROM information
```
I know. I'm doing **wrong**. But I haven't found anything on how to do it.
---
I want to do something like that:
```
CREATE PROC add_person
(
@id tinyint,
@name nvarchar(max),
@surname nvarchar(max),
@salary int,
@job nvarchar(max)
)
AS
BEGIN
INSERT INTO information
VALUES(@id,@name,@surname,@salary,@job)
END
DECLARE @row_count nvarchar(max)
SET @row_count = SELECT COUNT(*) FROM information
BEGIN TRAN
add_person 34,'asdf','asdf',3000,'asdf'
IF @row_count > 33
ROLLBACK TRAN
ELSE
COMMIT TRAN
GO;
```
**My goal:** to prevent the addition of new people if the number of people exceeds thirty-four.
|
2019/04/21
|
[
"https://Stackoverflow.com/questions/55785574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
electron-acrylic-window
=======================
Actually, it is possible, with a little bit of magic. I have no idea why nobody pointed that out, but there exists a small utility called [electron-acrylic-window](https://github.com/Seo-Rii/electron-acrylic-window), which allows you to do exactly that. You can choose between the acrylic ("frosted") and blur effects, as well as change the color of the window and the opacity.
Under the hood, it uses [node-gyp](https://github.com/nodejs/node-gyp) and low-level C++ code to render the page however you like. It's pretty easy to implement in Javascript.
The major drawback is that anything that is remotely transparent (and not above anything with a solid color) will be rendered as totally transparent.
Sample usage
------------
`index.js`
```js
const { BrowserWindow } = require('electron-acrylic-window');
// import { BrowserWindow } from 'electron-acrylic-window';
win = new BrowserWindow({
...,
frame: false,
vibrancy: {
theme: 'light', // (default) or 'dark' or '#rrggbbaa'
effect: 'acrylic', // (default) or 'blur'
disableOnBlur: true, // (default)
}
});
// alternatively use these to
// dynamically change vibrancy
win.setVibrancy([options])
// or
setVibrancy(win, [options])
```
`style.css`
```css
body {
background-color: transparent;
}
.watev {
background-color: black;
}
```
|
It's not possible to blur other apps in the background.
<https://www.electronjs.org/docs/api/frameless-window#limitations>
>
> The blur filter only applies to the web page, so there is no way to
> apply blur effect to the content below the window (i.e. other
> applications open on the user's system).
>
>
>
|
55,785,574
|
I want to assign the total number of rows to a variable named **"@row\_count"**.
```
DECLARE @row_count int
SET @row_count = SELECT COUNT(*) FROM information
```
I know. I'm doing **wrong**. But I haven't found anything on how to do it.
---
I want to do something like that:
```
CREATE PROC add_person
(
@id tinyint,
@name nvarchar(max),
@surname nvarchar(max),
@salary int,
@job nvarchar(max)
)
AS
BEGIN
INSERT INTO information
VALUES(@id,@name,@surname,@salary,@job)
END
DECLARE @row_count nvarchar(max)
SET @row_count = SELECT COUNT(*) FROM information
BEGIN TRAN
add_person 34,'asdf','asdf',3000,'asdf'
IF @row_count > 33
ROLLBACK TRAN
ELSE
COMMIT TRAN
GO;
```
**My goal:** to prevent the addition of new people if the number of people exceeds thirty-four.
|
2019/04/21
|
[
"https://Stackoverflow.com/questions/55785574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
electron-acrylic-window
=======================
Actually, it is possible, with a little bit of magic. I have no idea why nobody pointed that out, but there exists a small utility called [electron-acrylic-window](https://github.com/Seo-Rii/electron-acrylic-window), which allows you to do exactly that. You can choose between the acrylic ("frosted") and blur effects, as well as change the color of the window and the opacity.
Under the hood, it uses [node-gyp](https://github.com/nodejs/node-gyp) and low-level C++ code to render the page however you like. It's pretty easy to implement in Javascript.
The major drawback is that anything that is remotely transparent (and not above anything with a solid color) will be rendered as totally transparent.
Sample usage
------------
`index.js`
```js
const { BrowserWindow } = require('electron-acrylic-window');
// import { BrowserWindow } from 'electron-acrylic-window';
win = new BrowserWindow({
...,
frame: false,
vibrancy: {
theme: 'light', // (default) or 'dark' or '#rrggbbaa'
effect: 'acrylic', // (default) or 'blur'
disableOnBlur: true, // (default)
}
});
// alternatively use these to
// dynamically change vibrancy
win.setVibrancy([options])
// or
setVibrancy(win, [options])
```
`style.css`
```css
body {
background-color: transparent;
}
.watev {
background-color: black;
}
```
|
Electron does not allow you to blur on anything running behind it. It only allows you to blur the content on your webpage/app. Anything in your css styling will only be applied to the foreground contents. I know because I too have tried and failed.
|
11,826,556
|
I am using a service called 'embedly' which is showing my feeds. I'm trying to shorten the text of this feed, so I tried:
```
$('.description').html(
function(){
return $.trim($(this).html())
.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";}
);
```
I placed this in document ready and also in 'window.load' but nothing seems to work. Here is an example: [http://jsfiddle.net](http://jsfiddle.net/2VBSX/1/)
|
2012/08/06
|
[
"https://Stackoverflow.com/questions/11826556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647909/"
] |
This one took me a very long time to figure out, but I think the best you can do is give the elements a second to load into the DOM, and then run your function: <http://jsfiddle.net/2VBSX/5/>
```
$('div.newscontainer').embedly({
key:':e0a98aba95ef11e09dcd4040d3dc5c07'
}).hide();
setTimeout(function() {
$('div.newscontainer').show().find('.description').html(
function(){
return $.trim($(this).html())
.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
);
}, 1000);
```
|
Jquery's HTML doesn't accept a function as argument, but only plain HTML (a string).
To do what you wanto to do, use `.each()` :)
**Correction:** as pointed out by the commenter below, my code is correct but .html() **does** indeed accept a function as argument, in the form `$(...).html(function(index, oldhtml));`, making possible to access directly the html part. (Thanks to @Raminson for pointing it out)
Prior to @Raminson's observation my code was:
```
$('.description').each(
function(i,e){
$(e).html(reduce($(e).html()));}
);
function reduce(s)
{
return s.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
```
With the correction, the first part becomes (still using the `reduce()` function):
```
$(".description").html(function(i,s) { return reduce(s); });
```
|
11,826,556
|
I am using a service called 'embedly' which is showing my feeds. I'm trying to shorten the text of this feed, so I tried:
```
$('.description').html(
function(){
return $.trim($(this).html())
.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";}
);
```
I placed this in document ready and also in 'window.load' but nothing seems to work. Here is an example: [http://jsfiddle.net](http://jsfiddle.net/2VBSX/1/)
|
2012/08/06
|
[
"https://Stackoverflow.com/questions/11826556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647909/"
] |
Jquery's HTML doesn't accept a function as argument, but only plain HTML (a string).
To do what you wanto to do, use `.each()` :)
**Correction:** as pointed out by the commenter below, my code is correct but .html() **does** indeed accept a function as argument, in the form `$(...).html(function(index, oldhtml));`, making possible to access directly the html part. (Thanks to @Raminson for pointing it out)
Prior to @Raminson's observation my code was:
```
$('.description').each(
function(i,e){
$(e).html(reduce($(e).html()));}
);
function reduce(s)
{
return s.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
```
With the correction, the first part becomes (still using the `reduce()` function):
```
$(".description").html(function(i,s) { return reduce(s); });
```
|
So, my other answer is not valid because the OP didn't mention that all the elements were created on the fly, so they cannot be matched in the classical way.
If the modifications are attached to a suitable event (click, for example), then it would be easy to use delegates with `.on()`, as they are valid also for new elements inserted in the DOM.
But alas this is not the case, we must operate on the element's creation.
One solution would be @ChrisClower's one (a timer polling the page regularly for new elements).
Another solution would be to use the LiveQuery plugin: <http://docs.jquery.com/Plugins/livequery>
Then all would be simple:
```
$(".description").livequery(function() { $(e).html(reduce($(e).html())); });
function reduce(s)
{
return s.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
```
|
11,826,556
|
I am using a service called 'embedly' which is showing my feeds. I'm trying to shorten the text of this feed, so I tried:
```
$('.description').html(
function(){
return $.trim($(this).html())
.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";}
);
```
I placed this in document ready and also in 'window.load' but nothing seems to work. Here is an example: [http://jsfiddle.net](http://jsfiddle.net/2VBSX/1/)
|
2012/08/06
|
[
"https://Stackoverflow.com/questions/11826556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647909/"
] |
This one took me a very long time to figure out, but I think the best you can do is give the elements a second to load into the DOM, and then run your function: <http://jsfiddle.net/2VBSX/5/>
```
$('div.newscontainer').embedly({
key:':e0a98aba95ef11e09dcd4040d3dc5c07'
}).hide();
setTimeout(function() {
$('div.newscontainer').show().find('.description').html(
function(){
return $.trim($(this).html())
.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
);
}, 1000);
```
|
So, my other answer is not valid because the OP didn't mention that all the elements were created on the fly, so they cannot be matched in the classical way.
If the modifications are attached to a suitable event (click, for example), then it would be easy to use delegates with `.on()`, as they are valid also for new elements inserted in the DOM.
But alas this is not the case, we must operate on the element's creation.
One solution would be @ChrisClower's one (a timer polling the page regularly for new elements).
Another solution would be to use the LiveQuery plugin: <http://docs.jquery.com/Plugins/livequery>
Then all would be simple:
```
$(".description").livequery(function() { $(e).html(reduce($(e).html())); });
function reduce(s)
{
return s.substring(0, 100)
.split(" ").slice(0, -1)
.join(" ") + "...";
}
```
|
14,480,944
|
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
e.g
```
String folder = "ArslanFolder 20/01/2013";
```
**So I want to remove these characters with "\_"**
Here are characters
```
private static final String ReservedChars = "|\?*<\":>+[]/'";
```
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14480944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486139/"
] |
Use this code:
```
String folder = "ArslanFolder 20/01/2013 ? / '";
String result = folder.replaceAll("[|?*<\":>+\\[\\]/']", "_");
```
And the result would be:
```
ArslanFolder 20_01_2013 _ _ _
```
you didn't say that space should be replaced, so spaces are there... you could add it if it is necessary to be done.
|
Try this :
```
replaceAll("[\\W]", "_");
```
It will replace all non alphanumeric characters with underscore
|
14,480,944
|
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
e.g
```
String folder = "ArslanFolder 20/01/2013";
```
**So I want to remove these characters with "\_"**
Here are characters
```
private static final String ReservedChars = "|\?*<\":>+[]/'";
```
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14480944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486139/"
] |
I used one of this:
```
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
```
See this link:
[Replace special characters](https://stackoverflow.com/questions/4283351/how-to-replace-special-characters-in-a-string)
|
Try this :
```
replaceAll("[\\W]", "_");
```
It will replace all non alphanumeric characters with underscore
|
14,480,944
|
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
e.g
```
String folder = "ArslanFolder 20/01/2013";
```
**So I want to remove these characters with "\_"**
Here are characters
```
private static final String ReservedChars = "|\?*<\":>+[]/'";
```
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14480944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486139/"
] |
Use this code:
```
String folder = "ArslanFolder 20/01/2013 ? / '";
String result = folder.replaceAll("[|?*<\":>+\\[\\]/']", "_");
```
And the result would be:
```
ArslanFolder 20_01_2013 _ _ _
```
you didn't say that space should be replaced, so spaces are there... you could add it if it is necessary to be done.
|
I used one of this:
```
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
```
See this link:
[Replace special characters](https://stackoverflow.com/questions/4283351/how-to-replace-special-characters-in-a-string)
|
14,480,944
|
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
e.g
```
String folder = "ArslanFolder 20/01/2013";
```
**So I want to remove these characters with "\_"**
Here are characters
```
private static final String ReservedChars = "|\?*<\":>+[]/'";
```
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14480944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486139/"
] |
Use this code:
```
String folder = "ArslanFolder 20/01/2013 ? / '";
String result = folder.replaceAll("[|?*<\":>+\\[\\]/']", "_");
```
And the result would be:
```
ArslanFolder 20_01_2013 _ _ _
```
you didn't say that space should be replaced, so spaces are there... you could add it if it is necessary to be done.
|
**This is correct solution:**
```
String result = inputString.replaceAll("[\\\\|?\u0000*<\":>+\\[\\]/']", "_");
```
Kent answer is good, but he isnt include characters `NUL` and `\`.
Also, this is a secure solution for replacing/renaming text of user-input file names, for example.
|
14,480,944
|
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
e.g
```
String folder = "ArslanFolder 20/01/2013";
```
**So I want to remove these characters with "\_"**
Here are characters
```
private static final String ReservedChars = "|\?*<\":>+[]/'";
```
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14480944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486139/"
] |
I used one of this:
```
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
```
See this link:
[Replace special characters](https://stackoverflow.com/questions/4283351/how-to-replace-special-characters-in-a-string)
|
**This is correct solution:**
```
String result = inputString.replaceAll("[\\\\|?\u0000*<\":>+\\[\\]/']", "_");
```
Kent answer is good, but he isnt include characters `NUL` and `\`.
Also, this is a secure solution for replacing/renaming text of user-input file names, for example.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
>
> My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
>
>
> So, what is the difference between int \*pointerArray = new int[10]; and int array[10]; if any?
>
>
>
What you mention is the reason for much confusion in any C/C++ beginner.
In C/C++, an array corresponds to a block of memory sufficiently large to hold all of its elements. This is associated to the `[]` syntax, like in your example:
```
int array[10];
```
One feature of C/C++ is that you can refer to an array by using a pointer to its type. For this reason, you are allowed to write:
```
int* array_pointer = array;
```
which is the same as:
```
int* array_pointer = &array[0];
```
and this allows to access array elements in the usual way: `array_pointer[3]`,
but you cannot treat `array` as a pointer, like doing pointer arithmetics on it (i.e., array++ miserably fails).
That said, it is also true that you can manage arrays without using the `[]` syntax at all and just allocate arrays by using `malloc` and then using them with raw pointers. This makes the "beauty" of C/C++.
Resuming: a distinction must be made between the pointer and the memory that it points to (the actual array):
1. the `[]` syntax in declarations (i.e., `int array[10];`) refers to both aspects at once (it gives you, as to say, a pointer and an array);
2. when declaring a pointer variable (i.e., `int* p;`), you just get the pointer;
3. when evaluating an expression (i.e., `int i = p[4];`, or `array[4];`), the `[]` just means dereferencing a pointer.
Apart from this, the only difference between `int *pointerArray = new int[10];` and `int array[10];` is that former is allocated dynamically, the latter on the stack.
|
The main difference is that some operations that are allowed on pointers are not allowed on arrays.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
`int array[10];` declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using `delete []` on that kind of array, in fact, you might crash the program if you `delete` it.
When you use `operator new`, you allocate memory dynamically which could be *slower* and the memory usually comes from the *heap* rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and `delete[]` your stuff when you don't need it anymore.
As to your array being filled with zeros, what your class material does not say is that you have to do this:
```
int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;
```
That code extends the array `arr` by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).
|
Dynamically allocated:
```
int * pointerArray = new int[10];
```
[BTW, this is a pointer to an array of 10 ints, NOT a pointer array]
Statically allocated (possibly on the stack):
```
int array[10];
```
Otherwise they are the same.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
`int array[10];` declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using `delete []` on that kind of array, in fact, you might crash the program if you `delete` it.
When you use `operator new`, you allocate memory dynamically which could be *slower* and the memory usually comes from the *heap* rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and `delete[]` your stuff when you don't need it anymore.
As to your array being filled with zeros, what your class material does not say is that you have to do this:
```
int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;
```
That code extends the array `arr` by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).
|
On the one hand:
```
int ar[10];
```
is using memory allocated on the stack. You can think of it also locally available and while it is possible to pass a pointer / reference to otehr functions, the memory will be freed as soon as it goes out of scope (in your example at the end of the main method but that's usually not the case).
On the other hand:
```
int ar* = new int[10];
```
allocates the memory for the array on the heap. It is available until your whole program exits or it is deleted using
```
delete[] ar;
```
note, that for delete you need the "[]" if and only if the corresponding new has had them, too.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
>
> My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
>
>
> So, what is the difference between int \*pointerArray = new int[10]; and int array[10]; if any?
>
>
>
What you mention is the reason for much confusion in any C/C++ beginner.
In C/C++, an array corresponds to a block of memory sufficiently large to hold all of its elements. This is associated to the `[]` syntax, like in your example:
```
int array[10];
```
One feature of C/C++ is that you can refer to an array by using a pointer to its type. For this reason, you are allowed to write:
```
int* array_pointer = array;
```
which is the same as:
```
int* array_pointer = &array[0];
```
and this allows to access array elements in the usual way: `array_pointer[3]`,
but you cannot treat `array` as a pointer, like doing pointer arithmetics on it (i.e., array++ miserably fails).
That said, it is also true that you can manage arrays without using the `[]` syntax at all and just allocate arrays by using `malloc` and then using them with raw pointers. This makes the "beauty" of C/C++.
Resuming: a distinction must be made between the pointer and the memory that it points to (the actual array):
1. the `[]` syntax in declarations (i.e., `int array[10];`) refers to both aspects at once (it gives you, as to say, a pointer and an array);
2. when declaring a pointer variable (i.e., `int* p;`), you just get the pointer;
3. when evaluating an expression (i.e., `int i = p[4];`, or `array[4];`), the `[]` just means dereferencing a pointer.
Apart from this, the only difference between `int *pointerArray = new int[10];` and `int array[10];` is that former is allocated dynamically, the latter on the stack.
|
There is a difference but not in the area that you point to. `*pointerArray` will point to the beginning of a block of memory of size 10 bytes. So will `array`. The only difference will be where it is stored in memory. `pointerArray` is dynamically assigned memory (at `run-time`) and hence will go on the heap, while `array[10]` will be allocated at `compile-time` and will go to the stack.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
`int array[10];` declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using `delete []` on that kind of array, in fact, you might crash the program if you `delete` it.
When you use `operator new`, you allocate memory dynamically which could be *slower* and the memory usually comes from the *heap* rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and `delete[]` your stuff when you don't need it anymore.
As to your array being filled with zeros, what your class material does not say is that you have to do this:
```
int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;
```
That code extends the array `arr` by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).
|
>
> My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
>
>
> So, what is the difference between int \*pointerArray = new int[10]; and int array[10]; if any?
>
>
>
What you mention is the reason for much confusion in any C/C++ beginner.
In C/C++, an array corresponds to a block of memory sufficiently large to hold all of its elements. This is associated to the `[]` syntax, like in your example:
```
int array[10];
```
One feature of C/C++ is that you can refer to an array by using a pointer to its type. For this reason, you are allowed to write:
```
int* array_pointer = array;
```
which is the same as:
```
int* array_pointer = &array[0];
```
and this allows to access array elements in the usual way: `array_pointer[3]`,
but you cannot treat `array` as a pointer, like doing pointer arithmetics on it (i.e., array++ miserably fails).
That said, it is also true that you can manage arrays without using the `[]` syntax at all and just allocate arrays by using `malloc` and then using them with raw pointers. This makes the "beauty" of C/C++.
Resuming: a distinction must be made between the pointer and the memory that it points to (the actual array):
1. the `[]` syntax in declarations (i.e., `int array[10];`) refers to both aspects at once (it gives you, as to say, a pointer and an array);
2. when declaring a pointer variable (i.e., `int* p;`), you just get the pointer;
3. when evaluating an expression (i.e., `int i = p[4];`, or `array[4];`), the `[]` just means dereferencing a pointer.
Apart from this, the only difference between `int *pointerArray = new int[10];` and `int array[10];` is that former is allocated dynamically, the latter on the stack.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
Dynamically allocated:
```
int * pointerArray = new int[10];
```
[BTW, this is a pointer to an array of 10 ints, NOT a pointer array]
Statically allocated (possibly on the stack):
```
int array[10];
```
Otherwise they are the same.
|
The main difference is that some operations that are allowed on pointers are not allowed on arrays.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
`int array[10];` declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using `delete []` on that kind of array, in fact, you might crash the program if you `delete` it.
When you use `operator new`, you allocate memory dynamically which could be *slower* and the memory usually comes from the *heap* rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and `delete[]` your stuff when you don't need it anymore.
As to your array being filled with zeros, what your class material does not say is that you have to do this:
```
int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;
```
That code extends the array `arr` by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).
|
First, I'd look for some other place to learn C++. The page you cite is
very confusing, and has little to do with the way one actually programs
in C++. In C++, most of the time, you'd use `std::vector` for an array,
not the complex solutions proposed on the page you cite. In practice,
you never use `operator new[]` (an array `new`).
In fact, `std::vector` is in some ways more like `ArrayList` than simple
arrays in Java; unlike an array in Java, you can simply grow the vector
by inserting elements into it, preferrably at the end. And it supports
iterators, although C++ iterators are considerably different than Java
iterators. On the other hand, you can access it using the `[]`
operator, like a normal array.
The arrays described on the page you cite are usually called C style
arrays. In C++, their use is mostly limited to objects with static
lifetime, although they do occasionally appear in classes. In any case, they are never allocated dynamically.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
>
> My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
>
>
> So, what is the difference between int \*pointerArray = new int[10]; and int array[10]; if any?
>
>
>
What you mention is the reason for much confusion in any C/C++ beginner.
In C/C++, an array corresponds to a block of memory sufficiently large to hold all of its elements. This is associated to the `[]` syntax, like in your example:
```
int array[10];
```
One feature of C/C++ is that you can refer to an array by using a pointer to its type. For this reason, you are allowed to write:
```
int* array_pointer = array;
```
which is the same as:
```
int* array_pointer = &array[0];
```
and this allows to access array elements in the usual way: `array_pointer[3]`,
but you cannot treat `array` as a pointer, like doing pointer arithmetics on it (i.e., array++ miserably fails).
That said, it is also true that you can manage arrays without using the `[]` syntax at all and just allocate arrays by using `malloc` and then using them with raw pointers. This makes the "beauty" of C/C++.
Resuming: a distinction must be made between the pointer and the memory that it points to (the actual array):
1. the `[]` syntax in declarations (i.e., `int array[10];`) refers to both aspects at once (it gives you, as to say, a pointer and an array);
2. when declaring a pointer variable (i.e., `int* p;`), you just get the pointer;
3. when evaluating an expression (i.e., `int i = p[4];`, or `array[4];`), the `[]` just means dereferencing a pointer.
Apart from this, the only difference between `int *pointerArray = new int[10];` and `int array[10];` is that former is allocated dynamically, the latter on the stack.
|
First, I'd look for some other place to learn C++. The page you cite is
very confusing, and has little to do with the way one actually programs
in C++. In C++, most of the time, you'd use `std::vector` for an array,
not the complex solutions proposed on the page you cite. In practice,
you never use `operator new[]` (an array `new`).
In fact, `std::vector` is in some ways more like `ArrayList` than simple
arrays in Java; unlike an array in Java, you can simply grow the vector
by inserting elements into it, preferrably at the end. And it supports
iterators, although C++ iterators are considerably different than Java
iterators. On the other hand, you can access it using the `[]`
operator, like a normal array.
The arrays described on the page you cite are usually called C style
arrays. In C++, their use is mostly limited to objects with static
lifetime, although they do occasionally appear in classes. In any case, they are never allocated dynamically.
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
`int array[10];` declares the array size statically, that means it is fixed - which is the only major difference. It also might be allocated to be inside the function's stack frame, i.e. on the program's stack. You do not need to worry about using `delete []` on that kind of array, in fact, you might crash the program if you `delete` it.
When you use `operator new`, you allocate memory dynamically which could be *slower* and the memory usually comes from the *heap* rather than the program's stack (though not always). This is better in most cases, as you are more limited in the stack space than the heap space. However, you must watch out for memory leaks and `delete[]` your stuff when you don't need it anymore.
As to your array being filled with zeros, what your class material does not say is that you have to do this:
```
int *arr = new int[20]; // old array
//do magic here and decide that we need a bigger array
int *bigger = new int[50]; // allocate a bigger array
for (int i = 0; i < 20; i++) bigger[i] = arr[i]; // copy the elements from the old array into the new array
delete[] arr;
arr = bigger;
```
That code extends the array `arr` by 30 more elements. Note that you must copy the old data into the new array, or else it will not be there (in your case, everything becomes 0).
|
It is true that you can get most of array functionality by using a pointer to its first element. But compiler knows that a static array is composed of several elements and the most notable difference is the result of the `sizeof` operator.
`sizeof(pointerArray) = sizeof int*`
`sizeof(array) = 10 * sizeof int`
|
6,122,091
|
I'm familiar with Java and trying to teach myself C/C++. I'm stealing some curriculum from a class that is hosting their materials [here](http://courses.washington.edu/css342/zander/css332/array.html). I unfortunately can't ask the teacher since I'm not in the class. My concern is with the section under "dynamically declared arrays":
>
> If you
> want to be able to alter the size of
> your array at run time, then declare
> dynamic arrays. These are done with
> pointers and the new operator. For the
> basics on pointers, read the pointers
> section.
>
>
> Allocate memory using new, and then
> you access the array in the same way
> you would a static array. For example,
>
>
> int\* arrayPtr = new int[10]; for
> (int i = 0; i < 10; i++) {
> arrayPtr[i] = i; }
>
>
> The memory picture is identical to the
> static array, but you can change the
> size if you need to. Don't forget you
> must deallocate the memory before
> allocating new memory (or you will
> have a memory leak).
>
>
> delete [] arrayPtr; // the []
> is needed when deleting array pointers
> arrayPtr = new int[50]; . . .
>
>
> When you're completely done with the
> array, you must delete its memory:
>
>
> delete [] arrayPtr;
>
>
> Dynamic multi-dimensional arrays are
> done in a similar manner to Java. You
> will have pointers to pointers. For an
> example, see a
>
>
>
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between `int *pointerArray = new int[10];` and `int array[10];` if any?
I've done some tests that seem to indicate that they do the exact same thing. Is the website wrong or did I read that wrong?
```
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// Initialize the pointer array
int *pointerArray = new int[10];
for (int i = 0; i < 10; i++){
pointerArray[i] = i;
}
// Initialize the regular array
int array[10];
for (int i = 0; i < 10; i++){
array[i]= i;
}
cout << *(pointerArray + 5) << endl;
cout << *(array + 5) << endl;
cout << pointerArray[5] << endl;
cout << array[5] << endl;
cout << pointerArray << endl;
cout << array << endl;
return 0;
}
```
Output:
```
5
5
5
5
0x8f94030
0xbfa6a37c
```
I've tried to "dynamically re-size" my pointer array as described on the site, but my new (bigger) pointer array ends up filled with 0's which is not very useful.
|
2011/05/25
|
[
"https://Stackoverflow.com/questions/6122091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349611/"
] |
The problem with understanding C/C++ arrays when coming from Java is that C/C++ distinguishes between the array variable and the memory used to store the array contents. Both concepts are important and distinct. In Java, you really just have a reference to an object that is an array.
You also need to understand that C/C++ has two ways of allocating memory. Memory can be allocated on the help or the stack. Java doesn't have this distinction.
In C and C++, an array variable is a pointer to the first element of the array. An array variable can exist on the heap or the stack, and so can the memory that contains its contents. And they can be difference. Your examples are `int` arrays, so you can consider the array variable to be an `int*`.
There are two differences between `int *pointerArray = new int[10];` and `int array[10];`:
The first difference is that the memory that contains the contents of the first array is allocated on the *heap*. The second array is more tricky. If `array` is a local variable in a function then its contents are allocated on the stack, but if it is a member variable of a class then its contents are allocated wherever the containing object is allocated (heap or stack).
The second difference is that, as you've realised, the first array is dynamic: its size can be determined at run-time. The second array is fixed: the compiler must be able to determine its size at compile time.
|
The main difference is that some operations that are allowed on pointers are not allowed on arrays.
|
10,710,566
|
How to match different instances of the same word.
Eg: if the string is synergy. How to match it with synergizes, synergism, synergically, synergistic.
I could write the following:
```
while(<IN>)
{
chomp $_;
my $line= $_;
$word="Synergy";
if($line=~m/$word(\w+)/i)
{
$line=~s/$word/<Effect>$word<\/Effect>/ig;
}
}
```
|
2012/05/22
|
[
"https://Stackoverflow.com/questions/10710566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226696/"
] |
What you probably want to do is called stemming.
However, for this to work, you have to stem all the words in the text plus the one you search for. Hopefully all of your listed words result in the same stem. I haven't tested it yet.
```
use Lingua::Stem;
my $stemmer = Lingua::Stem->new( -locale => 'EN-UK' );
# first convert text to list of words
my @words;
while(<IN>) {
push @words, split(/\b/, $_); # you can do better here
}
# now stem all words.
my $stemmed_words = $stemmer->stem(@words);
# results in an array ref of stems in the same order as the words have been.
# now stem your search
my $stemmed_search = $stemmer->stem($word);
# and do the search from above inside stemmed array.
```
Now it depends on what you want. If you want to exchange all those words with something, you have to get the indexes of the matched (stemmed) words and do the replacement at the same positions inside your text.
|
You're going to want to use regular expressions. It is unclear what exactly the criteria you want to match, but in your example all the words start with "synergi" so `if($string =~ \bsynergi\w*\b)` would find all lines containing "synergi" anywhere in them.
|
10,710,566
|
How to match different instances of the same word.
Eg: if the string is synergy. How to match it with synergizes, synergism, synergically, synergistic.
I could write the following:
```
while(<IN>)
{
chomp $_;
my $line= $_;
$word="Synergy";
if($line=~m/$word(\w+)/i)
{
$line=~s/$word/<Effect>$word<\/Effect>/ig;
}
}
```
|
2012/05/22
|
[
"https://Stackoverflow.com/questions/10710566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226696/"
] |
What you probably want to do is called stemming.
However, for this to work, you have to stem all the words in the text plus the one you search for. Hopefully all of your listed words result in the same stem. I haven't tested it yet.
```
use Lingua::Stem;
my $stemmer = Lingua::Stem->new( -locale => 'EN-UK' );
# first convert text to list of words
my @words;
while(<IN>) {
push @words, split(/\b/, $_); # you can do better here
}
# now stem all words.
my $stemmed_words = $stemmer->stem(@words);
# results in an array ref of stems in the same order as the words have been.
# now stem your search
my $stemmed_search = $stemmer->stem($word);
# and do the search from above inside stemmed array.
```
Now it depends on what you want. If you want to exchange all those words with something, you have to get the indexes of the matched (stemmed) words and do the replacement at the same positions inside your text.
|
You might want to check out Text::Soundex. For example,
```
use Text::Soundex;
# The following all return S562
print soundex("synergizes"), "\n";
print soundex("synergism"), "\n";
print soundex("synergically"), "\n";
print soundex("synergistic"), "\n";
```
Further reading: [Perldoc Text::Soundex](http://perldoc.perl.org/Text/Soundex.html)
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
Others have mentioned File::Find, which is the way I'd go, but you asked for an iterator, which File::Find isn't (nor is File::Find::Rule). You might want to look at [File::Next](http://search.cpan.org/dist/File-Next/) or [File::Find::Object](http://search.cpan.org/dist/File-Find-Object/), which do have an iterative interfaces. Mark Jason Dominus goes over building your own in chapter 4.2.2 of [Higher Order Perl](http://hop.perl.plover.com/book/).
|
My preferred method is to use the File::Find module as so:
```
use File::Find;
find (\&checkFile, $directory_to_check_recursively);
sub checkFile()
{
#examine each file in here. Filename is in $_ and you are chdired into it's directory
#directory is also available in $File::Find::dir
}
```
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
This sounds like a job for [File::Find::Rule](http://search.cpan.org/perldoc?File::Find::Rule):
```
#!/usr/bin/perl
use strict;
use warnings;
use autodie; # Causes built-ins like open to succeed or die.
# You can 'use Fatal qw(open)' if autodie is not installed.
use File::Find::Rule;
use Getopt::Std;
use constant SECONDS_IN_DAY => 24 * 60 * 60;
our %option = (
m => 1, # -m switch: days ago modified, defaults to 1
o => undef, # -o switch: output file, defaults to STDOUT
);
getopts('m:o:', \%option);
# If we haven't been given directories to search, default to the
# current working directory.
if (not @ARGV) {
@ARGV = ( '.' );
}
print STDERR "Finding files changed in the last $option{m} day(s)\n";
# Convert our time in days into a timestamp in seconds from the epoch.
my $last_modified_timestamp = time() - SECONDS_IN_DAY * $option{m};
# Now find all the regular files, which have been modified in the last
# $option{m} days, looking in all the locations specified in
# @ARGV (our remaining command line arguments).
my @files = File::Find::Rule->file()
->mtime(">= $last_modified_timestamp")
->in(@ARGV);
# $out_fh will store the filehandle where we send the file list.
# It defaults to STDOUT.
my $out_fh = \*STDOUT;
if ($option{o}) {
open($out_fh, '>', $option{o});
}
# Print our results.
print {$out_fh} join("\n", @files), "\n";
```
|
[File::Find](http://search.cpan.org/~rgarcia/perl-5.10.0/lib/File/Find.pm) is the right way to solve this problem. There is no use in reimplementing stuff that already exists in other modules, but reimplementing something that is in a standard module should really be discouraged.
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
Where the problem is solved mainly by standard libraries use them.
File::Find in this case works nicely.
There may be many ways to do things in perl, but where a very standard library exists to do something, it should be utilised unless it has problems of it's own.
```
#!/usr/bin/perl
use strict;
use File::Find();
File::Find::find( {wanted => \&wanted}, ".");
sub wanted {
my (@stat);
my ($time) = time();
my ($days) = 5 * 60 * 60 * 24;
@stat = stat($_);
if (($time - $stat[9]) >= $days) {
print "$_ \n";
}
}
```
|
I write a subroutine that reads a directory with `readdir`, throws out the "." and ".." directories, recurses if it finds a new directory, and examines the files for what I'm looking for (in your case, you'll want to use `utime` or `stat`). By time the recursion is done, every file should have been examined.
I think all the functions you'd need for this script are described briefly here:
<http://www.cs.cf.ac.uk/Dave/PERL/node70.html>
The semantics of input and output are a fairly trivial exercise which I'll leave to you.
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
Others have mentioned File::Find, which is the way I'd go, but you asked for an iterator, which File::Find isn't (nor is File::Find::Rule). You might want to look at [File::Next](http://search.cpan.org/dist/File-Next/) or [File::Find::Object](http://search.cpan.org/dist/File-Find-Object/), which do have an iterative interfaces. Mark Jason Dominus goes over building your own in chapter 4.2.2 of [Higher Order Perl](http://hop.perl.plover.com/book/).
|
I write a subroutine that reads a directory with `readdir`, throws out the "." and ".." directories, recurses if it finds a new directory, and examines the files for what I'm looking for (in your case, you'll want to use `utime` or `stat`). By time the recursion is done, every file should have been examined.
I think all the functions you'd need for this script are described briefly here:
<http://www.cs.cf.ac.uk/Dave/PERL/node70.html>
The semantics of input and output are a fairly trivial exercise which I'll leave to you.
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
My preferred method is to use the File::Find module as so:
```
use File::Find;
find (\&checkFile, $directory_to_check_recursively);
sub checkFile()
{
#examine each file in here. Filename is in $_ and you are chdired into it's directory
#directory is also available in $File::Find::dir
}
```
|
I write a subroutine that reads a directory with `readdir`, throws out the "." and ".." directories, recurses if it finds a new directory, and examines the files for what I'm looking for (in your case, you'll want to use `utime` or `stat`). By time the recursion is done, every file should have been examined.
I think all the functions you'd need for this script are described briefly here:
<http://www.cs.cf.ac.uk/Dave/PERL/node70.html>
The semantics of input and output are a fairly trivial exercise which I'll leave to you.
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
Where the problem is solved mainly by standard libraries use them.
File::Find in this case works nicely.
There may be many ways to do things in perl, but where a very standard library exists to do something, it should be utilised unless it has problems of it's own.
```
#!/usr/bin/perl
use strict;
use File::Find();
File::Find::find( {wanted => \&wanted}, ".");
sub wanted {
my (@stat);
my ($time) = time();
my ($days) = 5 * 60 * 60 * 24;
@stat = stat($_);
if (($time - $stat[9]) >= $days) {
print "$_ \n";
}
}
```
|
I wrote [File::Find::Closures](http://search.cpan.org/dist/File-Find-Closures) as a set of closures that you can use with File::Find so you don't have to write your own. There's a couple of mtime functions that should handle
```
use File::Find;
use File::Find::Closures qw(:all);
my( $wanted, $list_reporter ) = find_by_modified_after( time - 86400 );
#my( $wanted, $list_reporter ) = find_by_modified_before( time - 86400 );
File::Find::find( $wanted, @directories );
my @modified = $list_reporter->();
```
You don't really need to use the module because I mostly designed it as a way that you could look at the code and steal the parts that you wanted. In this case it's a little trickier because all the subroutines that deal with stat depend on a second subroutine. You'll quickly get the idea from the code though.
Good luck,
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
This sounds like a job for [File::Find::Rule](http://search.cpan.org/perldoc?File::Find::Rule):
```
#!/usr/bin/perl
use strict;
use warnings;
use autodie; # Causes built-ins like open to succeed or die.
# You can 'use Fatal qw(open)' if autodie is not installed.
use File::Find::Rule;
use Getopt::Std;
use constant SECONDS_IN_DAY => 24 * 60 * 60;
our %option = (
m => 1, # -m switch: days ago modified, defaults to 1
o => undef, # -o switch: output file, defaults to STDOUT
);
getopts('m:o:', \%option);
# If we haven't been given directories to search, default to the
# current working directory.
if (not @ARGV) {
@ARGV = ( '.' );
}
print STDERR "Finding files changed in the last $option{m} day(s)\n";
# Convert our time in days into a timestamp in seconds from the epoch.
my $last_modified_timestamp = time() - SECONDS_IN_DAY * $option{m};
# Now find all the regular files, which have been modified in the last
# $option{m} days, looking in all the locations specified in
# @ARGV (our remaining command line arguments).
my @files = File::Find::Rule->file()
->mtime(">= $last_modified_timestamp")
->in(@ARGV);
# $out_fh will store the filehandle where we send the file list.
# It defaults to STDOUT.
my $out_fh = \*STDOUT;
if ($option{o}) {
open($out_fh, '>', $option{o});
}
# Print our results.
print {$out_fh} join("\n", @files), "\n";
```
|
Where the problem is solved mainly by standard libraries use them.
File::Find in this case works nicely.
There may be many ways to do things in perl, but where a very standard library exists to do something, it should be utilised unless it has problems of it's own.
```
#!/usr/bin/perl
use strict;
use File::Find();
File::Find::find( {wanted => \&wanted}, ".");
sub wanted {
my (@stat);
my ($time) = time();
my ($days) = 5 * 60 * 60 * 24;
@stat = stat($_);
if (($time - $stat[9]) >= $days) {
print "$_ \n";
}
}
```
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
My preferred method is to use the File::Find module as so:
```
use File::Find;
find (\&checkFile, $directory_to_check_recursively);
sub checkFile()
{
#examine each file in here. Filename is in $_ and you are chdired into it's directory
#directory is also available in $File::Find::dir
}
```
|
Using standard modules is indeed a good idea but out of interest here is my back to basic approach using no external modules. I know code syntax here might not be everyone's cup of tea.
It could be improved to use less memory via providing an iterator access (input list could temporarily be on hold once it reaches a certain size) and conditional check can be expanded via callback ref.
```
sub mfind {
my %done;
sub find {
my $last_mod = shift;
my $path = shift;
#determine physical link if symlink
$path = readlink($path) || $path;
#return if already processed
return if $done{$path} > 1;
#mark path as processed
$done{$path}++;
#DFS recursion
return grep{$_} @_
? ( find($last_mod, $path), find($last_mod, @_) )
: -d $path
? find($last_mod, glob("$path/*") )
: -f $path && (stat($path))[9] >= $last_mod
? $path : undef;
}
return find(@_);
}
print join "\n", mfind(time - 1 * 86400, "some path");
```
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
Where the problem is solved mainly by standard libraries use them.
File::Find in this case works nicely.
There may be many ways to do things in perl, but where a very standard library exists to do something, it should be utilised unless it has problems of it's own.
```
#!/usr/bin/perl
use strict;
use File::Find();
File::Find::find( {wanted => \&wanted}, ".");
sub wanted {
my (@stat);
my ($time) = time();
my ($days) = 5 * 60 * 60 * 24;
@stat = stat($_);
if (($time - $stat[9]) >= $days) {
print "$_ \n";
}
}
```
|
There's my [File::Finder](http://search.cpan.org/perldoc/File::Finder), as already mentioned, but there's also my iterator-as-a-tied-hash solution from [Finding Files Incrementally (Linux Magazine)](http://www.stonehenge.com/merlyn/LinuxMag/col30.html).
|
161,687
|
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.
So an example Perl problem:
A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.
The question, for Perl developers: What is your best way to accomplish this?
|
2008/10/02
|
[
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
] |
There's my [File::Finder](http://search.cpan.org/perldoc/File::Finder), as already mentioned, but there's also my iterator-as-a-tied-hash solution from [Finding Files Incrementally (Linux Magazine)](http://www.stonehenge.com/merlyn/LinuxMag/col30.html).
|
I'm riskying to get downvoted, but IMHO 'ls' (with appropriate params) command does it in a best known performant way. In this case it might be quite good solution to pipe 'ls' from perl code through shell, returning results to an array or hash.
Edit: It could also be 'find' used, as proposed in comments.
|
11,497,749
|
I am transitioning to GlassFish 3.1.2, and can't seem to resolve a problem with authentication.
The agenda is simple: I want a login bean to do programmatic authentication for a user. The authentication seems to work (the code goes past the login() method), but the server ends up shown 403 for the protected resources... Please help :)
Here are more details. There is a pure JSF login page with name/pass pair:
```
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui" template="/templates/main.xhtml">
<ui:define name="body">
<h:form id="form">
<p:messages />
<p:panel>
<h:panelGrid>
<h:outputText value="User Name" />
<p:inputText value="#{loginBean.userName}" id="userName"
required="true" />
<p:message for="userName" />
<h:outputText value="Password" />
<p:password value="#{loginBean.password}" id="password"
required="true" />
<p:message for="password" />
</h:panelGrid>
<h:panelGrid columns="2">
<p:commandButton value="Clear"
actionListener="#{loginBean.clear()}" ajax="false" />
<p:commandButton value="Login" action="#{loginBean.login()}"
ajax="false" />
</h:panelGrid>
</p:panel>
</h:form>
</ui:define>
</ui:composition>
```
and a bean that carries out the login
```
@Named("loginBean")
@SessionScoped
public class LoginBean implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
@Named("dao")
private Dao dao;
private String userName;
private String password;
@Inject
private UserBean userBean;
...
public String login() {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
try {
request.login(getUserName(), getPassword());
Principal principal = request.getUserPrincipal();
logger.info("Logged in successfully: " + principal);
} catch (ServletException e) {
Messages.addError("Invalid user name or password.");
return null;
}
User user = dao.findSingle("SELECT u FROM User AS u WHERE u.name = ?1",
getUserName());
if (user == null) {
logger.severe("Unable to find user record after successful authentication");
Messages.addError("Unable to load user record");
try {
request.logout();
} catch (ServletException e) {
logger.log(Level.SEVERE, "Unable to logout after failed login attempt", e);
}
return null;
}
getUserBean().setUser(user);
return "/list/list.xhtml?faces-redirect=true";
}
...
accessors
...
}
```
Here is my web.xml
```
<?xml version='1.0' encoding='UTF-8'?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>GM</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- Faces Servlet -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<login-config>
<realm-name>gmRealm</realm-name>
</login-config>
<security-role>
<role-name>user</role-name>
</security-role>
<security-role>
<role-name>admin</role-name>
</security-role>
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/list/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>user</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>Admin Area</web-resource-name>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<welcome-file-list>
<welcome-file>login.xhtml</welcome-file>
</welcome-file-list>
</web-app>
```
Here is the folder structure for the project:

I was also able to set up the realm as discussed here: <http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html>
Nothing fancy, AFAICT.
However, whenever I get to the protected resource after a successful login, I get:
```
HTTP Status 403 - Access to the requested resource has been denied
```
Despite the fact that the server log contains the message:
```
INFO: Logged in successfully: nick
```
Also note that when I remove "?faces-redirect=true", from the login() method's return value, the initial protected resource is rendered just fine right after the login, but all the subsequent requests to it fail with 403.
Here is what it shows in the debugger:

I also think that I've done my homework:
[Performing user authentication in Java EE / JSF using j\_security\_check](https://stackoverflow.com/questions/2206911/best-way-for-user-authentication-on-javaee-6-using-jsf-2-0)
[Programmatically control login with Servlet 3.0](https://stackoverflow.com/questions/6189536/programmatically-control-login-with-servlet-3-0)
[JSF 2.0 Simple login page](https://stackoverflow.com/questions/3752104/jsf-2-0-simple-login-page)
[Glassfish 3 security - Form based authentication using a JDBC Realm](https://stackoverflow.com/questions/7944963/glassfish-3-security-form-based-authentication-using-a-jdbc-realm)
Please help...
|
2012/07/16
|
[
"https://Stackoverflow.com/questions/11497749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/590984/"
] |
Oh, well, I guess this one is too deployment specific. I ended up re-conding the prototype in Spring for Tomcat stack. Works like charm now :).
|
i think you are not permitted jsf resources in spring security. add following line in security.xml in http tags.
```
<http .........>
<intercept-url pattern="/javax.faces.resource/**" access="permitAll"/>
</http>
```
|
20,876,772
|
I'm developing a multiple segment file downloader. To accomplish this task I'm currently creating as many temporary files on disk as segments I have (they are fixed in number during the file downloading). In the end I just create a new file `f` and copy all the segments' contents onto `f`.
I was wondering if there's not a better way to accomplish this. My idealization is of initially creating `f` in its full-size and then have the different threads write directly onto their portion. There need not to be any kind of interaction between them. We can assume any of them will start at its own starting point in the file and then only fill information sequentially in the file until its task is over.
I've heard about Memory-Mapped files (<http://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx>) and I'm wondering if they are the solution to my problem or not.
Thanks
|
2014/01/02
|
[
"https://Stackoverflow.com/questions/20876772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130758/"
] |
Simply declare a parameter of type `Form` in the other's class constructor:
```
public class myClass
{
private Form otherForm;
public myClass(Form form)
{
otherForm = form;
}
}
```
and call it from within `Form1`:
```
_myClass = new myClass(this);
```
|
Sure you can:
```
_myClass = new myClass(this);
```
|
20,876,772
|
I'm developing a multiple segment file downloader. To accomplish this task I'm currently creating as many temporary files on disk as segments I have (they are fixed in number during the file downloading). In the end I just create a new file `f` and copy all the segments' contents onto `f`.
I was wondering if there's not a better way to accomplish this. My idealization is of initially creating `f` in its full-size and then have the different threads write directly onto their portion. There need not to be any kind of interaction between them. We can assume any of them will start at its own starting point in the file and then only fill information sequentially in the file until its task is over.
I've heard about Memory-Mapped files (<http://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx>) and I'm wondering if they are the solution to my problem or not.
Thanks
|
2014/01/02
|
[
"https://Stackoverflow.com/questions/20876772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130758/"
] |
You'd just do:
```
_myClass = new myClass(this);
```
And then change the constructor in myClass:
```
public class myClass
{
private Form1 theForm;
public myClass(Form1 theForm)
{
this.theForm = theForm;
}
...
}
```
Now you can access the form from within the class. I think I'd avoid doing this though. Try to leave the form in charge of calling the class and determining when it should close itself.
Having the class hold a reference back to the form that instantiated it, and closing it from within the class seems like it could lead to confusion and maintainability issues down the road.
|
Simply declare a parameter of type `Form` in the other's class constructor:
```
public class myClass
{
private Form otherForm;
public myClass(Form form)
{
otherForm = form;
}
}
```
and call it from within `Form1`:
```
_myClass = new myClass(this);
```
|
20,876,772
|
I'm developing a multiple segment file downloader. To accomplish this task I'm currently creating as many temporary files on disk as segments I have (they are fixed in number during the file downloading). In the end I just create a new file `f` and copy all the segments' contents onto `f`.
I was wondering if there's not a better way to accomplish this. My idealization is of initially creating `f` in its full-size and then have the different threads write directly onto their portion. There need not to be any kind of interaction between them. We can assume any of them will start at its own starting point in the file and then only fill information sequentially in the file until its task is over.
I've heard about Memory-Mapped files (<http://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx>) and I'm wondering if they are the solution to my problem or not.
Thanks
|
2014/01/02
|
[
"https://Stackoverflow.com/questions/20876772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130758/"
] |
Simply declare a parameter of type `Form` in the other's class constructor:
```
public class myClass
{
private Form otherForm;
public myClass(Form form)
{
otherForm = form;
}
}
```
and call it from within `Form1`:
```
_myClass = new myClass(this);
```
|
Unless I'm missing something, this ought to be fairly straightforward:
```
public Form1(myClass instance)
{
InitializeComponent();
_myClass = instance;
}
```
|
20,876,772
|
I'm developing a multiple segment file downloader. To accomplish this task I'm currently creating as many temporary files on disk as segments I have (they are fixed in number during the file downloading). In the end I just create a new file `f` and copy all the segments' contents onto `f`.
I was wondering if there's not a better way to accomplish this. My idealization is of initially creating `f` in its full-size and then have the different threads write directly onto their portion. There need not to be any kind of interaction between them. We can assume any of them will start at its own starting point in the file and then only fill information sequentially in the file until its task is over.
I've heard about Memory-Mapped files (<http://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx>) and I'm wondering if they are the solution to my problem or not.
Thanks
|
2014/01/02
|
[
"https://Stackoverflow.com/questions/20876772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130758/"
] |
You'd just do:
```
_myClass = new myClass(this);
```
And then change the constructor in myClass:
```
public class myClass
{
private Form1 theForm;
public myClass(Form1 theForm)
{
this.theForm = theForm;
}
...
}
```
Now you can access the form from within the class. I think I'd avoid doing this though. Try to leave the form in charge of calling the class and determining when it should close itself.
Having the class hold a reference back to the form that instantiated it, and closing it from within the class seems like it could lead to confusion and maintainability issues down the road.
|
Sure you can:
```
_myClass = new myClass(this);
```
|
20,876,772
|
I'm developing a multiple segment file downloader. To accomplish this task I'm currently creating as many temporary files on disk as segments I have (they are fixed in number during the file downloading). In the end I just create a new file `f` and copy all the segments' contents onto `f`.
I was wondering if there's not a better way to accomplish this. My idealization is of initially creating `f` in its full-size and then have the different threads write directly onto their portion. There need not to be any kind of interaction between them. We can assume any of them will start at its own starting point in the file and then only fill information sequentially in the file until its task is over.
I've heard about Memory-Mapped files (<http://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx>) and I'm wondering if they are the solution to my problem or not.
Thanks
|
2014/01/02
|
[
"https://Stackoverflow.com/questions/20876772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130758/"
] |
Sure you can:
```
_myClass = new myClass(this);
```
|
Unless I'm missing something, this ought to be fairly straightforward:
```
public Form1(myClass instance)
{
InitializeComponent();
_myClass = instance;
}
```
|
20,876,772
|
I'm developing a multiple segment file downloader. To accomplish this task I'm currently creating as many temporary files on disk as segments I have (they are fixed in number during the file downloading). In the end I just create a new file `f` and copy all the segments' contents onto `f`.
I was wondering if there's not a better way to accomplish this. My idealization is of initially creating `f` in its full-size and then have the different threads write directly onto their portion. There need not to be any kind of interaction between them. We can assume any of them will start at its own starting point in the file and then only fill information sequentially in the file until its task is over.
I've heard about Memory-Mapped files (<http://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx>) and I'm wondering if they are the solution to my problem or not.
Thanks
|
2014/01/02
|
[
"https://Stackoverflow.com/questions/20876772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130758/"
] |
I can't figure out what you want to achieve. but if you just want to pass this form than you can use this.
```
_myClass = new myClass(this);
```
|
Sure you can:
```
_myClass = new myClass(this);
```
|
20,876,772
|
I'm developing a multiple segment file downloader. To accomplish this task I'm currently creating as many temporary files on disk as segments I have (they are fixed in number during the file downloading). In the end I just create a new file `f` and copy all the segments' contents onto `f`.
I was wondering if there's not a better way to accomplish this. My idealization is of initially creating `f` in its full-size and then have the different threads write directly onto their portion. There need not to be any kind of interaction between them. We can assume any of them will start at its own starting point in the file and then only fill information sequentially in the file until its task is over.
I've heard about Memory-Mapped files (<http://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx>) and I'm wondering if they are the solution to my problem or not.
Thanks
|
2014/01/02
|
[
"https://Stackoverflow.com/questions/20876772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130758/"
] |
You'd just do:
```
_myClass = new myClass(this);
```
And then change the constructor in myClass:
```
public class myClass
{
private Form1 theForm;
public myClass(Form1 theForm)
{
this.theForm = theForm;
}
...
}
```
Now you can access the form from within the class. I think I'd avoid doing this though. Try to leave the form in charge of calling the class and determining when it should close itself.
Having the class hold a reference back to the form that instantiated it, and closing it from within the class seems like it could lead to confusion and maintainability issues down the road.
|
Unless I'm missing something, this ought to be fairly straightforward:
```
public Form1(myClass instance)
{
InitializeComponent();
_myClass = instance;
}
```
|
20,876,772
|
I'm developing a multiple segment file downloader. To accomplish this task I'm currently creating as many temporary files on disk as segments I have (they are fixed in number during the file downloading). In the end I just create a new file `f` and copy all the segments' contents onto `f`.
I was wondering if there's not a better way to accomplish this. My idealization is of initially creating `f` in its full-size and then have the different threads write directly onto their portion. There need not to be any kind of interaction between them. We can assume any of them will start at its own starting point in the file and then only fill information sequentially in the file until its task is over.
I've heard about Memory-Mapped files (<http://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx>) and I'm wondering if they are the solution to my problem or not.
Thanks
|
2014/01/02
|
[
"https://Stackoverflow.com/questions/20876772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130758/"
] |
You'd just do:
```
_myClass = new myClass(this);
```
And then change the constructor in myClass:
```
public class myClass
{
private Form1 theForm;
public myClass(Form1 theForm)
{
this.theForm = theForm;
}
...
}
```
Now you can access the form from within the class. I think I'd avoid doing this though. Try to leave the form in charge of calling the class and determining when it should close itself.
Having the class hold a reference back to the form that instantiated it, and closing it from within the class seems like it could lead to confusion and maintainability issues down the road.
|
I can't figure out what you want to achieve. but if you just want to pass this form than you can use this.
```
_myClass = new myClass(this);
```
|
20,876,772
|
I'm developing a multiple segment file downloader. To accomplish this task I'm currently creating as many temporary files on disk as segments I have (they are fixed in number during the file downloading). In the end I just create a new file `f` and copy all the segments' contents onto `f`.
I was wondering if there's not a better way to accomplish this. My idealization is of initially creating `f` in its full-size and then have the different threads write directly onto their portion. There need not to be any kind of interaction between them. We can assume any of them will start at its own starting point in the file and then only fill information sequentially in the file until its task is over.
I've heard about Memory-Mapped files (<http://msdn.microsoft.com/en-us/library/dd997372(v=vs.110).aspx>) and I'm wondering if they are the solution to my problem or not.
Thanks
|
2014/01/02
|
[
"https://Stackoverflow.com/questions/20876772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130758/"
] |
I can't figure out what you want to achieve. but if you just want to pass this form than you can use this.
```
_myClass = new myClass(this);
```
|
Unless I'm missing something, this ought to be fairly straightforward:
```
public Form1(myClass instance)
{
InitializeComponent();
_myClass = instance;
}
```
|
17,008,230
|
I am currently using eclipse for working with Java. Additionaly I use git to synchronize my project between my laptop and my desktop PC.
The problem is now the following: I added external JARs to the project (Slick-Util, LWJGL).
But the path to each library is another on each device. So everytime I start working on the other device, I have to change the path to the jar files and the javadocs.
The libraries are all stored in my eclipse workspace. So the libraries and the projects are all in the same folder. And this folder is also commited with git.
Is there a way to change the eclipse settings (or do something else) so I do not have to change the path to the libraries and javadocs everytime?
I already googled and searched for it, but I could not find something about it.
|
2013/06/09
|
[
"https://Stackoverflow.com/questions/17008230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970549/"
] |
add jar files to a lib folder inside your project like this : D:\Workspace\myproject\lib\your-jar-file.jar
then go to your projects build path select libraries tab and click on *add jars* and **NOT** *add external jars* this way your jar files path will be relative to your project
**EDIT :**
I highly recommend to use a build tool as Kiril Raychev described.
it will look a bit confusing to start with but after a while and after a normal growth in your application that will lead to using different frameworks, controlling and managing dependencies and their conflicts without a build tool will literally kill you.
|
Up until now i usually use svn so i'm not entirely sure how it works out in git, but have you tried to store the JARs in the lib folder of the project they are used in? (Eclipse displays the lib folder so you can easiely add them to the buildpath with a right click on the library in the package explorer.)
That way the relative location/path of the libraries to the project should stay the same. Furthermore if you plan to pack the project into a JAR later you ship the libraries inside that JAR without having to worry whether the user of that file even has them on his computer.
PS: Looks like i'm a minute too late. Dave basically said the same thing.
|
17,008,230
|
I am currently using eclipse for working with Java. Additionaly I use git to synchronize my project between my laptop and my desktop PC.
The problem is now the following: I added external JARs to the project (Slick-Util, LWJGL).
But the path to each library is another on each device. So everytime I start working on the other device, I have to change the path to the jar files and the javadocs.
The libraries are all stored in my eclipse workspace. So the libraries and the projects are all in the same folder. And this folder is also commited with git.
Is there a way to change the eclipse settings (or do something else) so I do not have to change the path to the libraries and javadocs everytime?
I already googled and searched for it, but I could not find something about it.
|
2013/06/09
|
[
"https://Stackoverflow.com/questions/17008230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970549/"
] |
Just don't add the libraries' jars to git. There are multiple build tools for java, which manage dependencies for you - you just state the libraries you're going to use, and the build tool downloads it for you at build time.
I would recommend [Gradle](http://www.gradle.org/), but [Maven](http://maven.apache.org/) is also a very popular choice.
In gradle, you would create a file `build.gradle`, and define your dependencies in it:
```
apply plugin: 'eclipse'
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
compile 'org.lwjgl.lwjgl:lwjgl:2.9.0'
compile 'org.lwjgl.lwjgl:lwjgl_util:2.9.0'
}
```
Then you would run `gradle eclipse` from the command line - that would add the libraries you use to the classpath in eclipse. And when you want to compile and package your project you would run `gradle build` from the command line. You should read about it if you're going to use it, what I describe may not be *exactly* what you need.
Also, there are [instructions for using LWJGL with maven](http://www.lwjgl.org/wiki/index.php?title=LWJGL_use_in_Maven).
|
add jar files to a lib folder inside your project like this : D:\Workspace\myproject\lib\your-jar-file.jar
then go to your projects build path select libraries tab and click on *add jars* and **NOT** *add external jars* this way your jar files path will be relative to your project
**EDIT :**
I highly recommend to use a build tool as Kiril Raychev described.
it will look a bit confusing to start with but after a while and after a normal growth in your application that will lead to using different frameworks, controlling and managing dependencies and their conflicts without a build tool will literally kill you.
|
17,008,230
|
I am currently using eclipse for working with Java. Additionaly I use git to synchronize my project between my laptop and my desktop PC.
The problem is now the following: I added external JARs to the project (Slick-Util, LWJGL).
But the path to each library is another on each device. So everytime I start working on the other device, I have to change the path to the jar files and the javadocs.
The libraries are all stored in my eclipse workspace. So the libraries and the projects are all in the same folder. And this folder is also commited with git.
Is there a way to change the eclipse settings (or do something else) so I do not have to change the path to the libraries and javadocs everytime?
I already googled and searched for it, but I could not find something about it.
|
2013/06/09
|
[
"https://Stackoverflow.com/questions/17008230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970549/"
] |
add jar files to a lib folder inside your project like this : D:\Workspace\myproject\lib\your-jar-file.jar
then go to your projects build path select libraries tab and click on *add jars* and **NOT** *add external jars* this way your jar files path will be relative to your project
**EDIT :**
I highly recommend to use a build tool as Kiril Raychev described.
it will look a bit confusing to start with but after a while and after a normal growth in your application that will lead to using different frameworks, controlling and managing dependencies and their conflicts without a build tool will literally kill you.
|
You can simply use -f flag on add command.
```
git add -f test.jar
```
And, then commit and push to your repo.
|
17,008,230
|
I am currently using eclipse for working with Java. Additionaly I use git to synchronize my project between my laptop and my desktop PC.
The problem is now the following: I added external JARs to the project (Slick-Util, LWJGL).
But the path to each library is another on each device. So everytime I start working on the other device, I have to change the path to the jar files and the javadocs.
The libraries are all stored in my eclipse workspace. So the libraries and the projects are all in the same folder. And this folder is also commited with git.
Is there a way to change the eclipse settings (or do something else) so I do not have to change the path to the libraries and javadocs everytime?
I already googled and searched for it, but I could not find something about it.
|
2013/06/09
|
[
"https://Stackoverflow.com/questions/17008230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970549/"
] |
Just don't add the libraries' jars to git. There are multiple build tools for java, which manage dependencies for you - you just state the libraries you're going to use, and the build tool downloads it for you at build time.
I would recommend [Gradle](http://www.gradle.org/), but [Maven](http://maven.apache.org/) is also a very popular choice.
In gradle, you would create a file `build.gradle`, and define your dependencies in it:
```
apply plugin: 'eclipse'
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
compile 'org.lwjgl.lwjgl:lwjgl:2.9.0'
compile 'org.lwjgl.lwjgl:lwjgl_util:2.9.0'
}
```
Then you would run `gradle eclipse` from the command line - that would add the libraries you use to the classpath in eclipse. And when you want to compile and package your project you would run `gradle build` from the command line. You should read about it if you're going to use it, what I describe may not be *exactly* what you need.
Also, there are [instructions for using LWJGL with maven](http://www.lwjgl.org/wiki/index.php?title=LWJGL_use_in_Maven).
|
Up until now i usually use svn so i'm not entirely sure how it works out in git, but have you tried to store the JARs in the lib folder of the project they are used in? (Eclipse displays the lib folder so you can easiely add them to the buildpath with a right click on the library in the package explorer.)
That way the relative location/path of the libraries to the project should stay the same. Furthermore if you plan to pack the project into a JAR later you ship the libraries inside that JAR without having to worry whether the user of that file even has them on his computer.
PS: Looks like i'm a minute too late. Dave basically said the same thing.
|
17,008,230
|
I am currently using eclipse for working with Java. Additionaly I use git to synchronize my project between my laptop and my desktop PC.
The problem is now the following: I added external JARs to the project (Slick-Util, LWJGL).
But the path to each library is another on each device. So everytime I start working on the other device, I have to change the path to the jar files and the javadocs.
The libraries are all stored in my eclipse workspace. So the libraries and the projects are all in the same folder. And this folder is also commited with git.
Is there a way to change the eclipse settings (or do something else) so I do not have to change the path to the libraries and javadocs everytime?
I already googled and searched for it, but I could not find something about it.
|
2013/06/09
|
[
"https://Stackoverflow.com/questions/17008230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970549/"
] |
Just don't add the libraries' jars to git. There are multiple build tools for java, which manage dependencies for you - you just state the libraries you're going to use, and the build tool downloads it for you at build time.
I would recommend [Gradle](http://www.gradle.org/), but [Maven](http://maven.apache.org/) is also a very popular choice.
In gradle, you would create a file `build.gradle`, and define your dependencies in it:
```
apply plugin: 'eclipse'
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
compile 'org.lwjgl.lwjgl:lwjgl:2.9.0'
compile 'org.lwjgl.lwjgl:lwjgl_util:2.9.0'
}
```
Then you would run `gradle eclipse` from the command line - that would add the libraries you use to the classpath in eclipse. And when you want to compile and package your project you would run `gradle build` from the command line. You should read about it if you're going to use it, what I describe may not be *exactly* what you need.
Also, there are [instructions for using LWJGL with maven](http://www.lwjgl.org/wiki/index.php?title=LWJGL_use_in_Maven).
|
You can simply use -f flag on add command.
```
git add -f test.jar
```
And, then commit and push to your repo.
|
67,868,175
|
I need to include jinja templating in element.innerHTML but jinja is not working.
Code script.js:
```
contentDiv.innerHTML = getContent(fragmentId);
function getContent(fragmentId) {
var pages = {
quad1: `
<form class="form-inline" method="POST" id="form1">
<h3>
<input type="number" id="quad_a1" name="input_a" class="form-control mx-2 col-1" placeholder="a">
<b>x² +</b>
<input type="number" id="quad_b1" name="input_b" class="form-control mx-2 col-1" placeholder="b">
<b>x +</b>
<input type="number" name="input_c" class="form-control mx-2 col-1" placeholder="c">
<b>=</b>
<input type="number" name="input_d" class="form-control mx-2 col-2" placeholder="Default(0)">
<button type="submit" class="btn btn-primary float-right mr-5" onclick="return empty_quad()">Solve</button>
</h3>
</form>
{{ sol }}
`,
.
.
.
};
return pages[fragmentId];
}
```
But the output is literally {{ sol }}, not the value of sol:
[](https://i.stack.imgur.com/wwSWk.png)
So how to access the variable sol passed through flask's render\_template() in script.js?
|
2021/06/07
|
[
"https://Stackoverflow.com/questions/67868175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15879415/"
] |
Sure you can write your own Functional Interface(s), despite as many as possible will be nearly infinite (bound by size limitations of source and code files!)
The Functional Interfaces are specified in [JLS 9.8](https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-9.8) - basically an `interface` with a single abstract method.
But I would try to stick as much as possible to the *standard* interfaces from the `java.util.function` package (also a good source for examples of how to implement additional ones.)
|
A few years ago I created this set of generic functional interfaces with zero to three arguments, with and without return value. It covered 99% of my use cases since Java 8.
```
/**
* Functional Interfaces
*/
public class Functions {
/** 0 args, with return value */
@FunctionalInterface
public static interface Func0R<RETURN> {
public RETURN run() throws Exception;
default public RETURN runNoEx() {
try {
return run();
}
catch(Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
}
/** 1 args, with return value */
@FunctionalInterface
public static interface Func1R<ARG1, RETURN> {
public RETURN run(ARG1 arg1) throws Exception;
default public RETURN runNoEx(ARG1 arg1) {
try {
return run(arg1);
}
catch(Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
}
/** 2 args, with return value */
@FunctionalInterface
public static interface Func2R<ARG1, ARG2, RETURN> {
public RETURN run(ARG1 arg1, ARG2 arg2) throws Exception;
default public RETURN runNoEx(ARG1 arg1, ARG2 arg2) {
try {
return run(arg1, arg2);
}
catch(Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
}
/** 3 args, with return value */
@FunctionalInterface
public static interface Func3R<ARG1, ARG2, ARG3, RETURN> {
public RETURN run(ARG1 arg1, ARG2 arg2, ARG3 arg3) throws Exception;
default public RETURN runNoEx(ARG1 arg1, ARG2 arg2, ARG3 arg3) {
try {
return run(arg1, arg2, arg3);
}
catch(Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
}
/** 0 args, no return value (void) */
@FunctionalInterface
public interface Func0V {
public void run() throws Exception;
default public void runNoEx() {
try {
run();
}
catch(Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
}
/** 1 args, no return value (void) */
@FunctionalInterface
public static interface Func1V<ARG1> {
public void run(ARG1 arg1) throws Exception;
default public void runNoEx(ARG1 arg1) {
try {
run(arg1);
}
catch(Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
}
/** 2 args, no return value (void) */
@FunctionalInterface
public static interface Func2V<ARG1, ARG2> {
public void run(ARG1 arg1, ARG2 arg2) throws Exception;
default public void runNoEx(ARG1 arg1, ARG2 arg2) {
try {
run(arg1, arg2);
}
catch(Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
}
/** 3 args, no return value (void) */
@FunctionalInterface
public static interface Func3V<ARG1, ARG2, ARG3> {
public void run(ARG1 arg1, ARG2 arg2, ARG3 arg3) throws Exception;
default public void runNoEx(ARG1 arg1, ARG2 arg2, ARG3 arg3) {
try {
run(arg1, arg2, arg3);
}
catch(Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
}
}
```
Sample usage:
```
public class Component {
private Func1R<Component, Integer> strategy;
public void setStrategy(Func1R<Component, Integer> strategy) {
this.strategy = strategy;
}
public void calc() {
int result = this.strategy.runNoEx(this);
// ...
}
}
```
|
27,755,437
|
I have this code:
```
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
NSLog([NSString stringWithFormat:@"\n%g pixel \n=======================================",screenWidth]);
CGFloat imageWidth = [[self.widthArray objectAtIndex:indexPath.row] floatValue];
NSLog([NSString stringWithFormat:@"\n%f pixel\n=======================================",imageWidth]);
CGFloat ratio = screenWidth / imageWidth;
NSLog([NSString stringWithFormat:@"\nratio is %f\n=======================================",ratio]);
```
`screenWidth` and `imageWidth` is perfectly fine, but when I try to log `ratio` the program just crashes and the log says `(lldb)`. I still haven't found the solution yet anywhere. Any Sugestions?
EDIT:
the first two log is
```
2015-01-03 08:49:00.888 Huckleberry[6554:158359]
320.000000 pixel
=======================================
2015-01-03 08:49:00.889 Huckleberry[6554:158359]
512.000000 pixel
=======================================
```
and then the `ratio` is just `(lldb)`
|
2015/01/03
|
[
"https://Stackoverflow.com/questions/27755437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3927513/"
] |
If you see `(lldb)` in the console you've most likely hit a breakpoint. If you haven't added a breakpoint there yourself there might be an exception breakpoint in your project, catching all uncaught exceptions.
Try clicking on the "play" looking button above the console, that should continue the execution (or at least help you with what the crash was).
|
```
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
NSLog(@"Screen width = %f pixel", (float) screenWidth);
CGFloat imageWidth = [[self.widthArray objectAtIndex:indexPath.row] floatValue];
NSLog(@"Image width = %f pixel", (float) imageWidth]);
CGFloat ratio = screenWidth / imageWidth;
NSLog(@"ratio is %f", (float) ratio]);
```
|
12,978,404
|
I got the following query:
```
SELECT ur.repair_id, ur.repair_complete, ur.repair_noted_by_client, ur.repair_problem, ur.added_at, ur.added_by, ur.repaired_at, ur.repaired_by,
aa.account_fullname AS added_by_name,
ar.account_fullname AS repaired_by_name
FROM units_repairs AS ur
LEFT JOIN (SELECT account_id, account_fullname FROM accounts LIMIT 1) AS aa ON aa.account_id = ur.added_by
LEFT JOIN (SELECT account_id, account_fullname FROM accounts LIMIT 1) AS ar ON ar.account_id = ur.repaired_by
WHERE ur.unit_id = 1
```
It return the fullname only if the `account_id = 1`. If let say `repaired_by = 2` then it say `NULL`...
Thanks, I don't know what I am missing.
|
2012/10/19
|
[
"https://Stackoverflow.com/questions/12978404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1009061/"
] |
You are joining with inner query:
```
SELECT account_id, account_fullname FROM accounts LIMIT 1
```
where you have `LIMIT 1`, which gives you only one row (which probably has repaired\_by = 1), and then you want to filter and get only rows where repaired\_by is 2...and you don't have that one.
|
Probably there are no records that satisfy the condition `repaired_by = 2` in the line,
```
LEFT JOIN (SELECT account_id, account_fullname FROM accounts LIMIT 1) AS ar ON ar.account_id = ur.repaired_by
```
Hence, `ar.account_id = ur.repaired_by` returns NULL.
|
7,268
|
This is the basic layout of our apartment (not exactly to scale):
```
|==========--------====---------------------======|
| | | |
| | | |
| | | Master |
| | Bedroom | Bedroom |
| | 2 | |
| Living Room |---/ ----------| |
| 1 Hall [AC] / 3 |
| |-----------/ --|-/ -----/ ---|
| | | | |
| Kitchen | Bath | Bath | W.I. |
| | | | Closet |
|-------------------------------------------------|
```
Key:
* `/` door
* `1` large vent
* `2` small vent
* `3` small vent
* `=` window
* `[AC]` Air Conditioning intake
My girlfriend and I have our computer desks in the master bedroom. The problem we're having is only a fraction of the airflow comes out of vent 3 into the master bedroom, and it gets hot as \*\*\*\* in here. Note that for most of the day, the Master Bedroom window is in direct sunlight, aggravating the problem. We keep the blinds closed all day but are not allowed (by complex rules) to put anything in the window.
Normally ~60% of the airflow goes into the living room via vent `1`, ~30% goes into the smaller Bedroom via vent `2`, and ~10% of the airflow goes into the master bedroom via `3` (percentages estimated). If I close vent `2`, maybe ~15-20% comes out of vent `3` and the rest comes out of vent `1`.
The problem is that vent 1 is a gigantic vent and *cannot be closed*. Our apartment complex maintenance staff are useless; every time we ask them for help with the AC, they just reset the thermostat and say everything is fine.
I've tried jamming cardboard into vent 1 to close it off but it doesn't seem to work well enough. We keep the bathroom and closet doors closed to reduce the square footage that needs cooling, but that doesn't help enough.
I'm looking for any suggestions on *how to better control the air flow* (not just 'how to stay cool'), whether that's by better obstructing the vents, partitioning the house with dividers, adjusting circulation with fans placed in specific places, or something else. I'm not sure where to start, and hoping someone will have good suggestions. Thanks!
|
2015/06/01
|
[
"https://lifehacks.stackexchange.com/questions/7268",
"https://lifehacks.stackexchange.com",
"https://lifehacks.stackexchange.com/users/6941/"
] |
First, stop the extra heat from the window by putting up plastic in the window. Painters plastic should be good, just get a correctly sized piece and tape it up, making sure to completely seal the plastic to the window frame.
Next, I would put a big fan in a cold part of the living room and aim it down the hall to your room with the door open to let the cold air in.
Or you could blow the hot air from your room towards the thermostat so that the ac runs until your room is closer to acceptable.
If you want to block the big vent, you should take the vent down, then put the cardboard over the vent, then put the vent back up so the cardboard stays in place.
|
Two options spring to mind. First is to relocate into the living room with your computers as that room seems to be the coolest. In one flat I lived in I swapped rooms so that the master bed room became the living room and vice versa.
The other thought was that instead of blocking vent 1, which might damage the vent, what about rerouting the air flow? If you get a properly sized tube/pipe and then divide the output in two parts where one half enters the tube going through the hall and into your master bedroom it might solve your problem.
|
46,299,115
|
In my app I am sending post request with string value with Jquery, then in controller, passed string value is used to get some data from API.
Next controller returns a view and model with data from API inside. That data from model I want to put inside values of few textboxes.
The main problem is that I dont know how to refresh that div with model values. When I used post form without jquery and ajax it works but I want to do it asynchronous.
Js script with post request:
```
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
var data1 = $('#textBox').val();
$.ajax({
url: '/Home/Fill',
type: 'POST',
dataType: 'string',
data: { number:data1 },
success: function (data) {
}
});
});
});
```
Controller:
```
[HttpPost]
public ActionResult Fill(string number)
{
CompanyInfo Info = new CompanyInfo();
//Here some API actions
return View("Index",Info);
}
```
Div with model values inside the Index view:
```
<div id="target">
<h1>Number:</h1>
<input type="text" value="@Html.DisplayFor(m => m.Num)" id="Number" />
<br />
<h1>Company name:</h1>
<input type="text" value="@Html.DisplayFor(m=>m.CompanyName)" id="CompanyName" />
<br />
<h1>Street Address</h1>
<input type="text" value="@Html.DisplayFor(m=>m.StreetAddress)" id="Address" />
</div>
```
|
2017/09/19
|
[
"https://Stackoverflow.com/questions/46299115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8082886/"
] |
At this point you're not really working with "views and models" in the ASP.NET MVC sense, you're simply working with JavaScript/jQuery to update your DOM. How you do that depends on the data you have and is done entirely in here:
```
success: function (data) {
}
```
So what's in `data`?
This implies that you have HTML in `data`, perhaps even an entire page:
```
return View("Index",Info);
```
If that's the case, you probably want to select out of `data` the information you want. Is it *the same* page that you're already showing? If so then you can just replace the HTML you already have with the HTML from the page. Perhaps something like this:
```
var newTarget = $('#target', data).html();
$('#target').html(newTarget);
```
That should grab the HTML of the `div id="target"` from `data` and then set it to that same `div` in the current page.
If the HTML in `data` is different from the current page, then you would need to target what you're doing differently of course. But ultimately it's the same concept. Be aware that a side-effect of replacing HTML elements in your page with new elements is that any event binding you had on the old elements is lost.
---
Note that this isn't the most efficient way to do this. Returning *an entire page* when all you need is an updated model includes a lot of overhead that you just end up ignoring anyway. This would be a good opportunity to look into using WebAPI controllers in your project, where you could return plain objects:
```
return Info;
```
Or even just returning a `JsonResult` from your MVC controller would do the trick:
```
return Json(Info);
```
That way the `data` variable in your client-side code doesn't contain all of this unnecessary HTML, but instead contains *just* the information in the `Info` object. With that, you can simply update the values of your `input` elements directly. Perhaps something like this:
```
$('#Number').val(data.Num);
$('#CompanyName').val(data.CompanyName);
$('#Address').val(data.StreetAddress);
```
It's up to you how you want to approach it. But you definitely have options and can do a good bit of refactoring to simplify things.
|
You need to use the `success: function(data)` listener inside your AJAX request. Get your `data` and parse it into the div.
|
101,113
|
What happens if you encrypt data with a good cypher that produces a cyphertext that looks random (say, AES but avoiding ECB mode), and then apply a Vigenere cypher to the encrypted random-looking data?
1. Encrypt data so it looks random (for example with AES-CBC)
2. Choose a long random binary key for Vigenere (for example: cc3e87ba3f43...)
3. XOR that key repeatedly, as in a Vigenere cypher (although we modify bytes instead of letters)
Questions: how strong is that Vigenere cypher, and how can it be broken without having to bruteforce all the Vigenere keys? If it can't be broken without bruteforcing all the Vigenere keys, does that mean that in this scenario it becomes a safe cypher, and with a key longer than 256 bits we could obtain a cypher that is even stronger than AES?
|
2022/07/21
|
[
"https://crypto.stackexchange.com/questions/101113",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/102959/"
] |
If you already encrypted with a strong cipher (e.g AES-256) and a strong secret key, the data is secure without Vigenere applied on top.
Adding a Vigenere layer on top won't hurt security but what is it's purpose?
Vigenere is usually very easy to break using frequency analasis however if the data input into Vigenere is undistinguisable from random data removing the Vigenere is challenging. In fact if we encrypt with Vigenere truelu random data, the fact the Vigenere key is repeated doesn't help us, we still can't learn the key or peal the Vigenere encryption.
|
The answer is somewhere between a bad idea and perfect security. If the key is as long as the message or even longer, your Vigenere cypher becomes a One Time Pad. The latter is perfectly secure, but not good for practice.
One the other hand: Normal Vigenere is easy and fast to solve computationally. Therefore you may not gain any security benefits in general.
Note: The combination of cryptographic applications can also lead to a completely insecure scheme. Moreover, the current security of AES-256 is so strong that it does not need to be improved (especially not for private use).
|
5,774,158
|
I'm trying to run the following MySQL query:
```
SELECT *
FROM user u
JOIN user_categories uc ON u.user_id = uc.user_id
WHERE (uc.category_id = 3 OR uc.category_id = 1)
```
It currently returns:
```
Joe,Smith,60657,male
Joe,Smith,60657,male
Mickey,Mouse,60613,female
Petter,Pan,60625,male
Petter,Pan,60625,male
Donald,Duck,60615,male
```
If the user belongs to both categories it currently returns them twice. How can I return the user only once without using SELECT DISTINCT, regardless of how many categories they belong to?
|
2011/04/25
|
[
"https://Stackoverflow.com/questions/5774158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215863/"
] |
You need a semi join. This can be achieved with a sub query.
```
SELECT *
FROM user u
WHERE EXISTS(SELECT *
FROM user_categories uc
WHERE u.user_id = uc.user_id AND
uc.category_id IN(1,3))
```
In MySQL the performance of sub queries is quite problematic however so a `JOIN` and duplicate elimination via `DISTINCT` or `GROUP BY` may perform better.
|
Try using a GROUP BY
```
SELECT * FROM user u
JOIN user_categories uc ON u.user_id = uc.user_id
WHERE uc.category_id = 3 OR uc.category_id = 1
GROUP BY u.user_id
```
|
5,774,158
|
I'm trying to run the following MySQL query:
```
SELECT *
FROM user u
JOIN user_categories uc ON u.user_id = uc.user_id
WHERE (uc.category_id = 3 OR uc.category_id = 1)
```
It currently returns:
```
Joe,Smith,60657,male
Joe,Smith,60657,male
Mickey,Mouse,60613,female
Petter,Pan,60625,male
Petter,Pan,60625,male
Donald,Duck,60615,male
```
If the user belongs to both categories it currently returns them twice. How can I return the user only once without using SELECT DISTINCT, regardless of how many categories they belong to?
|
2011/04/25
|
[
"https://Stackoverflow.com/questions/5774158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215863/"
] |
You need a semi join. This can be achieved with a sub query.
```
SELECT *
FROM user u
WHERE EXISTS(SELECT *
FROM user_categories uc
WHERE u.user_id = uc.user_id AND
uc.category_id IN(1,3))
```
In MySQL the performance of sub queries is quite problematic however so a `JOIN` and duplicate elimination via `DISTINCT` or `GROUP BY` may perform better.
|
I don't know about MySQL, but in Postgres you *may* get better performance in the semi-join version from
```
SELECT * FROM user u
WHERE u.user_id
IN (SELECT user_id FROM user_categories uc WHERE uc.category_id IN (1,3));
```
I would expect `SELECT DISTINCT` to run fastest but I have learned my expectations and DB performance are often much different!
|
5,774,158
|
I'm trying to run the following MySQL query:
```
SELECT *
FROM user u
JOIN user_categories uc ON u.user_id = uc.user_id
WHERE (uc.category_id = 3 OR uc.category_id = 1)
```
It currently returns:
```
Joe,Smith,60657,male
Joe,Smith,60657,male
Mickey,Mouse,60613,female
Petter,Pan,60625,male
Petter,Pan,60625,male
Donald,Duck,60615,male
```
If the user belongs to both categories it currently returns them twice. How can I return the user only once without using SELECT DISTINCT, regardless of how many categories they belong to?
|
2011/04/25
|
[
"https://Stackoverflow.com/questions/5774158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215863/"
] |
I don't know about MySQL, but in Postgres you *may* get better performance in the semi-join version from
```
SELECT * FROM user u
WHERE u.user_id
IN (SELECT user_id FROM user_categories uc WHERE uc.category_id IN (1,3));
```
I would expect `SELECT DISTINCT` to run fastest but I have learned my expectations and DB performance are often much different!
|
Try using a GROUP BY
```
SELECT * FROM user u
JOIN user_categories uc ON u.user_id = uc.user_id
WHERE uc.category_id = 3 OR uc.category_id = 1
GROUP BY u.user_id
```
|
3,096,420
|
I have this problem with my homework
6. Let $E$ be a non-empty bounded set of real numbers and put $\alpha = \sup E ,$
and $\beta = \inf E$ . Assume that $\alpha \notin E$ and $\beta \notin E .$ Which of the following statements
is true and which is false. In each case justify your answer.
(a) $E$ is an open set.
(b) $E$ is not a closed set.
(c) $E$ is an infinite set.
(d) $( \alpha , \beta ) \subset E$
It's about general topology and inf and sup. We have to state whether each statement is true or false and justify by giving nice proofs. My assumptions are:
1)False
2)True
3)True
4)False
Please, I need help in writing appropriate proofs. I'm new to this course and still don't know how to write proofs. Any help is appreciated. I only have problems proving part d), if anyone can help me. Thank you!
|
2019/02/01
|
[
"https://math.stackexchange.com/questions/3096420",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/640177/"
] |
This is a huge question...
It depends on the precision you'd like and on the kind of input data you have.
For discrete methods, you can use [Delaunay triangulation](https://en.wikipedia.org/wiki/Delaunay_triangulation). See for example [Delaunay Triangulation Algorithm and Application to Terrain Generation](http://page.mi.fu-berlin.de/faniry/files/faniry_aims.pdf). You have commercial packages like <https://www.geo-media.com/solutions/logiciel-covadis/modele-numerique-de-terrain>.
[](https://i.stack.imgur.com/gZNIM.png)
You also have continuous methods that can be based on [spline surfaces](http://www.cs.cornell.edu/courses/cs4620/2013fa/lectures/17surfaces.pdf).
[](https://i.stack.imgur.com/mh3Rw.png)
|
RBF based interpolation worked great. I divide the world in degree blocks e.. 31-32 lat 40-41 lon would be one block, I sample about 40k elevation pts from each block and fit RBF Gaussian bumps, or multiquadric functions to smaller sections of a block. I save W matrix and lat, lons for the fit and I have my continuous function to recreate the terrain at any point.
<https://hal.archives-ouvertes.fr/hal-00308008/document>
|
17,246,800
|
I'm currently messing around with Twitter API, but this question isn't really related to Twitter API; it's just a general PHP question.
I'm pulling a couple queries of Tweets separately and then merging the requests together. And so, basically, I'm ending up with a final array something like this at the end of it all, where the Tweets aren't necessarily in the correct chronological order:
```
$tweets = array(
array(
'text' => 'Some tweet.',
'time' => 'Sat Jun 22 00:45:37 +0000 2013'
),
array(
'text' => 'And another.',
'time' => 'Fri Jun 21 15:32:34 +0000 2013'
),
array(
'text' => 'Another tweet.',
'time' => 'Fri Jun 21 17:24:44 +0000 2013'
),
array(
'text' => 'And one more tweet.',
'time' => 'Fri Jun 21 08:01:37 +0000 2013'
)
);
```
And now I'm just trying to figure out what the best way to sort this array by the timestamp of each Tweet is, in descending order.
I'm reading about `usort` and `uasort` but I'm not just quite understanding them, along with how they would correspond to using this timestamp as a comparison. So any help here would really be appreciated. Thanks in advance!
|
2013/06/22
|
[
"https://Stackoverflow.com/questions/17246800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391400/"
] |
There's two parts to this question.
First, you need a way to compare two times - a straight string comparison of the time in the given format won't give you any useful information. You can use [`strtotime()`](http://ca3.php.net/manual/en/function.strtotime.php) to convert the strings to a unix timestamp that is just a number of seconds - allowing you to easily make comparisons.
```
$ts = strtotime($item['time']);
```
The second part is actually sorting the array. You can do that with [`usort()`](http://php.net/manual/en/function.usort.php) and a callback function like this:
```
function do_compare($item1, $item2) {
$ts1 = strtotime($item1['time']);
$ts2 = strtotime($item2['time']);
return $ts2 - $ts1;
}
usort($tweets, 'do_compare');
// items in $tweets are now sorted by time
```
`usort()` works by calling your function - either named or anonymous - every time it needs to compare two elements. Your function needs to return a number less than zero if the first item comes first, zero if the items are equal, or greater than zero if the first item comes second. In your example, we're just subtracting the first timestamp from the second to get this value (if the first item is greater, the result will be negative, putting it first - a descending sort). The actual numeric value doesn't matter - just whether it's less than, equal to, or greater than zero.
Another way to do it without needing a named function is to use a [closure](http://ca3.php.net/manual/en/functions.anonymous.php) - or an [anonymous function](http://ca3.php.net/manual/en/functions.anonymous.php).
That would look like this:
```
usort($tweets, function($item1, $item2) {
$ts1 = strtotime($item1['time']);
$ts2 = strtotime($item2['time']);
return $ts2 - $ts1;
});
// items in $tweets are now sorted by time
```
This is essentially the same as the first solution, except we're defining the function inline instead of referring back to the name of a function that's been previously defined.
|
Use [array\_multisort](http://php.net/manual/en/function.array-multisort.php).
```
// Obtain a list of columns
foreach ($tweets as $key => $row) {
$text[$key] = $row['text'];
$time[$key] = strtotime($row['time']);
}
array_multisort($time, SORT_DESC);
```
|
57,248,774
|
I have the dataframe,
from that I converted to ndarray,
```
X = df.iloc[:].values
```
then I did the feature selection which gives me some columns [3,45,67,89,101,145,...]
as there are many columns may I know how to get back the corresponding column names in the dataframe
The reverse I can do using below code
```
cols = ['Amount','Savings_Amount','Loan_Term']
[df.columns.get_loc(c) for c in cols if c in df]
```
But I need to find names from the indices.
|
2019/07/29
|
[
"https://Stackoverflow.com/questions/57248774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11053801/"
] |
You can use [`object.keys([schema])`](https://joi.dev/api/#objectkeysschema), which
>
> Sets or extends the allowed object keys where:
>
>
>
>
> * `schema` - optional object where each key is assigned a **joi** type object.
> If `schema` is `{}` no keys allowed. If `schema` is `null` or `undefined`, any
> key allowed. If `schema` is an object with keys, the keys are added to
> any previously defined keys (but narrows the selection if all keys
> previously allowed). Defaults to 'undefined' which allows any child
> key.
>
>
>
Example:
```
const base = Joi.object().keys({
a: Joi.number(),
b: Joi.string()
});
// Validate keys a, b and c.
const extended = base.keys({
c: Joi.boolean()
});
```
|
Simply you can [spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) the `user` inside `ownerSchema`:
```
const ownerSchema = {
...user,
/* owner specific fields goes here */
};
```
|
3,061,094
|
Given an integer $n \in \Bbb{Z}$, we understand $\root 3 \of n$ to mean the number $x \in \Bbb{R}$ such that $x^3 - n = 0$. Then $\Bbb{Q}(\root 3 \of n) \subset \Bbb{R}$, right? The same then goes for the ring of algebraic integers $\mathcal{O}\_{\Bbb{Q}(\root 3 \of n)}$.
Since $\root 3 \of {-n} = -\root 3 \of n$, it follows that $\Bbb{Q}(\root 3 \of n) = \Bbb{Q}(\root 3 \of {-n})$ and likewise $\mathcal{O}\_{\Bbb{Q}(\root 3 \of n)} = \mathcal{O}\_{\Bbb{Q}(\root 3 \of {-n})}$. So in order for a ring adjoining a cubic root to $\Bbb{Q}$ to have complex numbers we need a cubic root that is imaginary or complex.
Therefore, given $$\omega = \frac{-1 + \sqrt{-3}}{2}$$ and $n > 1$, the ring of integers of $\Bbb{Q}(\omega \root 3 \of n)$ should contain complex numbers. What about the ring of $\Bbb{Q}(i \root 3 \of n)$? That is a distinct kind of rings than the other two I've mentioned, right?
Is this all correct? What kinds of cubic rings have I overlooked?
|
2019/01/03
|
[
"https://math.stackexchange.com/questions/3061094",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215060/"
] |
Things are so easy at algebraic degree $1$, we only have $\textbf Z$ to worry about.
At algebraic degree $2$, we have infinitely many real quadratic integer rings and infinitely many imaginary quadratic integer rings, but it still feels manageable because we're only dealing with two kinds of rings, plus $\textbf Z$.
Construct a polynomial of the form $x^2 + bx \pm 1$, where $b \in \textbf Z$. The "$\pm 1$" bit helps us narrow our focus down to units. By the quadratic equation, if we choose to go with $-1$, we have $$x = \frac{-b \pm \sqrt{b^2 + 4}}{2}$$ (in some cases you might have to rewrite things like $\sqrt{200}$ so that you have a squarefree number under the radical symbol).
When we go to algebraic degree $3$, the complexity suddenly explodes. And we find that complexity by doing for cubics something similar to what we did for quadratics just now. Construct a polynomial of the form $x^3 + ax^2 + bx \pm 1$, where $a \in \textbf Z$ also. For example, $1 - \root 3 \of 2$ is a zero of $x^3 - 3x^2 + 3x + 1$.
But try to solve $x^3 + x^2 - x + 1$, that turns out to be way beyond my meager computational skills. I turn to Wolfram Alpha for help, and it gives three answers all involving $\root 3 \of {19 - 3 \sqrt{33}}$. Whoa.
So yeah, you have overlooked a lot of kinds of rings.
|
Hmmm... our own Franz Lemmermeyer really needs to weigh in on this one. Seven years ago he wrote a paper on the "simplest cubic fields" in *Manuscripta Mathematica*.
There are
* Simply real cubic rings
* Totally real cubic rings
I'm not sure what the distinction is. Then of course there are imaginary cubic rings, whether or not they're obtained by adjoining the cubic root of an integer or by some other adjunction.
|
3,061,094
|
Given an integer $n \in \Bbb{Z}$, we understand $\root 3 \of n$ to mean the number $x \in \Bbb{R}$ such that $x^3 - n = 0$. Then $\Bbb{Q}(\root 3 \of n) \subset \Bbb{R}$, right? The same then goes for the ring of algebraic integers $\mathcal{O}\_{\Bbb{Q}(\root 3 \of n)}$.
Since $\root 3 \of {-n} = -\root 3 \of n$, it follows that $\Bbb{Q}(\root 3 \of n) = \Bbb{Q}(\root 3 \of {-n})$ and likewise $\mathcal{O}\_{\Bbb{Q}(\root 3 \of n)} = \mathcal{O}\_{\Bbb{Q}(\root 3 \of {-n})}$. So in order for a ring adjoining a cubic root to $\Bbb{Q}$ to have complex numbers we need a cubic root that is imaginary or complex.
Therefore, given $$\omega = \frac{-1 + \sqrt{-3}}{2}$$ and $n > 1$, the ring of integers of $\Bbb{Q}(\omega \root 3 \of n)$ should contain complex numbers. What about the ring of $\Bbb{Q}(i \root 3 \of n)$? That is a distinct kind of rings than the other two I've mentioned, right?
Is this all correct? What kinds of cubic rings have I overlooked?
|
2019/01/03
|
[
"https://math.stackexchange.com/questions/3061094",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215060/"
] |
It is a bit unclear to me exactly what kind of an answer you are looking for. Listing the following points that occurred to me while reading the question.
1. You don't need to use $\omega$ to get a cubic extension field containing non-real numbers. Any cubic polynomial $f(x)$, irreducible over $\Bbb{Q}$, such that $f$ has only a single real zero will yield such fields. For example, $f(x)=x^3-2x+2$, irreducible by Eisenstein, has a single real zero $\in(-2,-1)$. If $\alpha$ is one of the complex zeros of $f$, then $K\_1=\Bbb{Q}(\alpha)$ is a cubic field, and $\Bbb{Z}[\alpha]$ is a ring that as a an abelian group is free of rank three. The field $K\_1$ cannot be gotten by adjoining a cube root (real or complex) of an integer to $\Bbb{Q}$. A way of seeing that is to use the discriminants. The discriminant of $f(x)$ is $d(f)=-76$, implying that the discriminant of $\mathcal{O}\_{K\_1}$ is either $-76$ or $-19$. The discriminant of $g(x)=x^3-n$ is $d(g)=-27n^2$. The discriminants of orders of the same field can only differ by a factor that is a square, making it impossible for $\mathcal{O}\_{K\_1}$ to contain $\Bbb{Z}[\omega^j\root3\of n]$ for any alternative $j=0,1,2$ (so any root of $g(x)$).
2. Some cubic extension fields of $\Bbb{Q}$ are Galois extensions, implying that the minimal polynomials of all the elements have real zeros (all in that same field). An example appearing possibly the most frequently in our website is $K=\Bbb{Q}(2\cos(2\pi/9))$. The zeros of the irreducible polynomial $p(x)=x^3-3x+1$ are $2\cos(2^k\pi/9)$ with $k=1,2,3$, cyclically permuted by the mapping $r\mapsto r^2-2$. The ring of integers of $K$ is $\Bbb{Z}[2\cos(2\pi/9)]$. Here the discriminant is $d(p)=81$, the square of a rational number. This happens always with cubic Galois extensions.
3. The third primitive root of unity $\omega$ does play the following important role (look up Kummer theory for details and generalizations). If, instead of $\Bbb{Q}$, we use $F=\Bbb{Q}(\omega)$ as our base field, then we have the following characterization of cubic Galois extensions of $F$.
>
> Assume that $L$ is a cubic Galois extension of $F$, then there exists an element $z\in L$ such that $\alpha=z^3\in F$. In other words $L=F(\root3\of\alpha)$.
>
>
>
Of course, in the last bullet, $F$ has other types of cubic extensions, but none of those are Galois over $F$.
|
Hmmm... our own Franz Lemmermeyer really needs to weigh in on this one. Seven years ago he wrote a paper on the "simplest cubic fields" in *Manuscripta Mathematica*.
There are
* Simply real cubic rings
* Totally real cubic rings
I'm not sure what the distinction is. Then of course there are imaginary cubic rings, whether or not they're obtained by adjoining the cubic root of an integer or by some other adjunction.
|
3,061,094
|
Given an integer $n \in \Bbb{Z}$, we understand $\root 3 \of n$ to mean the number $x \in \Bbb{R}$ such that $x^3 - n = 0$. Then $\Bbb{Q}(\root 3 \of n) \subset \Bbb{R}$, right? The same then goes for the ring of algebraic integers $\mathcal{O}\_{\Bbb{Q}(\root 3 \of n)}$.
Since $\root 3 \of {-n} = -\root 3 \of n$, it follows that $\Bbb{Q}(\root 3 \of n) = \Bbb{Q}(\root 3 \of {-n})$ and likewise $\mathcal{O}\_{\Bbb{Q}(\root 3 \of n)} = \mathcal{O}\_{\Bbb{Q}(\root 3 \of {-n})}$. So in order for a ring adjoining a cubic root to $\Bbb{Q}$ to have complex numbers we need a cubic root that is imaginary or complex.
Therefore, given $$\omega = \frac{-1 + \sqrt{-3}}{2}$$ and $n > 1$, the ring of integers of $\Bbb{Q}(\omega \root 3 \of n)$ should contain complex numbers. What about the ring of $\Bbb{Q}(i \root 3 \of n)$? That is a distinct kind of rings than the other two I've mentioned, right?
Is this all correct? What kinds of cubic rings have I overlooked?
|
2019/01/03
|
[
"https://math.stackexchange.com/questions/3061094",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/215060/"
] |
I am copying the information below from [Daniel Harrer's diploma thesis](https://www.iazd.uni-hannover.de/fileadmin/institut/derenthal/papers/diplom-harrer.pdf), section 2.3; I believe it is originally due to Delone and Fadeev.
For any integers $a$, $b$, $c$, $d$, there is a commutative associative ring with basis $1$, $\alpha$, $\beta$ and multiplication table
$$\begin{array}{rccc}
\alpha^2 &=& b \alpha &- a \beta &-ac \\
\beta^2 &=& d \alpha &- c \beta &-bd \\
\alpha \beta &=& & & -ad \\
\end{array}$$
All cubic integral domains, and more generally all nilpotent-free cubic rings, are of this form.
These formulas define an integral domain if and only if the cubic polynomial $a z^3+b z^2 y + c z + d$ is irreducible. Indeed, if $\omega$ is a root of the irreducible $a z^3+b z^2 y + c z + d$, then we can embed this ring in $\mathbb{C}$ by $\alpha = - a \omega$ and $\beta = d/\omega$. (This paragraph isn't in Harrer.)
Two such cubic rings are isomorphic if and only if the cubics $ax^3+bx^2y+cxy^2+dy^3$ and $a'x^3+b'x^2y+c'xy^2+d'y^3$ are related by $GL\_2(\mathbb{Z})$ change of variables in $(x,y)$. (Here $GL\_2(\mathbb{Z})$ is $2 \times 2$ integer matrices with determinant $\pm 1$.) See Harrer for details.
I haven't seen anyone do this, but it seems natural to me: Let $\omega\_1$, $\omega\_2$, $\omega\_3$ be the roots of the cubic $az^3+bz^2+cz+d$ in $\mathbb{C}$. Then $GL\_2(\mathbb{Z})$ acts on these by Mobius transformations. If we restrict ourself to cubic fields with one real embedding, then one of the $\omega$'s will be in the upper half plane. We can use the $GL\_2(\mathbb{Z})$ action to move it into the [fundamental domain](https://en.wikipedia.org/wiki/Fundamental_domain#Fundamental_domain_for_the_modular_group) $|\mathrm{Re}(\omega)|<1/2$, $|\omega|>1$. So it seems to me that cubic rings with one real embedding have a natural canonical form where we require $az^3+bz^2+cz+d$ to have a root in the fundamental domain.
|
Hmmm... our own Franz Lemmermeyer really needs to weigh in on this one. Seven years ago he wrote a paper on the "simplest cubic fields" in *Manuscripta Mathematica*.
There are
* Simply real cubic rings
* Totally real cubic rings
I'm not sure what the distinction is. Then of course there are imaginary cubic rings, whether or not they're obtained by adjoining the cubic root of an integer or by some other adjunction.
|
11,204,894
|
I am working on an android project, the application is already built but just in order to improve the user interface. I am working on restyling the application.
For that I am also trying to use a custom font, but that is not working. I have gone through the sample codes available on the web but none doesn't solve my problem.
Here is how I am doing it.
```
package com.crittermap.backcountrynavigator.dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/handsean.ttf");
setTypeface(tf);
}
}
}
```
Here is the XML part
```
<com.crittermap.backcountrynavigator.dialog.MyTextView
android:id="@+id/offlinesummary"
android:layout_marginLeft="5dip"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/offlinecheckbox"
android:text="@string/cp_preview_off_desc"
style="@style/textN_l">
</com.crittermap.backcountrynavigator.dialog.MyTextView>
```
Style :
```
<style name="textN_l" parent="w_h">
<item name="android:textColor">@android:color/black</item>
<item name="android:textSize">12sp</item>
</style>
<style name="w_h"> <!-- Width and Height -->
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>
```
And the errors I am getting are
```
06-15 08:35:24.778: E/AndroidRuntime(2304): FATAL EXCEPTION: main
06-15 08:35:24.778: E/AndroidRuntime(2304): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.crittermap.backcountrynavigator.license/com.crittermap.backcountrynavigator.dialog.MapControlPanelDialog}: android.view.InflateException: Binary XML file line #24: Error inflating class com.crittermap.backcountrynavigator.dialog.MyTextView
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.os.Looper.loop(Looper.java:123)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Method.invokeNative(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Method.invoke(Method.java:507)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-15 08:35:24.778: E/AndroidRuntime(2304): at dalvik.system.NativeStart.main(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class com.crittermap.backcountrynavigator.dialog.MyTextView
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createView(LayoutInflater.java:518)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.Activity.setContentView(Activity.java:1657)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MapControlPanelDialog.onCreate(MapControlPanelDialog.java:72)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 11 more
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: java.lang.reflect.InvocationTargetException
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Constructor.constructNative(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createView(LayoutInflater.java:505)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 22 more
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: java.lang.RuntimeException: native typeface cannot be made
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.graphics.Typeface.<init>(Typeface.java:147)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.graphics.Typeface.createFromAsset(Typeface.java:121)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MyTextView.init(MyTextView.java:27)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MyTextView.<init>(MyTextView.java:17)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 25 more
```
Thank you
|
2012/06/26
|
[
"https://Stackoverflow.com/questions/11204894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175682/"
] |
Did you forget the namespace?
```
<com.crittermap.backcountrynavigator.dialog.MyTextView
android:id="@+id/offlinesummary"
android:layout_marginLeft="5dip"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/offlinecheckbox"
android:text="@string/cp_preview_off_desc"
android:style="@style/textN_l">
</com.crittermap.backcountrynavigator.dialog.MyTextView>
```
|
Try to add the layout width and height. Then, execute the program.
|
11,204,894
|
I am working on an android project, the application is already built but just in order to improve the user interface. I am working on restyling the application.
For that I am also trying to use a custom font, but that is not working. I have gone through the sample codes available on the web but none doesn't solve my problem.
Here is how I am doing it.
```
package com.crittermap.backcountrynavigator.dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/handsean.ttf");
setTypeface(tf);
}
}
}
```
Here is the XML part
```
<com.crittermap.backcountrynavigator.dialog.MyTextView
android:id="@+id/offlinesummary"
android:layout_marginLeft="5dip"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/offlinecheckbox"
android:text="@string/cp_preview_off_desc"
style="@style/textN_l">
</com.crittermap.backcountrynavigator.dialog.MyTextView>
```
Style :
```
<style name="textN_l" parent="w_h">
<item name="android:textColor">@android:color/black</item>
<item name="android:textSize">12sp</item>
</style>
<style name="w_h"> <!-- Width and Height -->
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>
```
And the errors I am getting are
```
06-15 08:35:24.778: E/AndroidRuntime(2304): FATAL EXCEPTION: main
06-15 08:35:24.778: E/AndroidRuntime(2304): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.crittermap.backcountrynavigator.license/com.crittermap.backcountrynavigator.dialog.MapControlPanelDialog}: android.view.InflateException: Binary XML file line #24: Error inflating class com.crittermap.backcountrynavigator.dialog.MyTextView
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.os.Looper.loop(Looper.java:123)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Method.invokeNative(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Method.invoke(Method.java:507)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-15 08:35:24.778: E/AndroidRuntime(2304): at dalvik.system.NativeStart.main(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class com.crittermap.backcountrynavigator.dialog.MyTextView
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createView(LayoutInflater.java:518)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.Activity.setContentView(Activity.java:1657)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MapControlPanelDialog.onCreate(MapControlPanelDialog.java:72)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 11 more
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: java.lang.reflect.InvocationTargetException
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Constructor.constructNative(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createView(LayoutInflater.java:505)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 22 more
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: java.lang.RuntimeException: native typeface cannot be made
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.graphics.Typeface.<init>(Typeface.java:147)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.graphics.Typeface.createFromAsset(Typeface.java:121)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MyTextView.init(MyTextView.java:27)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MyTextView.<init>(MyTextView.java:17)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 25 more
```
Thank you
|
2012/06/26
|
[
"https://Stackoverflow.com/questions/11204894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175682/"
] |
Did you forget the namespace?
```
<com.crittermap.backcountrynavigator.dialog.MyTextView
android:id="@+id/offlinesummary"
android:layout_marginLeft="5dip"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/offlinecheckbox"
android:text="@string/cp_preview_off_desc"
android:style="@style/textN_l">
</com.crittermap.backcountrynavigator.dialog.MyTextView>
```
|
change your code as
```
public class MyTextView extends TextView {
private Paint mPaint;
float middleY=1;
float mX=30;
float DY=30;
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/handsean.ttf");
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextSize(16);
mPaint.setColor(Color.BLACK);
mPaint.setTypeface(tf);
// setTypeface(tf);
}
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawColor(0xEFeffff);
Paint p = mPaint;
p.setTextAlign(Paint.Align.CENTER);
canvas.drawText("TESTEST", mX, middleY, p);
}
```
|
11,204,894
|
I am working on an android project, the application is already built but just in order to improve the user interface. I am working on restyling the application.
For that I am also trying to use a custom font, but that is not working. I have gone through the sample codes available on the web but none doesn't solve my problem.
Here is how I am doing it.
```
package com.crittermap.backcountrynavigator.dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/handsean.ttf");
setTypeface(tf);
}
}
}
```
Here is the XML part
```
<com.crittermap.backcountrynavigator.dialog.MyTextView
android:id="@+id/offlinesummary"
android:layout_marginLeft="5dip"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/offlinecheckbox"
android:text="@string/cp_preview_off_desc"
style="@style/textN_l">
</com.crittermap.backcountrynavigator.dialog.MyTextView>
```
Style :
```
<style name="textN_l" parent="w_h">
<item name="android:textColor">@android:color/black</item>
<item name="android:textSize">12sp</item>
</style>
<style name="w_h"> <!-- Width and Height -->
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>
```
And the errors I am getting are
```
06-15 08:35:24.778: E/AndroidRuntime(2304): FATAL EXCEPTION: main
06-15 08:35:24.778: E/AndroidRuntime(2304): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.crittermap.backcountrynavigator.license/com.crittermap.backcountrynavigator.dialog.MapControlPanelDialog}: android.view.InflateException: Binary XML file line #24: Error inflating class com.crittermap.backcountrynavigator.dialog.MyTextView
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.os.Looper.loop(Looper.java:123)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Method.invokeNative(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Method.invoke(Method.java:507)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-15 08:35:24.778: E/AndroidRuntime(2304): at dalvik.system.NativeStart.main(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class com.crittermap.backcountrynavigator.dialog.MyTextView
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createView(LayoutInflater.java:518)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.Activity.setContentView(Activity.java:1657)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MapControlPanelDialog.onCreate(MapControlPanelDialog.java:72)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 11 more
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: java.lang.reflect.InvocationTargetException
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Constructor.constructNative(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createView(LayoutInflater.java:505)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 22 more
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: java.lang.RuntimeException: native typeface cannot be made
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.graphics.Typeface.<init>(Typeface.java:147)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.graphics.Typeface.createFromAsset(Typeface.java:121)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MyTextView.init(MyTextView.java:27)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MyTextView.<init>(MyTextView.java:17)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 25 more
```
Thank you
|
2012/06/26
|
[
"https://Stackoverflow.com/questions/11204894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175682/"
] |
Did you forget the namespace?
```
<com.crittermap.backcountrynavigator.dialog.MyTextView
android:id="@+id/offlinesummary"
android:layout_marginLeft="5dip"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/offlinecheckbox"
android:text="@string/cp_preview_off_desc"
android:style="@style/textN_l">
</com.crittermap.backcountrynavigator.dialog.MyTextView>
```
|
try this
```
<com.crittermap.backcountrynavigator.dialog.MyTextView
android:id="@+id/offlinesummary"
android:layout_marginLeft="5dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/offlinecheckbox"
android:text="@string/cp_preview_off_desc"
android:style="@style/textN_l">
```
**UPDATE**
So other code is looks perfect. Only problem remains is in your ".ttf" file, may be this file is damaged. Download fonts from here developer.android.com/design/downloads/index.html and use them.
hope it will work.
|
11,204,894
|
I am working on an android project, the application is already built but just in order to improve the user interface. I am working on restyling the application.
For that I am also trying to use a custom font, but that is not working. I have gone through the sample codes available on the web but none doesn't solve my problem.
Here is how I am doing it.
```
package com.crittermap.backcountrynavigator.dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/handsean.ttf");
setTypeface(tf);
}
}
}
```
Here is the XML part
```
<com.crittermap.backcountrynavigator.dialog.MyTextView
android:id="@+id/offlinesummary"
android:layout_marginLeft="5dip"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/offlinecheckbox"
android:text="@string/cp_preview_off_desc"
style="@style/textN_l">
</com.crittermap.backcountrynavigator.dialog.MyTextView>
```
Style :
```
<style name="textN_l" parent="w_h">
<item name="android:textColor">@android:color/black</item>
<item name="android:textSize">12sp</item>
</style>
<style name="w_h"> <!-- Width and Height -->
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>
```
And the errors I am getting are
```
06-15 08:35:24.778: E/AndroidRuntime(2304): FATAL EXCEPTION: main
06-15 08:35:24.778: E/AndroidRuntime(2304): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.crittermap.backcountrynavigator.license/com.crittermap.backcountrynavigator.dialog.MapControlPanelDialog}: android.view.InflateException: Binary XML file line #24: Error inflating class com.crittermap.backcountrynavigator.dialog.MyTextView
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.os.Looper.loop(Looper.java:123)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Method.invokeNative(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Method.invoke(Method.java:507)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-15 08:35:24.778: E/AndroidRuntime(2304): at dalvik.system.NativeStart.main(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class com.crittermap.backcountrynavigator.dialog.MyTextView
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createView(LayoutInflater.java:518)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.Activity.setContentView(Activity.java:1657)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MapControlPanelDialog.onCreate(MapControlPanelDialog.java:72)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 11 more
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: java.lang.reflect.InvocationTargetException
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Constructor.constructNative(Native Method)
06-15 08:35:24.778: E/AndroidRuntime(2304): at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.view.LayoutInflater.createView(LayoutInflater.java:505)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 22 more
06-15 08:35:24.778: E/AndroidRuntime(2304): Caused by: java.lang.RuntimeException: native typeface cannot be made
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.graphics.Typeface.<init>(Typeface.java:147)
06-15 08:35:24.778: E/AndroidRuntime(2304): at android.graphics.Typeface.createFromAsset(Typeface.java:121)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MyTextView.init(MyTextView.java:27)
06-15 08:35:24.778: E/AndroidRuntime(2304): at com.crittermap.backcountrynavigator.dialog.MyTextView.<init>(MyTextView.java:17)
06-15 08:35:24.778: E/AndroidRuntime(2304): ... 25 more
```
Thank you
|
2012/06/26
|
[
"https://Stackoverflow.com/questions/11204894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175682/"
] |
Did you forget the namespace?
```
<com.crittermap.backcountrynavigator.dialog.MyTextView
android:id="@+id/offlinesummary"
android:layout_marginLeft="5dip"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/offlinecheckbox"
android:text="@string/cp_preview_off_desc"
android:style="@style/textN_l">
</com.crittermap.backcountrynavigator.dialog.MyTextView>
```
|
u have to use in xml as given below
```
<com.crittermap.backcountrynavigator.dialog.MyTextView
android:id="@+id/offlinesummary"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/offlinecheckbox"
android:text="@string/cp_preview_off_desc"
>
</com.crittermap.backcountrynavigator.dialog.MyTextView>
```
and in your any activity u have to use this way
```
MyTextView textview=(MyTextView)findViewById(R.id.offlinesummary);
```
|
12,899,282
|
I've started building Linux installers on the 64 bit windows version of Install4j recently and am getting the error below when it the generated installers start to do their extraction.
Is this something I'm doing wrong or is unsupported? Or a bug in 5.1 of install4j. I've recently upgraded to it as well.
```
Extracting files ...
yxN
An error occurred:
java.lang.IllegalArgumentException: Negative time
Error log: /tmp/install4jError8217531393990762392.log
java.lang.IllegalArgumentException: Negative time
at java.io.File.setLastModified(Unknown Source)
at com.install4j.runtime.installer.helper.fileinst.FileInstaller.install(Unknown Source)
```
|
2012/10/15
|
[
"https://Stackoverflow.com/questions/12899282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192789/"
] |
You are cloning the div **but not inserting** it anywhere in your DOM..
So it is non existent until you do that
```
var off = $(this).offset();
var div = $('#testtt').clone();
div.css({ position: "absolute", top: off.top, left: off.left });
$('body').append(div); <-- Appending to body here.. You can append anywhere you want
```
|
Probably an issue with duplicate id's
From the [API page](http://api.jquery.com/clone/):
>
> Note: Using .clone() has the side-effect of producing elements with
> duplicate id attributes, which are supposed to be unique. Where
> possible, it is recommended to avoid cloning elements with this
> attribute or using class attributes as identifiers instead.
>
>
>
After cloning, try changing the id of the cloned element:
```
div.attr('id').val('#testtt')
```
|
12,899,282
|
I've started building Linux installers on the 64 bit windows version of Install4j recently and am getting the error below when it the generated installers start to do their extraction.
Is this something I'm doing wrong or is unsupported? Or a bug in 5.1 of install4j. I've recently upgraded to it as well.
```
Extracting files ...
yxN
An error occurred:
java.lang.IllegalArgumentException: Negative time
Error log: /tmp/install4jError8217531393990762392.log
java.lang.IllegalArgumentException: Negative time
at java.io.File.setLastModified(Unknown Source)
at com.install4j.runtime.installer.helper.fileinst.FileInstaller.install(Unknown Source)
```
|
2012/10/15
|
[
"https://Stackoverflow.com/questions/12899282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192789/"
] |
You need to append div to your page. Currently, you have just created a reference to the clone without displaying it.
$("body").append(div);
|
in Jquery
```
$('.addRow').click(function(){
var off = $(this).offset();
var div = $('#testtt').clone();
div.css({ position: "absolute", top: off.top, left: off.left });
div.show();
div.appendTo($("#testtt");
```
})
|
12,899,282
|
I've started building Linux installers on the 64 bit windows version of Install4j recently and am getting the error below when it the generated installers start to do their extraction.
Is this something I'm doing wrong or is unsupported? Or a bug in 5.1 of install4j. I've recently upgraded to it as well.
```
Extracting files ...
yxN
An error occurred:
java.lang.IllegalArgumentException: Negative time
Error log: /tmp/install4jError8217531393990762392.log
java.lang.IllegalArgumentException: Negative time
at java.io.File.setLastModified(Unknown Source)
at com.install4j.runtime.installer.helper.fileinst.FileInstaller.install(Unknown Source)
```
|
2012/10/15
|
[
"https://Stackoverflow.com/questions/12899282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192789/"
] |
You need to append div to your page. Currently, you have just created a reference to the clone without displaying it.
$("body").append(div);
|
As per the comment from @andrewWhitaker, you need to add the new element to the DOM. e.g.
```
div.attr('id').val( div.attr('id')+"_cloned" );
$("#my_container_element_id").append(div);
```
You can also remove the
```
div.show();
```
|
12,899,282
|
I've started building Linux installers on the 64 bit windows version of Install4j recently and am getting the error below when it the generated installers start to do their extraction.
Is this something I'm doing wrong or is unsupported? Or a bug in 5.1 of install4j. I've recently upgraded to it as well.
```
Extracting files ...
yxN
An error occurred:
java.lang.IllegalArgumentException: Negative time
Error log: /tmp/install4jError8217531393990762392.log
java.lang.IllegalArgumentException: Negative time
at java.io.File.setLastModified(Unknown Source)
at com.install4j.runtime.installer.helper.fileinst.FileInstaller.install(Unknown Source)
```
|
2012/10/15
|
[
"https://Stackoverflow.com/questions/12899282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192789/"
] |
You are cloning the div **but not inserting** it anywhere in your DOM..
So it is non existent until you do that
```
var off = $(this).offset();
var div = $('#testtt').clone();
div.css({ position: "absolute", top: off.top, left: off.left });
$('body').append(div); <-- Appending to body here.. You can append anywhere you want
```
|
You have to attach the cloned div somewhere inside your html.
For example:
```
var off = $(this).offset();
var div = $('#testtt').clone();
div.css({ position: "absolute", top: off.top, left: off.left });
// append to parent of "this"
var parent = $(this).parent();
div.appendTo(parent);
// should be unnecessary, except if the style is display:none
//div.show();
```
|
12,899,282
|
I've started building Linux installers on the 64 bit windows version of Install4j recently and am getting the error below when it the generated installers start to do their extraction.
Is this something I'm doing wrong or is unsupported? Or a bug in 5.1 of install4j. I've recently upgraded to it as well.
```
Extracting files ...
yxN
An error occurred:
java.lang.IllegalArgumentException: Negative time
Error log: /tmp/install4jError8217531393990762392.log
java.lang.IllegalArgumentException: Negative time
at java.io.File.setLastModified(Unknown Source)
at com.install4j.runtime.installer.helper.fileinst.FileInstaller.install(Unknown Source)
```
|
2012/10/15
|
[
"https://Stackoverflow.com/questions/12899282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192789/"
] |
You need to append div to your page. Currently, you have just created a reference to the clone without displaying it.
$("body").append(div);
|
Probably an issue with duplicate id's
From the [API page](http://api.jquery.com/clone/):
>
> Note: Using .clone() has the side-effect of producing elements with
> duplicate id attributes, which are supposed to be unique. Where
> possible, it is recommended to avoid cloning elements with this
> attribute or using class attributes as identifiers instead.
>
>
>
After cloning, try changing the id of the cloned element:
```
div.attr('id').val('#testtt')
```
|
12,899,282
|
I've started building Linux installers on the 64 bit windows version of Install4j recently and am getting the error below when it the generated installers start to do their extraction.
Is this something I'm doing wrong or is unsupported? Or a bug in 5.1 of install4j. I've recently upgraded to it as well.
```
Extracting files ...
yxN
An error occurred:
java.lang.IllegalArgumentException: Negative time
Error log: /tmp/install4jError8217531393990762392.log
java.lang.IllegalArgumentException: Negative time
at java.io.File.setLastModified(Unknown Source)
at com.install4j.runtime.installer.helper.fileinst.FileInstaller.install(Unknown Source)
```
|
2012/10/15
|
[
"https://Stackoverflow.com/questions/12899282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192789/"
] |
You are cloning the div **but not inserting** it anywhere in your DOM..
So it is non existent until you do that
```
var off = $(this).offset();
var div = $('#testtt').clone();
div.css({ position: "absolute", top: off.top, left: off.left });
$('body').append(div); <-- Appending to body here.. You can append anywhere you want
```
|
You need to append it to another element by using `append()` or `appendTo()`.
|
12,899,282
|
I've started building Linux installers on the 64 bit windows version of Install4j recently and am getting the error below when it the generated installers start to do their extraction.
Is this something I'm doing wrong or is unsupported? Or a bug in 5.1 of install4j. I've recently upgraded to it as well.
```
Extracting files ...
yxN
An error occurred:
java.lang.IllegalArgumentException: Negative time
Error log: /tmp/install4jError8217531393990762392.log
java.lang.IllegalArgumentException: Negative time
at java.io.File.setLastModified(Unknown Source)
at com.install4j.runtime.installer.helper.fileinst.FileInstaller.install(Unknown Source)
```
|
2012/10/15
|
[
"https://Stackoverflow.com/questions/12899282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192789/"
] |
You have to attach the cloned div somewhere inside your html.
For example:
```
var off = $(this).offset();
var div = $('#testtt').clone();
div.css({ position: "absolute", top: off.top, left: off.left });
// append to parent of "this"
var parent = $(this).parent();
div.appendTo(parent);
// should be unnecessary, except if the style is display:none
//div.show();
```
|
Probably an issue with duplicate id's
From the [API page](http://api.jquery.com/clone/):
>
> Note: Using .clone() has the side-effect of producing elements with
> duplicate id attributes, which are supposed to be unique. Where
> possible, it is recommended to avoid cloning elements with this
> attribute or using class attributes as identifiers instead.
>
>
>
After cloning, try changing the id of the cloned element:
```
div.attr('id').val('#testtt')
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.