qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
14,929 | We have the following problem in the office: there is a colleague who, I think is nice enough once you get to know him a bit more closely. The thing is, most of the time he looks really grumpy or depressed. I don't really know how to read his face. He talks very little.
We could deal with that (there are seven persons in the room) but he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second. There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly.
Now, I do not want to offend him. I think it's just a thing he does without even thinking about it. I just want to ask him in a polite manner to try and close the door a bit more softly but can't think of a way that does not come across as rude or as passive aggressive.
Any thoughts on how I might go about that? | 2018/05/25 | [
"https://interpersonal.stackexchange.com/questions/14929",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/18238/"
] | It's beyond simple: The phrase you're looking for is "Do you mind" or "Would you mind" not letting the door close so noisily.
The title of the question is asking for "the right way". This is it.
Absent other factors which haven't been mentioned here, like previous interactions which would make this a touchy or difficult subject for conversation, this is a perfectly conventional request format which should convey the standard level of politeness and neutrality. If you say this, you're not making it about the colleague's bad mood, you're not accusing them of being unmannerly, you're just pointing out a disturbance and asking for consideration.
"I do not want to offend him" - Right, that's the beauty of these standard conventional phrases which we've inherited from generations past. Unless there's some other history or information here which makes you think that the standard request is going to offend him, go with the conventional standard mannerly phrase.
On the other hand, that's usually the best we can do, and we're really not responsible for unreasonable reactions on other people's part. If this person does act offended, that's an unforgivable imposition on **you**. | Perhaps your colleague "looks really grumpy or depressed. ... talks very little" because of something at home or elsewhere, that's probably not your business.
>
> "... he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second.".
>
>
>
So you object to the way he operates the door. He knows a special way to keep it vibrating.
>
> "There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly.".
>
>
>
That's understandable, but does everyone agree or are only you disturbed?
>
> "... but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?".
>
>
>
You need to figure out the results you want and how quickly you need them.
You don't want to come across as trying to portray him as an unsociable oaf, whom doesn't know how to operate a door.
If you were friends with this person it should be easy enough, but that doesn't seem the case.
You'll need to time your approach and decide how gingerly you want to proceed.
* Approach #1:
+ When he passes through the door ask if everything is OK.
+ If it is not ask if there's anything you can do, if everything is great even better.
+ Mention that he seems unhappy and has been slamming the door lately, it's come to the point where you need to bring this up; it's very disturbing.
* Approach #2:
+ Tell the boss, get them to resolve this. Suggest they pay to have the door *repaired*.
* Approach #3:
+ Tell them directly: "Shhhh!, there's no reason to be so noisy".
* Approach #4:
I tried searching the Internet for 'door operating instructions', I couldn't find anything (except for a dryer door); therein lies the problem ... You could try making a label and printing it on to a clear sticker - calculate his exact eye-height and line it up. Stick it to the door at lunch or after work anonymously.
I did manage to find something ***less*** than "Operating Instructions" but it should serve as a polite and anonymous hint:
[](http://www.pushandpullman.com/) |
14,929 | We have the following problem in the office: there is a colleague who, I think is nice enough once you get to know him a bit more closely. The thing is, most of the time he looks really grumpy or depressed. I don't really know how to read his face. He talks very little.
We could deal with that (there are seven persons in the room) but he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second. There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly.
Now, I do not want to offend him. I think it's just a thing he does without even thinking about it. I just want to ask him in a polite manner to try and close the door a bit more softly but can't think of a way that does not come across as rude or as passive aggressive.
Any thoughts on how I might go about that? | 2018/05/25 | [
"https://interpersonal.stackexchange.com/questions/14929",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/18238/"
] | If he enters the room and slams the door, ask him immediately like "don't you think that was too hard?". Or if he isn't afraid to destroy the door.
Reminding someone of this shouldn't yet be offending. Start with a hint to make him think about that. If this doesn't help, slowly become more direct.
Try to not say that every time at the beginning, see if it develops to get better. It can help to avoid he feels too guilty every time he walks through the door. Such habits need some time to vanish, there is a chance he slams the door and reminds oh next time I should no longer...
If he was a funny person you'd have a better position making stupid jokes about that. Such like "**BANGING DOOR** - oh colleague xy has arrived" or "has our next department exploded or is xy here?". But the way you describe him lets assume there is no big sense of humour.
It's important to discuss this with your colleagues, each of you should take turn to remind him. This doesn't make one single person the "bad guy" but shows that all of you are affected, this adds more seriousity to the topic. | I tend to agree with the answer Val provided. The simplest way to deal with this is to talk to the person.
If talking to the person, for whatever reason, is out of the question or uncomfortable, you could try posting a sign on the door asking that people be cautious when closing the door so as not to disrupt the office. Some might find this to be a bit passive aggressive, but it might raise awareness to your colleague and he may stop on his own. It may also provide the additional benefit of your colleague not feeling singled out. |
52,551,248 | I have an HTML page where the code is
```
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction(event) {
if (event.keyCode == 13) {
console.log(5 + 6);
return false;
}
}
</script>
<a href="#" id="descRef" onkeydown='myFunction(event)'><b>Search Description222</b></a>
</body>
</html>
```
It works and the function is triggered. But when I enable JAWS professional it does not trigger the function onkeypressdown | 2018/09/28 | [
"https://Stackoverflow.com/questions/52551248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5728426/"
] | You have to understand the difference between a screen reader's "browse mode" vs "forms mode". In "browse mode", the screen reader user can "browse" the DOM by using screen reader shortcut keys. For example, "H" will move the screen reader focus to the next heading, "B" will move to the next button, "L" will move to the next list, "T" will move to the next table, etc. These are all single character shortcut keys. No modifier (such as `ctrl` or `alt`) has to be pressed.
When the screen reader focus moves to an element that would like to have keyboard events, such as an input field, then there are options in the screen reader that "browse mode" can automatically change to "forms mode" (so that you can type stuff into a form field). JAWS will change modes automatically, but you can change your settings so that the mode must be changed manually. I suspect you have "automatic" set since it's the default.
However, this automatic change **only** happens for certain elements, such as an `<input>`. It does **not** happen for links because you don't normally type anything on a link (except ENTER).
So, to get keyboard events on a link, you must manually switch to "forms mode". For JAWS (it's different for NVDA), this can be done with `Ins` + `Z`. You'll hear "use virtual pc cursor OFF" when it changes. `Ins` + `Z` to toggle it back on (you'll hear "use virtual pc cursor ON").
After pressing `Ins` + `Z`, you should be able to type a letter while the focus is on the link and your event handler should run. | I found this answer: [Make onKeyDown trigger an HTML button's onClick event](https://stackoverflow.com/questions/10355895/make-onkeydown-trigger-an-html-buttons-onclick-event). Try to use Jquery syntax for passing a keyboard value in the a tag. look at the next code:
```
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script>
jQuery(function() {
jQuery(window).keypress(function(e){
if (e.keyCode === 13 && $('a:hover').length == true) {
console.log(5 + 6);
return false;
}
});
})
</script>
<a href="#" id="descRef"><b>Search Description222</b></a>
</body>
</html>
``` |
52,551,248 | I have an HTML page where the code is
```
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction(event) {
if (event.keyCode == 13) {
console.log(5 + 6);
return false;
}
}
</script>
<a href="#" id="descRef" onkeydown='myFunction(event)'><b>Search Description222</b></a>
</body>
</html>
```
It works and the function is triggered. But when I enable JAWS professional it does not trigger the function onkeypressdown | 2018/09/28 | [
"https://Stackoverflow.com/questions/52551248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5728426/"
] | You have to understand the difference between a screen reader's "browse mode" vs "forms mode". In "browse mode", the screen reader user can "browse" the DOM by using screen reader shortcut keys. For example, "H" will move the screen reader focus to the next heading, "B" will move to the next button, "L" will move to the next list, "T" will move to the next table, etc. These are all single character shortcut keys. No modifier (such as `ctrl` or `alt`) has to be pressed.
When the screen reader focus moves to an element that would like to have keyboard events, such as an input field, then there are options in the screen reader that "browse mode" can automatically change to "forms mode" (so that you can type stuff into a form field). JAWS will change modes automatically, but you can change your settings so that the mode must be changed manually. I suspect you have "automatic" set since it's the default.
However, this automatic change **only** happens for certain elements, such as an `<input>`. It does **not** happen for links because you don't normally type anything on a link (except ENTER).
So, to get keyboard events on a link, you must manually switch to "forms mode". For JAWS (it's different for NVDA), this can be done with `Ins` + `Z`. You'll hear "use virtual pc cursor OFF" when it changes. `Ins` + `Z` to toggle it back on (you'll hear "use virtual pc cursor ON").
After pressing `Ins` + `Z`, you should be able to type a letter while the focus is on the link and your event handler should run. | When Space or Enter is pressed while a link has focus, JAWS catches the keystroke, prevents the default behaviour and simulates a click instead. That's why KeyDown isn't working.
The expected behaviour for links is to load a new page or move the focus to a new place on the same page. Can you change the link to a button? You can get JAWS to respect the KeyDown event on buttons. |
6,253,576 | I'm actively developing desktop applications, local and network services, some classic ASP.NET, etc., so I'm used to static compilation and static code analysis. Now that I'm (finally) learning [ASP.NET MVC 3.0](http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework#Release_history) I'm seeing that many of the ASP.NET MVC experts and experienced developers are recommending using strongly-typed views in ASP.NET MVC 3.0 (where applicable).
I'm guessing that "strongly-typed" means writing `@model=...` at the top of a view's code. But in doing that I only get [IntelliSense](http://en.wikipedia.org/wiki/IntelliSense) to work, no static code checking is taking place. I can write anything I want in the `@model` statement in [cshtml](http://en.wikipedia.org/wiki/ASP.NET#Other_files) and it would compile and run. Consequentially, `Model.Anything` also compiles. In fact, if I *don't* type @model I can dynamically use whatever model I want that has "compatible" properties and methods.
I'm used to "strongly-typed" meaning "won't compile", like LINQ to *whatever* just will not compile if you don't get the properties right. Is there any other purpose for `@model` other than IntelliSense and a *run-time* error, and why is it called strong-typed if it's in fact, not?
*[Strong typing, Meanings in computer literature](http://en.wikipedia.org/wiki/Strong_typing#Meanings_in_computer_literature)* | 2011/06/06 | [
"https://Stackoverflow.com/questions/6253576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382783/"
] | Views are compiled at runtime by default. You can modify your project file (csproj) to compile the views when the application builds by setting the following property:
```
<MvcBuildViews>true</MvcBuildViews>
```
Downside of this approach is that your buildtime will increase significantly. You should consider only setting this option to true for release builds.
You can edit your project file by unloading the project, right-click the project and choose Edit ProjectFile | It is possible to setup your project so that it includes views in your compilation. This would be where static typing is useful. Another place would be in runtime, if you try to pass in a model that does not match the expected model you will immediately get an exception. If you were to type views dynamically then you would not know your model was invalid until your view tried to access a property of the model and finds out it isn't there.
The second scenario is also a nightmare if you pass in the wrong model object but it happens to have the same named property as the expected model. Then you just get invalid data and debugging becomes hell. |
6,253,576 | I'm actively developing desktop applications, local and network services, some classic ASP.NET, etc., so I'm used to static compilation and static code analysis. Now that I'm (finally) learning [ASP.NET MVC 3.0](http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework#Release_history) I'm seeing that many of the ASP.NET MVC experts and experienced developers are recommending using strongly-typed views in ASP.NET MVC 3.0 (where applicable).
I'm guessing that "strongly-typed" means writing `@model=...` at the top of a view's code. But in doing that I only get [IntelliSense](http://en.wikipedia.org/wiki/IntelliSense) to work, no static code checking is taking place. I can write anything I want in the `@model` statement in [cshtml](http://en.wikipedia.org/wiki/ASP.NET#Other_files) and it would compile and run. Consequentially, `Model.Anything` also compiles. In fact, if I *don't* type @model I can dynamically use whatever model I want that has "compatible" properties and methods.
I'm used to "strongly-typed" meaning "won't compile", like LINQ to *whatever* just will not compile if you don't get the properties right. Is there any other purpose for `@model` other than IntelliSense and a *run-time* error, and why is it called strong-typed if it's in fact, not?
*[Strong typing, Meanings in computer literature](http://en.wikipedia.org/wiki/Strong_typing#Meanings_in_computer_literature)* | 2011/06/06 | [
"https://Stackoverflow.com/questions/6253576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382783/"
] | Views are compiled at runtime by default. You can modify your project file (csproj) to compile the views when the application builds by setting the following property:
```
<MvcBuildViews>true</MvcBuildViews>
```
Downside of this approach is that your buildtime will increase significantly. You should consider only setting this option to true for release builds.
You can edit your project file by unloading the project, right-click the project and choose Edit ProjectFile | model is new dynamic type in .net 4.0, so these types get resolved at runtime not at compilation time. |
3,419 | I was reading a response on the meta here about how "clickbait" titles are annoying to that user (sorry about this one's title, friend). I find that nonstandard titles are better at getting eyes on a question and subsequently get more and better answers, which has lead me to trying to sensationalize my question titles a bit.
As they are now, some might not make sense without clicking on the question, but after you read the question it (hopefully) makes sense in context.
So, **are "clickbait" titles something that is generally frowned upon here?**
I can completely understand not having titles that have no bearing on the question, but is there a general distaste for non-question titles overall?
(Just as a note, the title for this one is an extreme example, and I have no weird old tips.) | 2016/03/24 | [
"https://worldbuilding.meta.stackexchange.com/questions/3419",
"https://worldbuilding.meta.stackexchange.com",
"https://worldbuilding.meta.stackexchange.com/users/18534/"
] | As I feel that I am the "that user" mentioned :), I'll explain my views on the subject.
We all know that reputation is a bunch of virtual points on an internet site. Nevertheless, we all like to accumulate them. As such we want our questions to be popular. Furthermore, as you mention, you want to attract enough people to get a good quality answer. Both of those are grounds to write an attractive title. A clickbait.
We probably all do that to some extend and that's fair game.
However, popularity do not always bring the best for the question. Yes, you get more reputation, yes you get more chance to get a better answer. However popular questions often get on the hot network questions list. And as such will attract many people less used to the site. Again, in itself, it isn't bad. Many/most of us joined Worldbuilding that way.
But, we tend to observe a few drawbacks:
* heavy upvotes on witty answers in detriment of more thorough ones,
* amplification of a ranking: most casual users won't bother reading all the answers, so the one with more upvotes... will get even more upvotes, when the other answers are forgotten,
* attract low quality answers: you accumulate more than 10 answers, often from newer users, who do not bring more to the question.
So clickbait titles are not necessarily bad. But one should not consider that they are always good. To get the best results in term of provided answer, it's best to have the most precise titles, to attract "experts". Quality over quantity. | I think the best "clickbait" is to **develop a reputation for asking well-framed, thought-provoking, and interesting questions**. That will lead to people from WB who know of you and your questions to say, "Ah, another `JGaines` question, this should be interesting!" (click)
That will lead to your question getting lots of views from WB regulars. That will lead to your question getting onto the HNQ (Hot Network Questions) list. That will let users from across all stacks view your title. This is where having an informative title that actually describes the gist of the question well is useful, since all they see is that one line, before deciding on whether to click or not. |
3,419 | I was reading a response on the meta here about how "clickbait" titles are annoying to that user (sorry about this one's title, friend). I find that nonstandard titles are better at getting eyes on a question and subsequently get more and better answers, which has lead me to trying to sensationalize my question titles a bit.
As they are now, some might not make sense without clicking on the question, but after you read the question it (hopefully) makes sense in context.
So, **are "clickbait" titles something that is generally frowned upon here?**
I can completely understand not having titles that have no bearing on the question, but is there a general distaste for non-question titles overall?
(Just as a note, the title for this one is an extreme example, and I have no weird old tips.) | 2016/03/24 | [
"https://worldbuilding.meta.stackexchange.com/questions/3419",
"https://worldbuilding.meta.stackexchange.com",
"https://worldbuilding.meta.stackexchange.com/users/18534/"
] | As I feel that I am the "that user" mentioned :), I'll explain my views on the subject.
We all know that reputation is a bunch of virtual points on an internet site. Nevertheless, we all like to accumulate them. As such we want our questions to be popular. Furthermore, as you mention, you want to attract enough people to get a good quality answer. Both of those are grounds to write an attractive title. A clickbait.
We probably all do that to some extend and that's fair game.
However, popularity do not always bring the best for the question. Yes, you get more reputation, yes you get more chance to get a better answer. However popular questions often get on the hot network questions list. And as such will attract many people less used to the site. Again, in itself, it isn't bad. Many/most of us joined Worldbuilding that way.
But, we tend to observe a few drawbacks:
* heavy upvotes on witty answers in detriment of more thorough ones,
* amplification of a ranking: most casual users won't bother reading all the answers, so the one with more upvotes... will get even more upvotes, when the other answers are forgotten,
* attract low quality answers: you accumulate more than 10 answers, often from newer users, who do not bring more to the question.
So clickbait titles are not necessarily bad. But one should not consider that they are always good. To get the best results in term of provided answer, it's best to have the most precise titles, to attract "experts". Quality over quantity. | Although clickbait titles may be entertaining, they don't really get the gist of the question across unless you actually make the effort to read the whole question. By your logic, I feel like you're doing the opposite of what you want to do: you're pushing potentially useful answers with a title that might seem random. Since only your question's title is shown in the Hot Questions bar and on Worldbuilding, you could probably attract more quality answers if you gave a basic idea of what your question was about in the title. I personally skim through new questions reading only the title and a misleading title would cause me to just skim over it, potentially missing a hidden gem. |
3,419 | I was reading a response on the meta here about how "clickbait" titles are annoying to that user (sorry about this one's title, friend). I find that nonstandard titles are better at getting eyes on a question and subsequently get more and better answers, which has lead me to trying to sensationalize my question titles a bit.
As they are now, some might not make sense without clicking on the question, but after you read the question it (hopefully) makes sense in context.
So, **are "clickbait" titles something that is generally frowned upon here?**
I can completely understand not having titles that have no bearing on the question, but is there a general distaste for non-question titles overall?
(Just as a note, the title for this one is an extreme example, and I have no weird old tips.) | 2016/03/24 | [
"https://worldbuilding.meta.stackexchange.com/questions/3419",
"https://worldbuilding.meta.stackexchange.com",
"https://worldbuilding.meta.stackexchange.com/users/18534/"
] | As I feel that I am the "that user" mentioned :), I'll explain my views on the subject.
We all know that reputation is a bunch of virtual points on an internet site. Nevertheless, we all like to accumulate them. As such we want our questions to be popular. Furthermore, as you mention, you want to attract enough people to get a good quality answer. Both of those are grounds to write an attractive title. A clickbait.
We probably all do that to some extend and that's fair game.
However, popularity do not always bring the best for the question. Yes, you get more reputation, yes you get more chance to get a better answer. However popular questions often get on the hot network questions list. And as such will attract many people less used to the site. Again, in itself, it isn't bad. Many/most of us joined Worldbuilding that way.
But, we tend to observe a few drawbacks:
* heavy upvotes on witty answers in detriment of more thorough ones,
* amplification of a ranking: most casual users won't bother reading all the answers, so the one with more upvotes... will get even more upvotes, when the other answers are forgotten,
* attract low quality answers: you accumulate more than 10 answers, often from newer users, who do not bring more to the question.
So clickbait titles are not necessarily bad. But one should not consider that they are always good. To get the best results in term of provided answer, it's best to have the most precise titles, to attract "experts". Quality over quantity. | The purpose of the question title is to **accurately and succintly summarize the most important parts of the question** in order to establish context for the question body.
The title itself cannot cover all the ground that the question text itself does. That's just not practical, let alone that it isn't the purpose of the title at all. This is even more so on a site like Worldbuilding, where we generally expect askers to lay out the background that any answers will need to adhere to in sufficient detail, and ideally also show what research the asker has done in trying to answer the question themselves or at the very least establish their knowledge level.
The title *can* and should however give a summary, such that (especially together with the tags) you can tell at a glance *what the OP is asking about.*
I have been known to downvote mercilessly any questions I come across where the title does not accurately summarize the question. In some cases I have also voted to close for the same reason.
Consider the title field placeholder text: **What's your worldbuilding question? Be specific.**
By all means feel free to write a "witty" or "clickbait" title, but *make sure it first and foremost fulfills its purpose of being a summary of the question.* |
3,419 | I was reading a response on the meta here about how "clickbait" titles are annoying to that user (sorry about this one's title, friend). I find that nonstandard titles are better at getting eyes on a question and subsequently get more and better answers, which has lead me to trying to sensationalize my question titles a bit.
As they are now, some might not make sense without clicking on the question, but after you read the question it (hopefully) makes sense in context.
So, **are "clickbait" titles something that is generally frowned upon here?**
I can completely understand not having titles that have no bearing on the question, but is there a general distaste for non-question titles overall?
(Just as a note, the title for this one is an extreme example, and I have no weird old tips.) | 2016/03/24 | [
"https://worldbuilding.meta.stackexchange.com/questions/3419",
"https://worldbuilding.meta.stackexchange.com",
"https://worldbuilding.meta.stackexchange.com/users/18534/"
] | I think the best "clickbait" is to **develop a reputation for asking well-framed, thought-provoking, and interesting questions**. That will lead to people from WB who know of you and your questions to say, "Ah, another `JGaines` question, this should be interesting!" (click)
That will lead to your question getting lots of views from WB regulars. That will lead to your question getting onto the HNQ (Hot Network Questions) list. That will let users from across all stacks view your title. This is where having an informative title that actually describes the gist of the question well is useful, since all they see is that one line, before deciding on whether to click or not. | Although clickbait titles may be entertaining, they don't really get the gist of the question across unless you actually make the effort to read the whole question. By your logic, I feel like you're doing the opposite of what you want to do: you're pushing potentially useful answers with a title that might seem random. Since only your question's title is shown in the Hot Questions bar and on Worldbuilding, you could probably attract more quality answers if you gave a basic idea of what your question was about in the title. I personally skim through new questions reading only the title and a misleading title would cause me to just skim over it, potentially missing a hidden gem. |
3,419 | I was reading a response on the meta here about how "clickbait" titles are annoying to that user (sorry about this one's title, friend). I find that nonstandard titles are better at getting eyes on a question and subsequently get more and better answers, which has lead me to trying to sensationalize my question titles a bit.
As they are now, some might not make sense without clicking on the question, but after you read the question it (hopefully) makes sense in context.
So, **are "clickbait" titles something that is generally frowned upon here?**
I can completely understand not having titles that have no bearing on the question, but is there a general distaste for non-question titles overall?
(Just as a note, the title for this one is an extreme example, and I have no weird old tips.) | 2016/03/24 | [
"https://worldbuilding.meta.stackexchange.com/questions/3419",
"https://worldbuilding.meta.stackexchange.com",
"https://worldbuilding.meta.stackexchange.com/users/18534/"
] | I think the best "clickbait" is to **develop a reputation for asking well-framed, thought-provoking, and interesting questions**. That will lead to people from WB who know of you and your questions to say, "Ah, another `JGaines` question, this should be interesting!" (click)
That will lead to your question getting lots of views from WB regulars. That will lead to your question getting onto the HNQ (Hot Network Questions) list. That will let users from across all stacks view your title. This is where having an informative title that actually describes the gist of the question well is useful, since all they see is that one line, before deciding on whether to click or not. | The purpose of the question title is to **accurately and succintly summarize the most important parts of the question** in order to establish context for the question body.
The title itself cannot cover all the ground that the question text itself does. That's just not practical, let alone that it isn't the purpose of the title at all. This is even more so on a site like Worldbuilding, where we generally expect askers to lay out the background that any answers will need to adhere to in sufficient detail, and ideally also show what research the asker has done in trying to answer the question themselves or at the very least establish their knowledge level.
The title *can* and should however give a summary, such that (especially together with the tags) you can tell at a glance *what the OP is asking about.*
I have been known to downvote mercilessly any questions I come across where the title does not accurately summarize the question. In some cases I have also voted to close for the same reason.
Consider the title field placeholder text: **What's your worldbuilding question? Be specific.**
By all means feel free to write a "witty" or "clickbait" title, but *make sure it first and foremost fulfills its purpose of being a summary of the question.* |
2,296,856 | I want to connect two devices using the GKSession, starting one as a server and the other one as a client. Using this configuration I can't use the GKPeerPickerController.
I'm having problems for connecting the two devices:
* Using only bluetooth: impossible
* using WiFi: at least there are some data exchange between the devices but no successfully conection.
In the interface file I have the
```
GKSessionDelegate
GKSession *session;
```
In the implementation, I start the server using this code:
```
session = [[GKSession alloc] initWithSessionID:@"iFood" displayName:nil sessionMode:GKSessionModeClient];
session.delegate = self;
session.available = YES;
```
The client starts using this code:
```
session = [[GKSession alloc] initWithSessionID:@"iFood" displayName:nil sessionMode:GKSessionModeServer];
session.delegate = self;
session.available = YES;
```
How I can force the use of Bluetooth instead of the WiFi ?
Also I have implemented those calls:
```
-(void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID {
NSLog(@"Someone is trying to connect");
}
- (BOOL)acceptConnectionFromPeer:(NSString *)peerID error:(NSError **)error {
NSLog(@"acceptConnectionFromPeer");
}
```
When I start, I get this into the debugger:
```
Listening on port 50775
2010-02-19 14:55:02.547 iFood[3009:5103] handleEvents started (2)
```
And when the other device starts to find, I get this:
```
~ DNSServiceBrowse callback: Ref=187f70, Flags=2, IFIndex=2 (name=[en0]), ErrorType=0 name=00eGs1R1A..Only by Audi regtype=_2c3mugr67ej6j7._udp. domain=local.
~ DNSServiceQueryRecord callback: Ref=17bd40, Flags=2, IFIndex=2 (name=[en0]), ErrorType=0 fullname=00eGs1R1A\.\.Only\032by\032Audi._2c3mugr67ej6j7._udp.local. rrtype=16 rrclass=1 rdlen=18 ttl=4500
** peer 1527211048: oldbusy=0, newbusy=0
~ DNSServiceBrowse callback: Ref=187f70, Flags=2, IFIndex=-3 (name=[]), ErrorType=0 name=00eGs1R1A..Only by Audi regtype=_2c3mugr67ej6j7._udp. domain=local.
GKPeer[186960] 1527211048 service count old=1 new=2
~ DNSServiceQueryRecord callback: Ref=17bd40, Flags=2, IFIndex=-3 (name=[]), ErrorType=0 fullname=00egs1r1a\.\.only\032by\032audi._2c3mugr67ej6j7._udp.local. rrtype=16 rrclass=1 rdlen=18 ttl=7200
** peer 1527211048: oldbusy=0, newbusy=0
~ DNSServiceBrowse callback: Ref=187f70, Flags=2, IFIndex=-3 (name=[]), ErrorType=0 name=00TF5kc1A..Only by Audi regtype=_2c3mugr67ej6j7._udp. domain=local.
~ DNSServiceQueryRecord callback: Ref=188320, Flags=2, IFIndex=-3 (name=[]), ErrorType=0 fullname=00tf5kc1a\.\.only\032by\032audi._2c3mugr67ej6j7._udp.local. rrtype=16 rrclass=1 rdlen=18 ttl=7200
** peer 1723356125: oldbusy=0, newbusy=0
~ DNSServiceQueryRecord callback: Ref=188320, Flags=2, IFIndex=2 (name=[en0]), ErrorType=0 fullname=00TF5kc1A\.\.Only\032by\032Audi._2c3mugr67ej6j7._udp.local. rrtype=16 rrclass=1 rdlen=18 ttl=4500
** peer 1723356125: oldbusy=0, newbusy=0
```
What I'm missing here ?
I'm sure that both devices have bluetooth enabled and connected into the same WiFi.
thanks,
r. | 2010/02/19 | [
"https://Stackoverflow.com/questions/2296856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266276/"
] | I think you miss to accept connection with client. After you receive the "didReceiveConnectionRequestFromPeer" callback, you need to accept connection with client like this:
```
-(void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID {
NSLog(@"Someone is trying to connect");
NSError *error;
[gkSession acceptConnectionFromPeer:peerID error:&error];
if(error)
NSLog(@"Error on accept connection with peer: ", error);
}
```
After this you will receive "GKPeerStateConnected" here:
```
- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state{}
```
I hope this help you. | I had similar problems, but from the description above I think you are making some
errors:
GKSession only implements BT; if you use the picker, then you can provide
separate methods for dealing with WiFi connections.
The "didReceiveConnectionRequestFromPeer" method should *call* the
"acceptConnectionFromPeer" method *on the session object* -- you do
not implement the "acceptConnectionFromPeer" on your delegate.
For debugging, you should log state changes in the delegate method
"session:peer:didChangeState:"
(see <http://developer.apple.com/iPhone/library/documentation/GameKit/Reference/GKSessionDelegate_Protocol/Reference/Reference.html> ). When a peer is "Available", you
can call "connectToPeer:"; when "Connected", you can use "sendData:toPeers:".
For IO after you have established a connection, you want to have called
the "setDataReceiveHandler:withContext:" method on the session.
Earlier I had some typos in my code but it is now working.
Good luck. |
3,517,943 | This is pretty self explanatory. How can I target only iphone for a popup. | 2010/08/19 | [
"https://Stackoverflow.com/questions/3517943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/424680/"
] | For Javascript and/or PHP:
<http://davidwalsh.name/detect-iphone> | [How do I detect Mobile Safari server side using PHP?](https://stackoverflow.com/questions/186734/how-do-i-detect-mobile-safari-server-side-using-php)
Will work with all web technologies -- not just php. |
39,245,973 | I'm writing signal processing library,
and I want to make this kind of hierarchy.
First, I defined `abstract class`
that define only "this wrapper class has one `double[]` field"
i.e.
```
public abstract class DoubleArray{
private final double[] array;
DoubleArray(double[] array){
this.array = array;
}
}
```
(I made constructor `package private` rather than `protected` because
I want to restrict usage of constructor outside the package)
(`System.arraycopy` is not used here
because this constructor is used only by me.)
Next, my first restriction is,
"cannot contain exceptional values"
i.e.
```
//inside the same package
public class SignalWithoutExceptionalValues extends DoubleArray{
SignalWithoutExceptionalValues(double[] signal){
super(signal);
for(double d : signal)
if(Double.isNaN(d) || Double.isInfinite(d))
throw new IllegalArgumentException("cannot contain exceptional values");
}
}
```
Next restriction is
"signal is in range of -1.0 ~ 1.0"
i.e.
```
//inside the same package
public final class OneAmplitudeSignal extends SignalWithoutExceptionalValues{
OneAmplitudeSignal(double[] signal){
super(signal);
for(double d : signal)
if(d > 1.0 || d < -1.0)
throw new IllegalArgumentException("is not normalized");
}
}
```
However, I think,
first of all,
I have to do `for-each` argument checking,
and then, after that,
assign to field.
but in this example,
I am forced to assign unchecked array to field,
because `DoubleArray` constructor must initialize `array` field.
So, my question is,
is there any strategy to do "**first checking then assign**"
in this kind of hierarchy.
**OR** this design is not appropriate for this purpose,
and there is another good design ?
Thank you.
**EDIT**
thank you for first two answers.
but by those solution,
library user can instantiate "illegal" signal,
because "checking mechanism can be overrided" .
However, I perfer inheritance
because `OneAmplitudeSignal` object can be
assigned to `SignalWithoutExceptionalValues` variables.
This fact corresponds to `OneAmp~` is **subset** of `SignalWithout~`.
Also, amplitude can be checked by `someSignal instanceof OneAmplitudeSignal` .
And "`final`" can't be used here
because I want to allow library users
to create new "**more restricted signal**"
or, "**new kind of restriction**" .
In addition, root class can be `non-abstract` .
in this case, "no restriction signal" can also be instantiated. | 2016/08/31 | [
"https://Stackoverflow.com/questions/39245973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You could extract the checking logic to a separate `check` method which the base constructor can execute prior to the assignment :
```
public abstract class DoubleArray{
private final double[] array;
protected abstract void check (double[] array);
DoubleArray(double[] array){
check(array);
this.array = array;
}
}
```
The sub-classes will override `check` to supply the required validation logic :
```
public class SignalWithoutExceptionalValues extends DoubleArray{
SignalWithoutExceptionalValues(double[] signal){
super(signal);
}
@Override
protected void check (double[] signal) {
for(double d : signal)
if(Double.isNaN(d) || Double.isInfinite(d))
throw new IllegalArgumentException("cannot contain exceptional values");
}
}
public final class OneAmplitudeSignal extends SignalWithoutExceptionalValues{
OneAmplitudeSignal(double[] signal){
super(signal);
}
@Override
protected void check (double[] signal) {
super.check ();
for(double d : signal)
if(d > 1.0 || d < -1.0)
throw new IllegalArgumentException("is not normalized");
}
}
``` | Since you are writing a library, it means that your library could be used in some cases you can't predict now. That's why I would avoid using inheritance because with inheritance you are scealing (enforcing) what you think is right in order to validate a signal by this static inheritance chain: `OneAmplitudeSignal` > `SignalWithoutExceptionalValues` > `DoubleArray`.
I would instead foster composition to do the validation. This is one possible implementation (more generic):
```
public interface Rule {
DoublePredicate getPredicate();
String getReason();
}
public final class ExceptionalValue implements Rule {
@Override
public DoublePredicate getPredicate() {
return d -> Double.isNaN(d) || Double.isInfinite(d);
}
@Override
public String getReason() {
return "cannot contain exceptional values";
}
}
public final class GreaterThanOneAmplitude implements Rule {
@Override
public DoublePredicate getPredicate() {
return d -> d > 1.0 || d < -1.0;
}
@Override
public String getReason() {
return "is not normalized";
}
}
public final class DoubleArray {
private final double[] array;
public DoubleArray(double[] signal, Collection<Rule> rules) {
for (Rule rule : rules) {
if (Arrays.stream(signal).anyMatch(rule.getPredicate())) {
throw new IllegalArgumentException(rule.getReason());
}
}
this.array = signal;
}
//...
}
```
On the other hand, if you don't need to (or want to) be generic simply do that:
```
public final class DoubleArray {
private final double[] array;
public DoubleArray(double[] signal) {
for(double d : signal) {
if(Double.isNaN(d) || Double.isInfinite(d)) {
throw new IllegalArgumentException("cannot contain exceptional values");
}
if(d > 1.0 || d < -1.0) {
throw new IllegalArgumentException("is not normalized");
}
}
this.array = signal;
}
//...
}
``` |
20,286,540 | I have written a simple function to toggle Fullscreen Mode on a web application. The application is only required to run in Chrome (eventually deployed under Kiosk mode), but there seems to be some strange behaviour with `cancelFullScreen` and `webkitCancelFullScreen`.
For example, here is the stripped down `toggleFullScreen` function:
```
var _isFullscreen = false;
function toggleFullScreen()
{
var doc = document.documentElement,
state = _inFullscreen,
requestFunc = (doc.requestFullScreen || doc.webkitRequestFullScreen),
cancelFunc = (doc.cancelFullScreen || doc.webkitCancelFullScreen);
_inFullscreen = !(state);
(!state) ? requestFunc.call(doc) : cancelFunc.call(doc);
}
```
For some strange reason, Chrome always reports that `cancelFunc` is `undefined`, even though `requestFunc` works fine.
Can anyone explain the reason for this, and a possible solution (without the need for jQuery or similar library plugins)? | 2013/11/29 | [
"https://Stackoverflow.com/questions/20286540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | With the help of @Tom Chung, and after playing around, it turns out that `cancelFullScreen` (and similarly `webkitCancelFullScreen` needs to be called on `document`, whereas `requestFullscreen` needs to be called on `document.documentElement`.
As such, the updated code as follows works fine:
```
function toggleFullScreen()
{
var doc = document.documentElement,
state = (document.webkitIsFullScreen || document.isFullScreen),
requestFunc = (doc.requestFullscreen || doc.webkitRequestFullScreen),
cancelFunc = (document.cancelFullScreen || document.webkitCancelFullScreen);
(!state) ? requestFunc.call(doc) : cancelFunc.call(document);
}
``` | ```
function toggleFullScreen()
{
//Post author DID NOT provide standards-compliant method at all.
//Standards compliant approaches should detect first.
//Prefixes are eventually removed / performance.
if ()//standards here
{
//standards here
}
else if (document.documentElement.webkitRequestFullScreen)
{
document.documentElement.webkitRequestFullScreen();
}
else if (document.webkitCancelFullScreen)
{
document.webkitCancelFullScreen();
}
}
```
Not sure why document.documentElement.webkitCancelFullScreen is undefined.
Maybe (I guess) the reason is that full screen effect can only be start once at the same time.
However, document.documentElement.webkitRequestFullScreen is required because document.documentElement give the element that is going to display in full screen.
Work perfectly in <http://jsfiddle.net/8mVBK/16/show/>
Update.
<http://jsfiddle.net/8mVBK/17/> |
20,286,540 | I have written a simple function to toggle Fullscreen Mode on a web application. The application is only required to run in Chrome (eventually deployed under Kiosk mode), but there seems to be some strange behaviour with `cancelFullScreen` and `webkitCancelFullScreen`.
For example, here is the stripped down `toggleFullScreen` function:
```
var _isFullscreen = false;
function toggleFullScreen()
{
var doc = document.documentElement,
state = _inFullscreen,
requestFunc = (doc.requestFullScreen || doc.webkitRequestFullScreen),
cancelFunc = (doc.cancelFullScreen || doc.webkitCancelFullScreen);
_inFullscreen = !(state);
(!state) ? requestFunc.call(doc) : cancelFunc.call(doc);
}
```
For some strange reason, Chrome always reports that `cancelFunc` is `undefined`, even though `requestFunc` works fine.
Can anyone explain the reason for this, and a possible solution (without the need for jQuery or similar library plugins)? | 2013/11/29 | [
"https://Stackoverflow.com/questions/20286540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | With the help of @Tom Chung, and after playing around, it turns out that `cancelFullScreen` (and similarly `webkitCancelFullScreen` needs to be called on `document`, whereas `requestFullscreen` needs to be called on `document.documentElement`.
As such, the updated code as follows works fine:
```
function toggleFullScreen()
{
var doc = document.documentElement,
state = (document.webkitIsFullScreen || document.isFullScreen),
requestFunc = (doc.requestFullscreen || doc.webkitRequestFullScreen),
cancelFunc = (document.cancelFullScreen || document.webkitCancelFullScreen);
(!state) ? requestFunc.call(doc) : cancelFunc.call(document);
}
``` | I am one of the developers working on [H5P](https://h5p.org), which supports fullscreen for all browsers supporting it. Below I have copied the parts of the code needed to exit fullscreen.
First we need to figure out the browser prefix
```
var fullScreenBrowserPrefix;
// Detect if we support fullscreen, and what prefix to use.
if (document.documentElement.requestFullScreen) {
/**
* Browser prefix to use when entering fullscreen mode.
* undefined means no fullscreen support.
* @member {string}
*/
fullScreenBrowserPrefix = '';
}
else if (document.documentElement.webkitRequestFullScreen) {
var safariBrowser = navigator.userAgent.match(/Version\/(\d)/);
safariBrowser = (safariBrowser === null ? 0 : parseInt(safariBrowser[1]));
// Do not allow fullscreen for safari < 7.
if (safariBrowser === 0 || safariBrowser > 6) {
fullScreenBrowserPrefix = 'webkit';
}
}
else if (document.documentElement.mozRequestFullScreen) {
fullScreenBrowserPrefix = 'moz';
}
else if (document.documentElement.msRequestFullscreen) {
fullScreenBrowserPrefix = 'ms';
}
```
Here's the code that invokes the correct exit-fullscreen-function:
```
if (fullScreenBrowserPrefix === '') {
document.exitFullscreen();
}
else if (fullScreenBrowserPrefix === 'moz') {
document.mozCancelFullScreen();
}
else {
document[fullScreenBrowserPrefix + 'ExitFullscreen']();
}
```
The code is copied from <https://github.com/h5p/h5p-php-library/blob/master/js/h5p.js> |
9,432,884 | We are using PostgreSQL with JPA which maps large strings to columns with type `TEXT`.
While programmatically we are able to read and write the data, pgAdmin and psql just show me the object ID when I select the data.
Is there a way/tool to quickly select the data without having to use some API (e.g., JDBC)?
An example:
```
doi=> \d+ xmlsnippet;
Table "doi.xmlsnippet"
Column | Type | Modifiers | Storage | Description
--------------+------------------------+-----------+----------+-------------
dbid | bigint | not null | plain |
version | bigint | not null | plain |
datasnippet | text | | extended |
doi | character varying(255) | | extended |
doipool_dbid | bigint | | plain |
```
The column `datasnippet` contains some large strings (with XML code)
When I select it, I get
```
doi=> select * from xmlsnippet;
dbid | version | datasnippet | doi | doipool_dbid
-------+---------+-------------+--------------------------+--------------
43 | 0 | 282878 | 10.3929/ethz-a-000077127 | 13
44 | 0 | 282879 | 10.3929/ethz-a-000085677 | 13
45 | 0 | 282880 | 10.3929/ethz-a-000085786 | 13
46 | 0 | 282881 | 10.3929/ethz-a-000087642 | 13
47 | 0 | 282882 | 10.3929/ethz-a-000088898 | 13
^^^^^^^
```
**Edit**: if I perform the same query using JDBC I get the expected content (the text I stored in the column) | 2012/02/24 | [
"https://Stackoverflow.com/questions/9432884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387981/"
] | Perhaps one of "the usual suspects" (i.e. JPA / Hibernate / PostgreSQL JDBC driver) mapped the column into the "Large Object" system of PostgreSQL.
A quick test in the `psql` shell:
```
db=> \lo_export 282878 /tmp/x.txt
lo_export
```
would export the stuff referenced by the first id from your example into the file `/tmp/x.txt`. Examine it with an editor. Tell us whether that's your data or not.
If this kind of mapping really happened, then you have a maintenance problem - large object must be deleted by hand and have some other intrinsic shortcomings. But that's another story. | In pgAdmin III, I use:
```
select dType, id, loread(lo_open(docxml::::int, 131072), 999999999) from XmlPadraoNFe
```
See: [pgAdmin III: How to view a blob?](https://stackoverflow.com/questions/14875748/pgadmin-iii-how-to-view-a-blob) |
32,926,452 | Assume there is a queue like this (the lines are only for clarity. They don't represent anything):
```
[1,1,1,
2,2,2,
3,3,
4,
5]
```
I want to sort it into this:
```
[1,2,3,4,5,
1,2,3,
1,2]
```
Is there an algorithm that solves this and if so, how is it called? | 2015/10/03 | [
"https://Stackoverflow.com/questions/32926452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238971/"
] | If you're writing in Python, check out the [Counter](https://docs.python.org/3.4/library/collections.html#collections.Counter) class which turns a list into a type of histogram:
```
from collections import Counter
l = [1, 1, 1,
2, 2, 2,
3, 3,
4,
5]
c = Counter(l)
result = []
for i in range(max(c.values())):
result += [k for k,v in c.items() if v > i]
print(result)
``` | There isn't any need to take the approach of counting occurrences described in [the levis501s approach](https://stackoverflow.com/questions/32926452/algorithm-name-for-sorting-of-numbers-into-ascending-groups/32926545#32926545) although it could well be argued that his code is more concise or more appropriate for Python environments.
You can solve this by repeating a loop until all the original elements are sorted and in that loop iterating through the list to find the smallest number that is greater than the last found number and popping it onto a result stack for that iteration and then terminating the inner loop when there aren't any larger numbers.
If you wanted to name the algorithm it to use, it could be a histogram sort variant or perhaps a bucket sort variant ... if you dug into parallel sorting algorithms, you may find something that more closely describes your problem.
Here's a Perl implementation:
```
my @a = reverse(qw/ 1 1 1 2 2 2 3 3 4 5/); ## Reverse order allows us to trim the array without messing up indexes
print qq{Source array = } . join(',',@a) . "\n";
my @bucket = ();
while ($#a >= 0)
{
my @bucket = (); ## Start a new bucket
for (my $i=$#a; $i>=0; $i--)
{
if ($#bucket == -1 && $a[$i]>0 || $bucket[$#bucket] < $a[$i])
{
push @bucket, $a[$i];
splice @a, $i, 1; ## Remove the element from the source data
}
}
print join(',', @bucket) . "\n"; ## Display the constructed bucket list
}
```
Or using an approach similar to levis501, again in Perl:
```
my @a = (1, 1, 1, 2, 2, 2, 3, 3, 4, 5);
my $hist = {};
foreach my $i (@a)
{
$hist->{$i}++;
}
while (scalar(%$hist)> 0)
{
foreach my $el (sort keys %$hist)
{
$hist->{$el}--;
print qq{$el};
delete $hist->{$el} if $hist->{$el}<1;
}
print "\n";
}
``` |
32,926,452 | Assume there is a queue like this (the lines are only for clarity. They don't represent anything):
```
[1,1,1,
2,2,2,
3,3,
4,
5]
```
I want to sort it into this:
```
[1,2,3,4,5,
1,2,3,
1,2]
```
Is there an algorithm that solves this and if so, how is it called? | 2015/10/03 | [
"https://Stackoverflow.com/questions/32926452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238971/"
] | If you're writing in Python, check out the [Counter](https://docs.python.org/3.4/library/collections.html#collections.Counter) class which turns a list into a type of histogram:
```
from collections import Counter
l = [1, 1, 1,
2, 2, 2,
3, 3,
4,
5]
c = Counter(l)
result = []
for i in range(max(c.values())):
result += [k for k,v in c.items() if v > i]
print(result)
``` | This answer is based on [levis501s'](https://stackoverflow.com/questions/32926452/algorithm-name-for-sorting-of-numbers-into-ascending-groups/32926545#32926545), but this seems simpler (or at least different). As with his answer, this uses Python although similar functionality can be implemented without too much effort in other high-level languages.
```
from collections import Counter
c = Counter([1, 1, 1, 2, 2, 2, 3, 3, 4, 5])
while c:
run = list(c)
run.sort()
for e in run:
print(e)
c[e] -= 1
if c[e] == 0:
del c[e]
``` |
32,926,452 | Assume there is a queue like this (the lines are only for clarity. They don't represent anything):
```
[1,1,1,
2,2,2,
3,3,
4,
5]
```
I want to sort it into this:
```
[1,2,3,4,5,
1,2,3,
1,2]
```
Is there an algorithm that solves this and if so, how is it called? | 2015/10/03 | [
"https://Stackoverflow.com/questions/32926452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238971/"
] | This answer is based on [levis501s'](https://stackoverflow.com/questions/32926452/algorithm-name-for-sorting-of-numbers-into-ascending-groups/32926545#32926545), but this seems simpler (or at least different). As with his answer, this uses Python although similar functionality can be implemented without too much effort in other high-level languages.
```
from collections import Counter
c = Counter([1, 1, 1, 2, 2, 2, 3, 3, 4, 5])
while c:
run = list(c)
run.sort()
for e in run:
print(e)
c[e] -= 1
if c[e] == 0:
del c[e]
``` | There isn't any need to take the approach of counting occurrences described in [the levis501s approach](https://stackoverflow.com/questions/32926452/algorithm-name-for-sorting-of-numbers-into-ascending-groups/32926545#32926545) although it could well be argued that his code is more concise or more appropriate for Python environments.
You can solve this by repeating a loop until all the original elements are sorted and in that loop iterating through the list to find the smallest number that is greater than the last found number and popping it onto a result stack for that iteration and then terminating the inner loop when there aren't any larger numbers.
If you wanted to name the algorithm it to use, it could be a histogram sort variant or perhaps a bucket sort variant ... if you dug into parallel sorting algorithms, you may find something that more closely describes your problem.
Here's a Perl implementation:
```
my @a = reverse(qw/ 1 1 1 2 2 2 3 3 4 5/); ## Reverse order allows us to trim the array without messing up indexes
print qq{Source array = } . join(',',@a) . "\n";
my @bucket = ();
while ($#a >= 0)
{
my @bucket = (); ## Start a new bucket
for (my $i=$#a; $i>=0; $i--)
{
if ($#bucket == -1 && $a[$i]>0 || $bucket[$#bucket] < $a[$i])
{
push @bucket, $a[$i];
splice @a, $i, 1; ## Remove the element from the source data
}
}
print join(',', @bucket) . "\n"; ## Display the constructed bucket list
}
```
Or using an approach similar to levis501, again in Perl:
```
my @a = (1, 1, 1, 2, 2, 2, 3, 3, 4, 5);
my $hist = {};
foreach my $i (@a)
{
$hist->{$i}++;
}
while (scalar(%$hist)> 0)
{
foreach my $el (sort keys %$hist)
{
$hist->{$el}--;
print qq{$el};
delete $hist->{$el} if $hist->{$el}<1;
}
print "\n";
}
``` |
45,552,444 | Hey I'm trying display a set of "tags" in a view controller using collection view cells but I'm having trouble finding a way to make them be able to dynamically resizable depending on the length of the string.
Right now the individual cells are statically sized so whenever a String that populates the cell with characters exceeding the size of the cell, it goes into the second line. I want it so that the cell can change length depending on the length of the String. So if it's the tag "#Vegan", it will automatically resize so that the tag isn't that big. Likewise, if it's a longer string like "#LaptopFriendly", it will become horizontally longer to accommodate the string and not use the second line. The vertical length can stay fixed. Thank you!
[](https://i.stack.imgur.com/8LjxR.png)
**UPDATE (interface builder settings when I run into errors using Rob's code):**
[](https://i.stack.imgur.com/QXpTR.png)
Simulator screenshot:
[](https://i.stack.imgur.com/CAhHF.png) | 2017/08/07 | [
"https://Stackoverflow.com/questions/45552444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8303592/"
] | You need unambiguous constraints between your label and the cell (e.g. leading, trailing, top, and bottom constraints):
[](https://i.stack.imgur.com/uS8of.png)
Then you can use `UICollectionViewFlowLayoutAutomaticSize` for the `itemSize` of your `collectionViewLayout`. Don't forget to set `estimatedItemSize`, too, which enables automatically resizing cells:
```
override func viewDidLoad() {
super.viewDidLoad()
let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = UICollectionViewFlowLayoutAutomaticSize
layout.estimatedItemSize = CGSize(width: 100, height: 40)
}
```
That yields:
[](https://i.stack.imgur.com/xPnMX.png) | You can calculate the lengths of the texts ahead of time, feed them into an array accessible by your collectionView and use them them to construct the size of the cell.
```
//Create vars
NSArray * texts = @[@"Short",@"Something Long",@"Something Really Long"];
NSMutableArray * lengths = [NSMutableArray new];
float padding = 30.0f;
//Create dummy label
UILabel * label = [UILabel new];
label.frame = CGRectZero;
label.font = [UIFont systemFontOfSize:20.0f weight:UIFontWeightBold];
//loop through the texts
for (NSString * string in texts){
//set text
label.text = string;
//calculate length + add padding
float length = [label.text boundingRectWithSize:label.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:label.font}
context:nil].size.width + padding;
//save value into array as NSNumber
[lengths addObject:@(length)];
}
//drop label
label = nil;
```
Create the size of the cell using some code like this:
```
return CGSizeMake(lengths[indexPath.row], 100.0f);
``` |
22,791,677 | I want the program to draw a circle whenever the screen gets touched and if the screen gets touched on another position I want the program to draw a circle again but without deleting the old one!
Now my problem is that it doesn't just draw a new circle in addition to the old one. It draws a new circle and deletes the old one. I tried to find a solution but nothing worked.
So can anyone please help me?
So it's working now!
--------------------
```
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
public class SingleTouchEventView extends View {
private Paint paint = new Paint();
List<Point> points = new ArrayList<Point>();
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);}
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
paint.setColor(Color.GREEN);
for(Point p: points){
canvas.drawCircle(p.x, p.y, 20, paint);
}
invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Point p = new Point();
p.x = (int)event.getX();
p.y = (int)event.getY();
points.add(p);
invalidate();
case MotionEvent.ACTION_MOVE: // a pointer was moved
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
break;
}
}
invalidate();
return true;
}
}
``` | 2014/04/01 | [
"https://Stackoverflow.com/questions/22791677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485877/"
] | You can achieve it by maintaining a list of points as a private instance variable:
```
private List<Point> points = new ArrayList<Point>;
```
Then you can add new points to this list every time a new touch event occurs:
```
Point p = new Point();
p.x = event.getX();
p.y = event.getY();
points.add(p);
invalidate();
```
Now in the onDraw() method you can print all the points in the list:
```
paint.setColor(Color.GREEN);
for(Point point: points){
canvas.drawCircle(point.x, point.y, 20, paint);
}
invalidate();
``` | Why not make a circle object which stores the coordinates of where to paint the circle, then add these objects to an array. Then in your paint method iterate through the array get the coordinates from each object and paint the circle using the coordinates?
So in your onclick method create a new circle object with the coordinates gained from the touch |
22,791,677 | I want the program to draw a circle whenever the screen gets touched and if the screen gets touched on another position I want the program to draw a circle again but without deleting the old one!
Now my problem is that it doesn't just draw a new circle in addition to the old one. It draws a new circle and deletes the old one. I tried to find a solution but nothing worked.
So can anyone please help me?
So it's working now!
--------------------
```
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
public class SingleTouchEventView extends View {
private Paint paint = new Paint();
List<Point> points = new ArrayList<Point>();
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);}
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
paint.setColor(Color.GREEN);
for(Point p: points){
canvas.drawCircle(p.x, p.y, 20, paint);
}
invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Point p = new Point();
p.x = (int)event.getX();
p.y = (int)event.getY();
points.add(p);
invalidate();
case MotionEvent.ACTION_MOVE: // a pointer was moved
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
break;
}
}
invalidate();
return true;
}
}
``` | 2014/04/01 | [
"https://Stackoverflow.com/questions/22791677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485877/"
] | You can achieve it by maintaining a list of points as a private instance variable:
```
private List<Point> points = new ArrayList<Point>;
```
Then you can add new points to this list every time a new touch event occurs:
```
Point p = new Point();
p.x = event.getX();
p.y = event.getY();
points.add(p);
invalidate();
```
Now in the onDraw() method you can print all the points in the list:
```
paint.setColor(Color.GREEN);
for(Point point: points){
canvas.drawCircle(point.x, point.y, 20, paint);
}
invalidate();
``` | one of my changing circle classes:
```
public class GrowCircle {
float x, y;int radius;
Paint myp = new Paint();
int colr,colg,colb;
int redvar=1;
int bluevar=5;
int greenvar=2;
int tripper=10;
int change=2;
Random rand = new Random();
public GrowCircle(float x, float y){
this.x=x;
this.y=y;
this.radius=2;
this.colr=rand.nextInt(254)+1;
this.colg=rand.nextInt(254)+1;
this.colb=rand.nextInt(254)+1;
}
public void update(){
if(tripper<=1||tripper>=15){
change=-change;
}
Random col = new Random();
myp.setColor(Color.argb(255,colr,colg,colb));
colr+=redvar;
colg+=greenvar;
colb+=bluevar;
if(colr<=5||colr>=250){
redvar=-redvar;
}
if(colg<=5||colg>=250){
greenvar=-greenvar;
}
if(colb<=5||colb>=250){
bluevar=-bluevar;
}
}
public void drawThis(Canvas canvas){
myp.setStrokeWidth(tripper);
myp.setStyle(Style.STROKE);
canvas.drawCircle(x, y, radius, myp);
}
}
```
so play with that and make it how you want and then do this:
///var declaration
```
CopyOnWriteArrayList<GrowCircle> gcirc= new CopyOnWriteArrayList<GrowCircle>();
```
//in update method
```
for(GrowCircle circ:gcirc){
circ.update();
}
```
// in draw method
```
for(GrowCircle circ:gcirc){
circ.drawThis(c);
}
//and in onTouch
float tx =event.getX();
float ty = event.getY();
gcirc.add(new GrowCircle(tx,ty));
``` |
47,184,745 | Angular5 introduced a new way of upgrating app from AngularJS to Angular -
`downgradeModule`. It should resolve an issue with to eager change detection in this kind of hybrid application. So far, in Angular4 I used `UpgradeModule` successfully, but it caused some performance issue because of change detections. Now I'm trying to use `downgradeModule`. In this approach AngularJS is started first, next downgradeModule starts Angular. In this way AngularJS in running outside of AngularZone, what should calm down change detection.
`main.ts` which is pointed in `.angular-cli.json` as "main"
```
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
import {enableProdMode, StaticProvider} from '@angular/core';
import { downgradeModule } from '@angular/upgrade/static';
enableProdMode();
declare var angular: any;
const bootstrapFn = (extraProviders: StaticProvider[]) => {
const platformRef = platformBrowserDynamic(extraProviders);
return platformRef.bootstrapModule(AppModule);
};
const myDowngradedModule = downgradeModule(bootstrapFn);
angular.bootstrap(document.documentElement, [
'legacyApp',
myDowngradedModule
]);
```
Now, AngularJS starts well, but Angular **does not**. No error on console, no tips. Just main selector eg. `<my-app>` is not evaluated.
Nothing changed in `app.module.ts` in context of previous working version.
```
@NgModule({
imports: [
CommonModule,
BrowserModule,
UpgradeModule,
RouterModule.forRoot([], { initialNavigation: false })
],
providers: [{provide: APP_BASE_HREF, useValue : '/shop/' }],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {
ngDoBootstrap() {}
}
```
I use some draft Angular doc, because the major one doesn't say anything about `downgradeModule`.
<https://pr18487-aedf0aa.ngbuilds.io/guide/upgrade-performance>
Does anyone know why Angular5 part is not starting?
Only for information purpose, the previous look of `main.ts` with `UpgradeModule` which worked quite well, but change detection.
```
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.documentElement, ['legacyApp']);
platformRef.injector.get(Router).initialNavigation();
});
``` | 2017/11/08 | [
"https://Stackoverflow.com/questions/47184745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/585773/"
] | I will self answer: for NSMutableArray there is no literal syntax, so you have to write:
```
self.box = [@[
[@[ _imageView1, _imageView2, _imageView3 ] mutableCopy],
[@[ _imageView4, _imageView5, _imageView6 ] mutableCopy],
[@[ _imageView7, _imageView8, _imageView9 ] mutableCopy]
] mutableCopy];
``` | If you wish to do it with fewer brackets than your own answer you can use:
```
self.box = @[
@[_imageView1, _imageView2, _imageView3].mutableCopy,
@[_imageView4, _imageView5, _imageView6].mutableCopy,
@[_imageView7, _imageView8, _imageView9].mutableCopy
].mutableCopy;
``` |
48,189,688 | Im trying to find if a .xlsx file contains a @.
I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns?
the code:
```
df = pandas.read_excel(open(path,'rb'), sheetname=0)
out = 'False'
for col in df.columns:
if df[col].str.contains('@').any():
out = 'True'
break
```
This is the error i'm getting:
```
df = pandas.read_excel(open(path,'rb'), sheetname=0)
File "/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 203, in read_excel
io = ExcelFile(io, engine=engine)
File "/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 258, in __init__
self.book = xlrd.open_workbook(file_contents=data)
File "/anaconda3/lib/python3.6/site-packages/xlrd/__init__.py", line 162, in open_workbook
ragged_rows=ragged_rows,
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 91, in open_workbook_xls
biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 1271, in getbof
bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 1265, in bof_error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\x17Microso'
``` | 2018/01/10 | [
"https://Stackoverflow.com/questions/48189688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495850/"
] | Take a look at the [json module](https://docs.python.org/3/library/json.html). More specifically the 'Decoding JSON:' section.
```
import json
import requests
response = requests.get() # api call
users = json.loads(response.text)
for user in users:
print(user['id'])
``` | It seems what you are looking for is the [json](https://docs.python.org/2/library/json.html) module. with it you can use this to parse a string into json format:
```
import json
output=json.loads(myJsonString)
``` |
48,189,688 | Im trying to find if a .xlsx file contains a @.
I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns?
the code:
```
df = pandas.read_excel(open(path,'rb'), sheetname=0)
out = 'False'
for col in df.columns:
if df[col].str.contains('@').any():
out = 'True'
break
```
This is the error i'm getting:
```
df = pandas.read_excel(open(path,'rb'), sheetname=0)
File "/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 203, in read_excel
io = ExcelFile(io, engine=engine)
File "/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 258, in __init__
self.book = xlrd.open_workbook(file_contents=data)
File "/anaconda3/lib/python3.6/site-packages/xlrd/__init__.py", line 162, in open_workbook
ragged_rows=ragged_rows,
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 91, in open_workbook_xls
biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 1271, in getbof
bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 1265, in bof_error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\x17Microso'
``` | 2018/01/10 | [
"https://Stackoverflow.com/questions/48189688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495850/"
] | Take a look at the [json module](https://docs.python.org/3/library/json.html). More specifically the 'Decoding JSON:' section.
```
import json
import requests
response = requests.get() # api call
users = json.loads(response.text)
for user in users:
print(user['id'])
``` | use python 3 and import urlib
```
import urllib.request
import json
url = link of the server
#Taking response and request from url
r = urllib.request.urlopen(url)
#reading and decoding the data
data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8'))
for json_inner_array in data:
for json_data in json_inner_array:
print("id: "+json_data["id"])
``` |
48,189,688 | Im trying to find if a .xlsx file contains a @.
I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns?
the code:
```
df = pandas.read_excel(open(path,'rb'), sheetname=0)
out = 'False'
for col in df.columns:
if df[col].str.contains('@').any():
out = 'True'
break
```
This is the error i'm getting:
```
df = pandas.read_excel(open(path,'rb'), sheetname=0)
File "/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 203, in read_excel
io = ExcelFile(io, engine=engine)
File "/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 258, in __init__
self.book = xlrd.open_workbook(file_contents=data)
File "/anaconda3/lib/python3.6/site-packages/xlrd/__init__.py", line 162, in open_workbook
ragged_rows=ragged_rows,
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 91, in open_workbook_xls
biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 1271, in getbof
bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 1265, in bof_error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\x17Microso'
``` | 2018/01/10 | [
"https://Stackoverflow.com/questions/48189688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495850/"
] | Take a look at the [json module](https://docs.python.org/3/library/json.html). More specifically the 'Decoding JSON:' section.
```
import json
import requests
response = requests.get() # api call
users = json.loads(response.text)
for user in users:
print(user['id'])
``` | You can try like below to get the values from json response:
```
import json
content=[{
"username": "admin",
"first_name": "",
"last_name": "",
"roles": "system_admin system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335509393,
"create_at": 1511335500662,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "pbjds5wmsp8cxr993nmc6ozodh"
}, {
"username": "chatops",
"first_name": "",
"last_name": "",
"roles": "system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335743479,
"create_at": 1511335743393,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "akxdddp5p7fjirxq7whhntq1nr"
}]
for item in content:
print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id']))
```
Output:
```
Name: admin
Email: [email protected]
ID: pbjds5wmsp8cxr993nmc6ozodh
Name: chatops
Email: [email protected]
ID: akxdddp5p7fjirxq7whhntq1nr
``` |
48,189,688 | Im trying to find if a .xlsx file contains a @.
I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns?
the code:
```
df = pandas.read_excel(open(path,'rb'), sheetname=0)
out = 'False'
for col in df.columns:
if df[col].str.contains('@').any():
out = 'True'
break
```
This is the error i'm getting:
```
df = pandas.read_excel(open(path,'rb'), sheetname=0)
File "/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 203, in read_excel
io = ExcelFile(io, engine=engine)
File "/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 258, in __init__
self.book = xlrd.open_workbook(file_contents=data)
File "/anaconda3/lib/python3.6/site-packages/xlrd/__init__.py", line 162, in open_workbook
ragged_rows=ragged_rows,
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 91, in open_workbook_xls
biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 1271, in getbof
bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 1265, in bof_error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\x17Microso'
``` | 2018/01/10 | [
"https://Stackoverflow.com/questions/48189688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495850/"
] | You can try like below to get the values from json response:
```
import json
content=[{
"username": "admin",
"first_name": "",
"last_name": "",
"roles": "system_admin system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335509393,
"create_at": 1511335500662,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "pbjds5wmsp8cxr993nmc6ozodh"
}, {
"username": "chatops",
"first_name": "",
"last_name": "",
"roles": "system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335743479,
"create_at": 1511335743393,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "akxdddp5p7fjirxq7whhntq1nr"
}]
for item in content:
print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id']))
```
Output:
```
Name: admin
Email: [email protected]
ID: pbjds5wmsp8cxr993nmc6ozodh
Name: chatops
Email: [email protected]
ID: akxdddp5p7fjirxq7whhntq1nr
``` | It seems what you are looking for is the [json](https://docs.python.org/2/library/json.html) module. with it you can use this to parse a string into json format:
```
import json
output=json.loads(myJsonString)
``` |
48,189,688 | Im trying to find if a .xlsx file contains a @.
I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns?
the code:
```
df = pandas.read_excel(open(path,'rb'), sheetname=0)
out = 'False'
for col in df.columns:
if df[col].str.contains('@').any():
out = 'True'
break
```
This is the error i'm getting:
```
df = pandas.read_excel(open(path,'rb'), sheetname=0)
File "/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 203, in read_excel
io = ExcelFile(io, engine=engine)
File "/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 258, in __init__
self.book = xlrd.open_workbook(file_contents=data)
File "/anaconda3/lib/python3.6/site-packages/xlrd/__init__.py", line 162, in open_workbook
ragged_rows=ragged_rows,
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 91, in open_workbook_xls
biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 1271, in getbof
bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
File "/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 1265, in bof_error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\x17Microso'
``` | 2018/01/10 | [
"https://Stackoverflow.com/questions/48189688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495850/"
] | You can try like below to get the values from json response:
```
import json
content=[{
"username": "admin",
"first_name": "",
"last_name": "",
"roles": "system_admin system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335509393,
"create_at": 1511335500662,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "pbjds5wmsp8cxr993nmc6ozodh"
}, {
"username": "chatops",
"first_name": "",
"last_name": "",
"roles": "system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335743479,
"create_at": 1511335743393,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "akxdddp5p7fjirxq7whhntq1nr"
}]
for item in content:
print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id']))
```
Output:
```
Name: admin
Email: [email protected]
ID: pbjds5wmsp8cxr993nmc6ozodh
Name: chatops
Email: [email protected]
ID: akxdddp5p7fjirxq7whhntq1nr
``` | use python 3 and import urlib
```
import urllib.request
import json
url = link of the server
#Taking response and request from url
r = urllib.request.urlopen(url)
#reading and decoding the data
data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8'))
for json_inner_array in data:
for json_data in json_inner_array:
print("id: "+json_data["id"])
``` |
70,464,882 | I want to know if a variable content can be used as variable name. Example below:
```
int a;
string b = "nombre";
```
I'm asking if "nombre" can replace "a" as variable name.
I'm trying to rename an object(like we rename files and folders). | 2021/12/23 | [
"https://Stackoverflow.com/questions/70464882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16421863/"
] | If you want to be able to map strings to numeric values, you could create a map object:
```
#include <unordered_map>
#include <string>
#include <iostream>
int main()
{
std::unordered_map<std::string, int> vars {
{ "nombre", 5 },
{ "otro_nombre", 3 },
};
std::cout << vars["nombre"] << '+' << vars["otro_nombre"]
<< " = " << (vars["nombre"] + vars["otro_nombre"]);
}
```
This yields:
```
5+3 = 8
```
on the output stream. See it working on [`GodBolt`](https://godbolt.org/z/5K57Mv9T6). | You can use references to create an alias for an already existing variables, if this is what you're looking for.
```
int a = 5;
int& nombre = a; //nombre is now an alias for a
``` |
4,028,676 | [Roughly speaking, the following question considers a special setting in which we want to prove a property in the form of $ord(g \sigma)\ |\ p^k$.]
**The Problem in Detail:**
Let $G$ be a finite group, and $H \leq G$ any subgroup with order $|H|=p^k$ (where $p$ is a prime, and $k \in \mathbb{N}$. Note that $H$ may not be a Sylow $p$-subgroup). Let $g \notin H$ be an element in $G$ s.t. $ord(g)\ |\ p^k $; and $\sigma\in G$ be s.t. for every integer $n$ we have $g^n \sigma g^{-n} \in H$. We claim that $ord(g \sigma)\ |\ p^k$.
(**Edit:** The previous claim is $ord(g) = ord(g \sigma)$, which is wrong due to the counterexample provided by @jpvee.)
**My Attempts:**
I can virtually do nothing other than expanding $(g \sigma)^l$, which does not contribute much.
I am quite confused on how to even start out the first step properly.
Can anyone please give me some hints on how I should proceed?
Thank you very much for your help!
:) | 2021/02/17 | [
"https://math.stackexchange.com/questions/4028676",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/846763/"
] | I have found a reference for proving this claim.
My claim is in fact a weaker version of the first lemma given in the article "On A Theorem of Frobenius" by Richard Brauer in 1969.
Since the proof is clearly presented in the original article (which can be easily accessed). I would not copy it down here :) | Sorry to disappoint you, but your conjecture is false. One counterexample I could come up with is the following:
Let $G:=S\_4$ be the symmetric group on four points, let $H:=\langle\,(1,2,3,4),(1,3)\,\rangle$ be a Sylow $2$-subgroup. Now choose $g:=(1,4)$ and $\sigma:=(1,2)(3,4)$.
Then $g\not\in H$, and $g^n\sigma g^{-n}\in H$ for all $n\in\mathbb{Z}$ (since $\sigma$ is an element of the Klein subgroup which is a normal subgroup of $G$ contained in $H$).
On the other hand, we have $g\sigma=(1,3,4,2)$ and thus $ord(g)=2\neq4=ord(g\sigma)$ |
23,247,923 | I know this is a noob error but I really can't discover why it's coming up as I am accessing an object that is set.
The `xloc` and `yloc` both being local variables.
```
gameBorder.FormInstance.tableLayoutPanel1.GetControlFromPosition(xloc, yloc).BackgroundImage = Properties.Resources.Image;
```
However this has been set within the form class:
```
namespace csharp_build
{
public partial class gameBorder : Form
{
public static gameBorder FormInstance;
public gameBorder()
{
FormInstance = this;
InitializeComponent();
}
}
}
```
Any idea why this happens? Would it be to do with the fact that the form class is referenced as `gameBorder`, and that is what the constructor is called, and the name for the form class in the solution explorer is Form1.cs?
I know this is a noob problem and I do apolagize but any help would be greatly appreciated. | 2014/04/23 | [
"https://Stackoverflow.com/questions/23247923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3375561/"
] | If you are sure that `tableLayoutPanel1` exists and is not null, then change your code to this and see what happens:
```
var control = gameBorder.FormInstance.tableLayoutPanel1.GetControlFromPosition
(xloc, yloc);
if (control == null) throw new NullReferenceException(
"No control at those coordinates");
control.BackgroundImage = Properties.Resources.Image;
```
jeez, guys, this is code for analysis, debugging, to help figure out illustrate the cause of the issue, that's all.....
WARNING WARNING WARNING: NOT INTENDED AS FINAL PRODUCTION CODE
Thanks to @SriramSakthivel comments below, please Note that `NullReferenceException` is being thrown here only for debugging/Analysis purposes, and should never be thrown by application code in production release. | The way you chain members and method results makes it hard to determine at a glance what causes the `NullReferenceException` to be thrown. `FormInstance` could be `null` if it's accessed before any `gameBorder` instances ever get created. Although unlikely, `tableLayoutPanel` could be `null` as well. The result of `GetControlFromPosition` method could very well be too, if no control is on the specified cell.
When you are encountering this kind of problem within this kind of code, the best thing to do is to decompose the calling chain. This way you will be able to quickly tell where the problem lies.
You can also make [code assertions](http://msdn.microsoft.com/en-us/library/vstudio/system.diagnostics.debug.assert), like this:
```
var formInstance = gameBorder.FormInstance;
Debug.Assert(formInstance != null);
var controlAtPos = formInstance.tableLayoutPanel1.GetControlFromPosition(xloc, yloc);
Debug.Assert(controlAtPos != null);
controlAtPos.BackgroundImage = Properties.Resources.Image; // You may want to make some assertions on resolving your image instance too
```
The beauty of code assertions is that it's easy to exclude these from compiling into production code. By default, it's compiled in debug configuration and excluded in release configuration. This way you can benefit from the help it provides on debugging without worrying about the extra overhead in deployed code.
Keep this in mind, it will be useful if you ever face this issue again in the future. |
69,218,168 | So I have some question abaout how to correctly use FutureBuilder. I read somewhere that we should store the future in a variable and call that variable in the FutureBuilder instead of the future service. But how do we initalize the initial value of that variable? When I tired this, it always gives `LateInitializationError: Field '_dataFuture@28307501' has not been initialized.` and should wait until the data is loaded.
```
late Future<List<TransaksiResp>> _dataFuture;
@override
void initState() {
super.initState();
transaksiService = TransaksiService();
getUserPrefs().then((value) {
setState(() {
_dataFuture = transaksiService.getTransaksi(user[2]);});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Flexible(
child: SizedBox(
child: FutureBuilder<List<TransaksiResp>>(
future: _dataFuture,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasError) {
print(snapshot);
return Center(
child: Text("Error"),
);
} else if (snapshot.hasData){
List<TransaksiResp> response = snapshot.data;
return _buildListView(response);
} else {
return Center(
child: Container(),
);
}
},
),
),
)
],
),
);
}
```
This is getUserPrefs method to get user data from Shared Preference
```
Future<void> getUserPrefs() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
user = prefs.getStringList("user")!;
setState(() {});
}
``` | 2021/09/17 | [
"https://Stackoverflow.com/questions/69218168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11214886/"
] | Get the answer, because I need the data from SharedPreferences, I need to wait for the function to finish first
```
_getService() async {
await getUserPrefs();
return await transaksiService.getTransaksi(user[2]);
}
```
Then calling it in `iniState` and save it in a variable
```
_dataFuture = _getService();
``` | * **FutureBuilder** removes boilerplate code.
* FutureBuilder Widget is used to create widgets based on the latest snapshot of interaction with a Future. It is necessary for Future to
be obtained earlier either through a change of state or change in dependencies.
If you get data from API refer my answer [here](https://stackoverflow.com/a/68709502/13997210) or [here](https://stackoverflow.com/a/68533647/13997210) or [here](https://stackoverflow.com/a/68594656/13997210) hope it's helpful to you in this examples I have used FutureBuilder refer it.
refer documentation [here](https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html) for **FutureBuilder**
You aslo refer [here](https://medium.com/nonstopio/flutter-future-builder-with-list-view-builder-d7212314e8c9)
Hope its help to you |
74,021,821 | I have a large pandas dataframe with common sentences 'S', which I'd like to learn, and their counts 'C', like this:
```py
df = pd.DataFrame({"S": ["Yes.", "Yes!", "Yes?",
"No?", "No.", "What?"],
"C": [100, 50, 40, 30, 10, 5]})
df
S C
0 Yes. 100
1 Yes! 50
2 Yes? 40
3 No? 30
4 No. 10
5 What? 5
```
If sentences are the same up to their last character, I'd like to collapse them into one, represented by the most common sentence, while adding up the counts across the group. The resulting dataframe should look like this:
```py
S C
0 Yes. 190
1 No? 40
2 What? 5
```
In the same way, I have list of common words - some lowercase, some uppercase - and I'd like to add the counts across the lower/uppercase group while retaining only the most common case. | 2022/10/11 | [
"https://Stackoverflow.com/questions/74021821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13466303/"
] | Your Lambda will be running in a serverless compute environment, not in your EC2. That means the `log` directory that you are traversing is in the serverless Lambda environment, not the `log` directory in your EC2 instance. My guess is, the Lambda `log` directory contains no log files. Hence, the code ran successfully without uploading anything to S3.
My suggestion is to keep this python as a local script in the instance. Then, as you have already indicated, you can use AWS SSM to trigger this script. | you probably miss to install in your ec2 the cloudwatch agent.
<https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html>
Furthermore, there is no need to "move" log between services, because AWS provide automatic logging for everything, with Cloudwatch and Cloudtrail services |
48,474,941 | I want to make `QLabel` with the image circle:
**Code:**
```
QLabel *label = new QLabel(this);
QPixmap avatarPixmap(":/Icon/default_avatar.png");
label->setPixmap(avatarPixmap);
label->setStyleSheet("border: 0.5px solid red; border-radius: 50%; background-clip: padding;");
```

It only rounds the `QLabel`, not the image. How to fix it? Thanks.
**Update:**
The only way is to override the `paintEvent` for `QLabel`
**Code:**
```
void AccountImage::paintEvent(QPaintEvent *event)
{
QPixmap pixmap(":/Icon/default_avatar.png");
QBrush brush(pixmap);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(brush);
painter.drawRoundedRect(0, 0, width(), height(), 100, 100);
QLabel::paintEvent(event);
}
```

The image is rounded but not properly scaled. Any ideas? | 2018/01/27 | [
"https://Stackoverflow.com/questions/48474941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731050/"
] | try to set mask on the label like:
```
int w = // set the width here
int h = // set the height here
QRect *rct = new QRect(0, 0, w, h);
QRegion *reg = new QRegion(*rct, QRegion::Ellipse);
label->setMask(*reg);
```
see: <http://doc.qt.io/archives/qt-4.8/qwidget.html#setMask> | The solution by overriding `QLabel` `paintEvent` method.
**Code:**
```
void AccountImage::paintEvent(QPaintEvent *event)
{
QPixmap pixmap(":/Icon/my_avatar.png");
QPixmap scaled = pixmap.scaled(width(), height(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
QBrush brush(scaled);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(brush);
painter.drawRoundedRect(0, 0, width(), height(), 100, 100);
QLabel::paintEvent(event);
}
```
**Result:**
[](https://i.stack.imgur.com/S0xUD.png) |
43,136,026 | I am new to python with great desire to learn the language. However, right now i need someone help with a code i am currently working on which keep flagging this error :
Oops, try again. get\_average(alice) returned None instead of the expected 91.15
This is the question with my solution below also:
Write a function called get\_average that takes a student dictionary (like lloyd, alice, or tyler) as input and returns his/her weighted average.
Define a function called get\_average that takes one argument called student.
Make a variable homework that stores the average() of student["homework"].
Repeat step 2 for "quizzes" and "tests".
Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%, quizzes are 30% and tests are 60%.
MY SOLUTION:
```
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": 88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
# Add your function below!
def average(numbers):
total = sum(numbers)
total = float(total)
result = total/len(numbers)
return result
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
Av = (0.1 * homework) + (0.6 * tests) +(0.3 * quizzes)
print Av
``` | 2017/03/31 | [
"https://Stackoverflow.com/questions/43136026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7796550/"
] | Alternatively, you can also try this:
```
import numpy as np
def weighted_average(d):
"""Returns weighted average of values corresponding to keys homework,
tests & quizzes of a dictionary d"""
# bind dict keys to variables homework, test, quiz
homework, test, quiz = [d["homework"]], [d["tests"]], [d["quizzes"]]
# calculate average through np.mean() and Return the value
return "Average: {}".format((0.1 * np.mean(homework)) + (0.6 * np.mean(test)) + (0.3 * np.mean(quiz)))
d = lloyd = {"name": "Lloyd","homework": [90.0, 97.0, 75.0, 92.0],"quizzes": [88.0, 40.0, 94.0],"tests": [75.0, 90.0]}
averages(d)
>>>'Average: 80.55'
``` | I've tested your code, fixed the missing opening bracket at line 4 (looyd quizzes) and it's working well.
```
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
# Add your function below!
def average(numbers):
total = sum(numbers)
total = float(total)
result = total/len(numbers)
return result
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
Av = (0.1 * homework) + (0.6 * tests) +(0.3 * quizzes)
print Av
get_average(alice)
```
This code is printing `91.15` on my python 2.7 |
1,644,635 | Prove that:
$n^n (\frac{n+1}{2})^{2n}$
1. Greater than or equal to $(\frac{n+1}{2})^3$
2. Greater than or equal to $(n!)^3$
Here $n\in \mathbb{N}$
How to prove this? It seems too complicated. Please suggest as how to initiate the solution? | 2016/02/07 | [
"https://math.stackexchange.com/questions/1644635",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/290994/"
] | Using $\bf{A.M\geq G.M}\;,$ We get
$$\frac{1^3+2^3+3^3+.........+n^3}{n}\geq \left(1^3\cdot 2^3\cdot 3^3\cdot.......n^3\right)^{\frac{1}{n}}$$
So $$\frac{n^2(n+1)^2}{4n}\geq \left(n!\right)^{\frac{1}{n}}\Rightarrow n^n\cdot \left(\frac{n+1}{2}\right)^{2n}\geq (n!)^3$$ | Part 1.
For $n\in N$, we have:
$n\geq \frac{n+1}{2}$
$n (\frac{n+1}{2})^2\geq (\frac{n+1}{2})^3$
$n^n (\frac{n+1}{2})^{2n}\geq (\frac{n+1}{2})^3$ |
5,576,500 | How to make three column layout having equal height using only css and html (no js) | 2011/04/07 | [
"https://Stackoverflow.com/questions/5576500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/690854/"
] | Easiest way is to use [faux column background technique](http://www.alistapart.com/articles/fauxcolumns/).
You can also try giving three divs massive bottom paddings with massive bottom margins with a container with `overflow: hidden`. It doesn't play nice with inline anchors though. | ```
<html><body>
```
`<div>`
```
<div style="float:left;height: 33.33%;width:10%;background-color:red">zdfsfs</div>
<div style="float:left;height: 33.33%;width:10%;background-color:blue">zgfsgsgfsgf</div>
<div style="float:left;height: 33.33%;width:10%;background-color:cyan">zvgzcxgvxz</div>
</div></body></html>
``` |
5,576,500 | How to make three column layout having equal height using only css and html (no js) | 2011/04/07 | [
"https://Stackoverflow.com/questions/5576500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/690854/"
] | Easiest way is to use [faux column background technique](http://www.alistapart.com/articles/fauxcolumns/).
You can also try giving three divs massive bottom paddings with massive bottom margins with a container with `overflow: hidden`. It doesn't play nice with inline anchors though. | ```
div {display : table-cell;}
```
This Could Be Another Solution To The Problem!
For More Information, Please See This Link: [Is there a disadvantage of using `display:table-cell`on divs?](https://stackoverflow.com/questions/6307934/is-there-a-disadvantage-of-using-displaytable-cellon-divs) |
17,261,551 | I have a sql like:
```
DBSession().query(Model).filter(***)
```
and I want to explain this sql using `SQLAlchemy`. | 2013/06/23 | [
"https://Stackoverflow.com/questions/17261551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744916/"
] | You want to [compile your SQLAlchemy query into a string](https://docs.sqlalchemy.org/faq/sqlexpressions.html#how-do-i-render-sql-expressions-as-strings-possibly-with-bound-parameters-inlined); use the correct dialect and use literal values for bind parameters
```
query = DBSession().query(Model).filter(***)
# you should have an engine reference used to create the DBSession object
sql = query.statement.compile(engine, compile_kwargs={"literal_binds": True})
```
You can then use that to ask for a MySQL explanation:
```
DBSession().execute(f'EXPLAIN {sql}')
``` | You can prepare your explain sql string like this:
```
'EXPLAIN' + query.compile(
compile_kwargs={"literal_binds": True},
dialect=mysql.dialect()
)
```
Advantage is query has parameters filled in. |
30,476,296 | I am working on an android project where Android support library v7-appcompat is being added by eclipse.Now after following android developers website, I have added dependency for this support library.My project is free of errors but while running the project i am getting the error **"The Import android.support.v7 cannot be resolved"**.I am attaching the log file and my main activity.I have followed almost every post related to this topic on SO but the issue is not resolved yet.
>
> LOGCAT
>
>
>
```
05-26 12:07:19.613: E/AndroidRuntime(18953): java.lang.Error: Unresolved compilation problem:
05-26 12:07:19.613: E/AndroidRuntime(18953): The import android.support.v7 cannot be resolved
05-26 12:07:19.613: E/AndroidRuntime(18953): at com.sim.clientkeeper.MainActivity.<init>(MainActivity.java:7)
05-26 12:07:19.613: E/AndroidRuntime(18953): at java.lang.Class.newInstanceImpl(Native Method)
`import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
SQLiteDatabase sqlDba;
SQLiteAdapter DbAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DbAdapter = new SQLiteAdapter(getApplicationContext());
DbAdapter.open();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClickClient(View v)
{
Intent i=new Intent(this,CLient_List_Activity.class);
startActivity(i);
}
public void onClickTravel(View v)
{
Intent i=new Intent(this,Travel_Activity.class);
startActivity(i);
}
}
`
```
I have added the appcompat library from project-->properties-->android-->adding it in the library section.
I am extending my MainActivity from AppCompatActivity as mentioned in earlier posts about the same topic. | 2015/05/27 | [
"https://Stackoverflow.com/questions/30476296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4080963/"
] | Just delete `android-support-v4.jar` from libs folder of your project. Rest of the things/errors will be gone. Eclipse will handle rest of the things.
if error still exist then try to remove unused imports & clean your project or restart your eclipse. | I think you have not added the App compact-v7 into uild path and also , please right click on your project and then navigate to the Properties , now in new dialog box click to android , select the appropriate android version and in down below in Library section add appcompact-v7 library . Hit apply and ok.
Clean your project. That is what worked for me |
4,935,869 | I am using php-ldap to manage posix accounts on a linux machine. I am able to search the database in php. And I am able to add users via the command line "ldapadd". However, when I try to add a user via PHP ldap\_add, I get an "Object class violation" error (errno 65).
I have tried everything I can think of, but the error has not changed. I have even looked to see if there is an alternative to php-ldap, but have not found one.
The problem is when I look up that error in the general LDAP guide, it says "This error is returned with the entry to be added or the entry as modified violates the object class schema rules. Normally additional information is returned the error detailing the violation." And then it lists 8 possible causes.
I need this more in depth error, but cannot find it. ldap\_error was also no help. Any ideas how to dig deaper here? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4935869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110129/"
] | I figured out how to dig deeper. I am using Ubuntu which was dumping logs to /var/log/{debug,syslog}
In order to get more info I had to increase the log level to 424 in /etc/ldap/slapd.d/cn=config.ldif
Then I was able to see the error in the logs which told me what I was doing wrong... using a dc attribute with an inetOrgPerson objectClass.
Thanks. | PosixAccount (the class that is needed for Linux users) has some mandatory attributes. You must provide in the same operation the:
* uid
* uidNumber
* gidNumber
* homeDirectory
Perhaps in one approach you are, one you are not? |
4,935,869 | I am using php-ldap to manage posix accounts on a linux machine. I am able to search the database in php. And I am able to add users via the command line "ldapadd". However, when I try to add a user via PHP ldap\_add, I get an "Object class violation" error (errno 65).
I have tried everything I can think of, but the error has not changed. I have even looked to see if there is an alternative to php-ldap, but have not found one.
The problem is when I look up that error in the general LDAP guide, it says "This error is returned with the entry to be added or the entry as modified violates the object class schema rules. Normally additional information is returned the error detailing the violation." And then it lists 8 possible causes.
I need this more in depth error, but cannot find it. ldap\_error was also no help. Any ideas how to dig deaper here? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4935869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110129/"
] | Object class violation always means the object you created violated the expectations of the schema.
slapd provides a metric ton of logging if you simply set the debug level to some arbitarily high number. | PosixAccount (the class that is needed for Linux users) has some mandatory attributes. You must provide in the same operation the:
* uid
* uidNumber
* gidNumber
* homeDirectory
Perhaps in one approach you are, one you are not? |
4,935,869 | I am using php-ldap to manage posix accounts on a linux machine. I am able to search the database in php. And I am able to add users via the command line "ldapadd". However, when I try to add a user via PHP ldap\_add, I get an "Object class violation" error (errno 65).
I have tried everything I can think of, but the error has not changed. I have even looked to see if there is an alternative to php-ldap, but have not found one.
The problem is when I look up that error in the general LDAP guide, it says "This error is returned with the entry to be added or the entry as modified violates the object class schema rules. Normally additional information is returned the error detailing the violation." And then it lists 8 possible causes.
I need this more in depth error, but cannot find it. ldap\_error was also no help. Any ideas how to dig deaper here? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4935869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110129/"
] | PosixAccount (the class that is needed for Linux users) has some mandatory attributes. You must provide in the same operation the:
* uid
* uidNumber
* gidNumber
* homeDirectory
Perhaps in one approach you are, one you are not? | We had the same problems, so we used the following bash command:
```
sudo tail -f syslog |grep slapd
```
So you will have an real time window to show you the detail reactions on your LDAP manipulations. |
4,935,869 | I am using php-ldap to manage posix accounts on a linux machine. I am able to search the database in php. And I am able to add users via the command line "ldapadd". However, when I try to add a user via PHP ldap\_add, I get an "Object class violation" error (errno 65).
I have tried everything I can think of, but the error has not changed. I have even looked to see if there is an alternative to php-ldap, but have not found one.
The problem is when I look up that error in the general LDAP guide, it says "This error is returned with the entry to be added or the entry as modified violates the object class schema rules. Normally additional information is returned the error detailing the violation." And then it lists 8 possible causes.
I need this more in depth error, but cannot find it. ldap\_error was also no help. Any ideas how to dig deaper here? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4935869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110129/"
] | I figured out how to dig deeper. I am using Ubuntu which was dumping logs to /var/log/{debug,syslog}
In order to get more info I had to increase the log level to 424 in /etc/ldap/slapd.d/cn=config.ldif
Then I was able to see the error in the logs which told me what I was doing wrong... using a dc attribute with an inetOrgPerson objectClass.
Thanks. | Object class violation always means the object you created violated the expectations of the schema.
slapd provides a metric ton of logging if you simply set the debug level to some arbitarily high number. |
4,935,869 | I am using php-ldap to manage posix accounts on a linux machine. I am able to search the database in php. And I am able to add users via the command line "ldapadd". However, when I try to add a user via PHP ldap\_add, I get an "Object class violation" error (errno 65).
I have tried everything I can think of, but the error has not changed. I have even looked to see if there is an alternative to php-ldap, but have not found one.
The problem is when I look up that error in the general LDAP guide, it says "This error is returned with the entry to be added or the entry as modified violates the object class schema rules. Normally additional information is returned the error detailing the violation." And then it lists 8 possible causes.
I need this more in depth error, but cannot find it. ldap\_error was also no help. Any ideas how to dig deaper here? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4935869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110129/"
] | I figured out how to dig deeper. I am using Ubuntu which was dumping logs to /var/log/{debug,syslog}
In order to get more info I had to increase the log level to 424 in /etc/ldap/slapd.d/cn=config.ldif
Then I was able to see the error in the logs which told me what I was doing wrong... using a dc attribute with an inetOrgPerson objectClass.
Thanks. | We had the same problems, so we used the following bash command:
```
sudo tail -f syslog |grep slapd
```
So you will have an real time window to show you the detail reactions on your LDAP manipulations. |
4,935,869 | I am using php-ldap to manage posix accounts on a linux machine. I am able to search the database in php. And I am able to add users via the command line "ldapadd". However, when I try to add a user via PHP ldap\_add, I get an "Object class violation" error (errno 65).
I have tried everything I can think of, but the error has not changed. I have even looked to see if there is an alternative to php-ldap, but have not found one.
The problem is when I look up that error in the general LDAP guide, it says "This error is returned with the entry to be added or the entry as modified violates the object class schema rules. Normally additional information is returned the error detailing the violation." And then it lists 8 possible causes.
I need this more in depth error, but cannot find it. ldap\_error was also no help. Any ideas how to dig deaper here? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4935869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110129/"
] | I figured out how to dig deeper. I am using Ubuntu which was dumping logs to /var/log/{debug,syslog}
In order to get more info I had to increase the log level to 424 in /etc/ldap/slapd.d/cn=config.ldif
Then I was able to see the error in the logs which told me what I was doing wrong... using a dc attribute with an inetOrgPerson objectClass.
Thanks. | A [comment](https://secure.php.net/manual/en/function.ldap-error.php#121881) under ldap\_error documentation says that to obtain additional info you can call this:
```
ldap_get_option($conn, LDAP_OPT_DIAGNOSTIC_MESSAGE, $err);
// $err now contains the additional info
``` |
4,935,869 | I am using php-ldap to manage posix accounts on a linux machine. I am able to search the database in php. And I am able to add users via the command line "ldapadd". However, when I try to add a user via PHP ldap\_add, I get an "Object class violation" error (errno 65).
I have tried everything I can think of, but the error has not changed. I have even looked to see if there is an alternative to php-ldap, but have not found one.
The problem is when I look up that error in the general LDAP guide, it says "This error is returned with the entry to be added or the entry as modified violates the object class schema rules. Normally additional information is returned the error detailing the violation." And then it lists 8 possible causes.
I need this more in depth error, but cannot find it. ldap\_error was also no help. Any ideas how to dig deaper here? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4935869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110129/"
] | Object class violation always means the object you created violated the expectations of the schema.
slapd provides a metric ton of logging if you simply set the debug level to some arbitarily high number. | We had the same problems, so we used the following bash command:
```
sudo tail -f syslog |grep slapd
```
So you will have an real time window to show you the detail reactions on your LDAP manipulations. |
4,935,869 | I am using php-ldap to manage posix accounts on a linux machine. I am able to search the database in php. And I am able to add users via the command line "ldapadd". However, when I try to add a user via PHP ldap\_add, I get an "Object class violation" error (errno 65).
I have tried everything I can think of, but the error has not changed. I have even looked to see if there is an alternative to php-ldap, but have not found one.
The problem is when I look up that error in the general LDAP guide, it says "This error is returned with the entry to be added or the entry as modified violates the object class schema rules. Normally additional information is returned the error detailing the violation." And then it lists 8 possible causes.
I need this more in depth error, but cannot find it. ldap\_error was also no help. Any ideas how to dig deaper here? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4935869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110129/"
] | Object class violation always means the object you created violated the expectations of the schema.
slapd provides a metric ton of logging if you simply set the debug level to some arbitarily high number. | A [comment](https://secure.php.net/manual/en/function.ldap-error.php#121881) under ldap\_error documentation says that to obtain additional info you can call this:
```
ldap_get_option($conn, LDAP_OPT_DIAGNOSTIC_MESSAGE, $err);
// $err now contains the additional info
``` |
4,935,869 | I am using php-ldap to manage posix accounts on a linux machine. I am able to search the database in php. And I am able to add users via the command line "ldapadd". However, when I try to add a user via PHP ldap\_add, I get an "Object class violation" error (errno 65).
I have tried everything I can think of, but the error has not changed. I have even looked to see if there is an alternative to php-ldap, but have not found one.
The problem is when I look up that error in the general LDAP guide, it says "This error is returned with the entry to be added or the entry as modified violates the object class schema rules. Normally additional information is returned the error detailing the violation." And then it lists 8 possible causes.
I need this more in depth error, but cannot find it. ldap\_error was also no help. Any ideas how to dig deaper here? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4935869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110129/"
] | A [comment](https://secure.php.net/manual/en/function.ldap-error.php#121881) under ldap\_error documentation says that to obtain additional info you can call this:
```
ldap_get_option($conn, LDAP_OPT_DIAGNOSTIC_MESSAGE, $err);
// $err now contains the additional info
``` | We had the same problems, so we used the following bash command:
```
sudo tail -f syslog |grep slapd
```
So you will have an real time window to show you the detail reactions on your LDAP manipulations. |
68,992,767 | I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
desired output:
```
11
12
25
32
64
```
May I know where I'm making mistake? | 2021/08/31 | [
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
I would recommend using i and j instead of element and compare\_index.
Look at line 9. Why does that fix it? | Your algorithm is almost correct but
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]` in this line you made the mistake.
It shouldn't be `compare_index`, it should be `element`. Please check the correct algorithm below
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
``` |
68,992,767 | I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
desired output:
```
11
12
25
32
64
```
May I know where I'm making mistake? | 2021/08/31 | [
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
I would recommend using i and j instead of element and compare\_index.
Look at line 9. Why does that fix it? | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex],element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
swapping is a must between `element_list[element]` and `element_list[mindex]`. |
68,992,767 | I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
desired output:
```
11
12
25
32
64
```
May I know where I'm making mistake? | 2021/08/31 | [
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
I would recommend using i and j instead of element and compare\_index.
Look at line 9. Why does that fix it? | I think the problem lies in the line
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]`
Here I believe you want to exchange the position of the bigger and the smaller number in the array, but the problem is that you are exchanging the positions of the elements with indexes `compare_index` and `mindex`. And in the very previous line you are doing `mindex = compare_index` so basically you are exchanging one element with itself.
Rather, you must exchange elements with indexes `element` and `mindex`, as `compare_index` is just for temporary use.
Make this change in that line:
`element_list[element], element_list[mindex] = element_list[mindex], element_list[element]`
I hope this solves your problem! |
68,992,767 | I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
desired output:
```
11
12
25
32
64
```
May I know where I'm making mistake? | 2021/08/31 | [
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] | Your algorithm is almost correct but
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]` in this line you made the mistake.
It shouldn't be `compare_index`, it should be `element`. Please check the correct algorithm below
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
``` | I think the problem lies in the line
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]`
Here I believe you want to exchange the position of the bigger and the smaller number in the array, but the problem is that you are exchanging the positions of the elements with indexes `compare_index` and `mindex`. And in the very previous line you are doing `mindex = compare_index` so basically you are exchanging one element with itself.
Rather, you must exchange elements with indexes `element` and `mindex`, as `compare_index` is just for temporary use.
Make this change in that line:
`element_list[element], element_list[mindex] = element_list[mindex], element_list[element]`
I hope this solves your problem! |
68,992,767 | I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
desired output:
```
11
12
25
32
64
```
May I know where I'm making mistake? | 2021/08/31 | [
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex],element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
swapping is a must between `element_list[element]` and `element_list[mindex]`. | I think the problem lies in the line
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]`
Here I believe you want to exchange the position of the bigger and the smaller number in the array, but the problem is that you are exchanging the positions of the elements with indexes `compare_index` and `mindex`. And in the very previous line you are doing `mindex = compare_index` so basically you are exchanging one element with itself.
Rather, you must exchange elements with indexes `element` and `mindex`, as `compare_index` is just for temporary use.
Make this change in that line:
`element_list[element], element_list[mindex] = element_list[mindex], element_list[element]`
I hope this solves your problem! |
510,665 | After learning mesh-current method for solving circuits, I started reading the wikipedia article on linearity to understand more on the "why?"
[Reference.](https://www.khanacademy.org/science/electrical-engineering/ee-circuit-analysis-topic/ee-dc-circuit-analysis/a/ee-superposition)
In this article, I sort of get why resistors are linear - because they obey both properties of a linear object which is
$$ f(x +y ) = f(x) + f(y)$$
$$ f(ax) = af(x)$$
as in,
$$i = \frac{v}{R}$$
$$ i(v\_1 + v\_2) = \frac{ v\_1 + v\_2}{R}$$
$$i(a v\_1 ) = a \frac{v\_1}{r}$$
But, I don't understand why this would be true for inductors and capacitors. Why do these physical systems obey this mathematical structure? I mean I was shocked that the mesh current method was actually a legitimate technique.
Note: The kind of answer that I'm looking for one is one which uses both physical intuition and mathematics to explain but not entirely explain the thing based on both. | 2020/07/16 | [
"https://electronics.stackexchange.com/questions/510665",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/236654/"
] | Some with a sense of humor said
"On a small enough scale, all behaviors are linear."
In circuit design, we do not have exact polynomial descriptions for any component, so we go with "it is linear".
And somewhat later, we learn about Taylor Series approximations to the Exponential Diode behaviors.
And we learn about 2\_nd order and 3\_rd order intercept points and P1 compression points, input referred and output referred.
And we learn to use spreadsheets to keep track of the distortion, and use worst case or RSS modeling.
All because our components are real structures with imperfect crystalline manufacturing, and incomplete numeric descriptions in the models.
And we get paid to release a design to the FAB or to the manufacturing floor.
So we, over years, become pragmatic, becoming engineers, accepting the wonderful variability of life, and highly reliable systems become available to customers.
It all works.
==============================
Then we get paid to convert all the systems\_on\_PCB to systems\_on\_silicon, and the fun learning starts all over again, not forgetting the "ground" is outside the Integrated Circuit, several millimeters away. Thus vast differential circuits become our tools. And wide substrate/well rings, to minimize gradients on silicon surface, become a tool.
Then, with everything located only 100 microns from any other circuit (well, maybe 1,000 micron or 5,000 microns), we get to rethink Heavyside and Maxwell, and realize magnetic fields are just a result of slight delays in the Efields, thus we can SHIELD magnetic fields using the SKIN EFFECT.
Thus circuit design and system design require constant digging down into the fundamentals, to rethink what we have been taught. There is a need to detect "folklore", and understand why the folklore exists, to explore that particular design space and find exceptions to the rules, and exploit them. Folklore about substrate noise control is plentious; challenge them.
Also we might ponder "harmonics". Harmonics are merely an expression of the correlation between a non-linear behavior and various linearly\_spaced sinusoids.
A step function correlates with ANYTHING, to some degree. We happily indicate the peaks and nulls in the amount of correlation, because of lossless energy storage(infinite Q); this realization lets us ponder FINITE\_Q systems, and realize harmonics do not exist; harmonics are just the result of "correlation".
Get thee to the lab, with a Spectrum Analyzer and Pulse Generator. And play with pulse\_frequency and pulse\_width and pulse\_risetime, and learn about "harmonics". Respect the input power limit of the SA.
Most importantly, alter the Resolution Bandwidth and Video Bandwidth of the SA, which lets you in essence alter\_the\_Q of the system; this may be the crucial takeaway thought from your lab tinkering. | >
> *What exactly is the intuition behind physical circuits being linear?*
>
>
>
One simple rule that I think of when judging if a circuit is linear is to consider if there might be harmonics produced when driving the circuit with a sine wave. If harmonics are produced with a sinusoidal input, then the circuit is somewhat non-linear. The more harmonic amplitude that is produced (compared to the original sine wave amplitude) then the more non-linear it is. |
510,665 | After learning mesh-current method for solving circuits, I started reading the wikipedia article on linearity to understand more on the "why?"
[Reference.](https://www.khanacademy.org/science/electrical-engineering/ee-circuit-analysis-topic/ee-dc-circuit-analysis/a/ee-superposition)
In this article, I sort of get why resistors are linear - because they obey both properties of a linear object which is
$$ f(x +y ) = f(x) + f(y)$$
$$ f(ax) = af(x)$$
as in,
$$i = \frac{v}{R}$$
$$ i(v\_1 + v\_2) = \frac{ v\_1 + v\_2}{R}$$
$$i(a v\_1 ) = a \frac{v\_1}{r}$$
But, I don't understand why this would be true for inductors and capacitors. Why do these physical systems obey this mathematical structure? I mean I was shocked that the mesh current method was actually a legitimate technique.
Note: The kind of answer that I'm looking for one is one which uses both physical intuition and mathematics to explain but not entirely explain the thing based on both. | 2020/07/16 | [
"https://electronics.stackexchange.com/questions/510665",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/236654/"
] | >
> *What exactly is the intuition behind physical circuits being linear?*
>
>
>
One simple rule that I think of when judging if a circuit is linear is to consider if there might be harmonics produced when driving the circuit with a sine wave. If harmonics are produced with a sinusoidal input, then the circuit is somewhat non-linear. The more harmonic amplitude that is produced (compared to the original sine wave amplitude) then the more non-linear it is. | For every electronic system, the output voltage or current is limited. So if the response gets very close to those limitations, the system is not linear. A system may be linear if the response is much smaller than those limits. |
510,665 | After learning mesh-current method for solving circuits, I started reading the wikipedia article on linearity to understand more on the "why?"
[Reference.](https://www.khanacademy.org/science/electrical-engineering/ee-circuit-analysis-topic/ee-dc-circuit-analysis/a/ee-superposition)
In this article, I sort of get why resistors are linear - because they obey both properties of a linear object which is
$$ f(x +y ) = f(x) + f(y)$$
$$ f(ax) = af(x)$$
as in,
$$i = \frac{v}{R}$$
$$ i(v\_1 + v\_2) = \frac{ v\_1 + v\_2}{R}$$
$$i(a v\_1 ) = a \frac{v\_1}{r}$$
But, I don't understand why this would be true for inductors and capacitors. Why do these physical systems obey this mathematical structure? I mean I was shocked that the mesh current method was actually a legitimate technique.
Note: The kind of answer that I'm looking for one is one which uses both physical intuition and mathematics to explain but not entirely explain the thing based on both. | 2020/07/16 | [
"https://electronics.stackexchange.com/questions/510665",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/236654/"
] | Some with a sense of humor said
"On a small enough scale, all behaviors are linear."
In circuit design, we do not have exact polynomial descriptions for any component, so we go with "it is linear".
And somewhat later, we learn about Taylor Series approximations to the Exponential Diode behaviors.
And we learn about 2\_nd order and 3\_rd order intercept points and P1 compression points, input referred and output referred.
And we learn to use spreadsheets to keep track of the distortion, and use worst case or RSS modeling.
All because our components are real structures with imperfect crystalline manufacturing, and incomplete numeric descriptions in the models.
And we get paid to release a design to the FAB or to the manufacturing floor.
So we, over years, become pragmatic, becoming engineers, accepting the wonderful variability of life, and highly reliable systems become available to customers.
It all works.
==============================
Then we get paid to convert all the systems\_on\_PCB to systems\_on\_silicon, and the fun learning starts all over again, not forgetting the "ground" is outside the Integrated Circuit, several millimeters away. Thus vast differential circuits become our tools. And wide substrate/well rings, to minimize gradients on silicon surface, become a tool.
Then, with everything located only 100 microns from any other circuit (well, maybe 1,000 micron or 5,000 microns), we get to rethink Heavyside and Maxwell, and realize magnetic fields are just a result of slight delays in the Efields, thus we can SHIELD magnetic fields using the SKIN EFFECT.
Thus circuit design and system design require constant digging down into the fundamentals, to rethink what we have been taught. There is a need to detect "folklore", and understand why the folklore exists, to explore that particular design space and find exceptions to the rules, and exploit them. Folklore about substrate noise control is plentious; challenge them.
Also we might ponder "harmonics". Harmonics are merely an expression of the correlation between a non-linear behavior and various linearly\_spaced sinusoids.
A step function correlates with ANYTHING, to some degree. We happily indicate the peaks and nulls in the amount of correlation, because of lossless energy storage(infinite Q); this realization lets us ponder FINITE\_Q systems, and realize harmonics do not exist; harmonics are just the result of "correlation".
Get thee to the lab, with a Spectrum Analyzer and Pulse Generator. And play with pulse\_frequency and pulse\_width and pulse\_risetime, and learn about "harmonics". Respect the input power limit of the SA.
Most importantly, alter the Resolution Bandwidth and Video Bandwidth of the SA, which lets you in essence alter\_the\_Q of the system; this may be the crucial takeaway thought from your lab tinkering. | I'm not sure what the problem is. If you do the exact same thing you did for the resistor with the inductor and capacitor, you'll find that the inductor and capacitor are linear as well.
$$ v=L\frac{di}{dt}$$
If \$ i=i\_1+i\_2\$, then \$ v=L\frac{d}{dt}(i\_1+i\_2)=L\frac{di\_1}{dt}+L\frac{di\_2}{dt}\$.
If you multiply \$ i\$ by some constant \$ \alpha\$, then \$ v=L\frac{d}{dt}(\alpha i)=\alpha L\frac{di}{dt}\$.
You can do the same thing with the capacitor.
However, I don't know what this has to do with the mesh-current technique. That technique is based on KVL and has nothing to do with the linearity of circuit components. You can still use the mesh-current technique with non-linear components (like a diode), but the resulting set of non-linear equations will be much harder to solve by hand. |
510,665 | After learning mesh-current method for solving circuits, I started reading the wikipedia article on linearity to understand more on the "why?"
[Reference.](https://www.khanacademy.org/science/electrical-engineering/ee-circuit-analysis-topic/ee-dc-circuit-analysis/a/ee-superposition)
In this article, I sort of get why resistors are linear - because they obey both properties of a linear object which is
$$ f(x +y ) = f(x) + f(y)$$
$$ f(ax) = af(x)$$
as in,
$$i = \frac{v}{R}$$
$$ i(v\_1 + v\_2) = \frac{ v\_1 + v\_2}{R}$$
$$i(a v\_1 ) = a \frac{v\_1}{r}$$
But, I don't understand why this would be true for inductors and capacitors. Why do these physical systems obey this mathematical structure? I mean I was shocked that the mesh current method was actually a legitimate technique.
Note: The kind of answer that I'm looking for one is one which uses both physical intuition and mathematics to explain but not entirely explain the thing based on both. | 2020/07/16 | [
"https://electronics.stackexchange.com/questions/510665",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/236654/"
] | I'm not sure what the problem is. If you do the exact same thing you did for the resistor with the inductor and capacitor, you'll find that the inductor and capacitor are linear as well.
$$ v=L\frac{di}{dt}$$
If \$ i=i\_1+i\_2\$, then \$ v=L\frac{d}{dt}(i\_1+i\_2)=L\frac{di\_1}{dt}+L\frac{di\_2}{dt}\$.
If you multiply \$ i\$ by some constant \$ \alpha\$, then \$ v=L\frac{d}{dt}(\alpha i)=\alpha L\frac{di}{dt}\$.
You can do the same thing with the capacitor.
However, I don't know what this has to do with the mesh-current technique. That technique is based on KVL and has nothing to do with the linearity of circuit components. You can still use the mesh-current technique with non-linear components (like a diode), but the resulting set of non-linear equations will be much harder to solve by hand. | For every electronic system, the output voltage or current is limited. So if the response gets very close to those limitations, the system is not linear. A system may be linear if the response is much smaller than those limits. |
510,665 | After learning mesh-current method for solving circuits, I started reading the wikipedia article on linearity to understand more on the "why?"
[Reference.](https://www.khanacademy.org/science/electrical-engineering/ee-circuit-analysis-topic/ee-dc-circuit-analysis/a/ee-superposition)
In this article, I sort of get why resistors are linear - because they obey both properties of a linear object which is
$$ f(x +y ) = f(x) + f(y)$$
$$ f(ax) = af(x)$$
as in,
$$i = \frac{v}{R}$$
$$ i(v\_1 + v\_2) = \frac{ v\_1 + v\_2}{R}$$
$$i(a v\_1 ) = a \frac{v\_1}{r}$$
But, I don't understand why this would be true for inductors and capacitors. Why do these physical systems obey this mathematical structure? I mean I was shocked that the mesh current method was actually a legitimate technique.
Note: The kind of answer that I'm looking for one is one which uses both physical intuition and mathematics to explain but not entirely explain the thing based on both. | 2020/07/16 | [
"https://electronics.stackexchange.com/questions/510665",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/236654/"
] | Some with a sense of humor said
"On a small enough scale, all behaviors are linear."
In circuit design, we do not have exact polynomial descriptions for any component, so we go with "it is linear".
And somewhat later, we learn about Taylor Series approximations to the Exponential Diode behaviors.
And we learn about 2\_nd order and 3\_rd order intercept points and P1 compression points, input referred and output referred.
And we learn to use spreadsheets to keep track of the distortion, and use worst case or RSS modeling.
All because our components are real structures with imperfect crystalline manufacturing, and incomplete numeric descriptions in the models.
And we get paid to release a design to the FAB or to the manufacturing floor.
So we, over years, become pragmatic, becoming engineers, accepting the wonderful variability of life, and highly reliable systems become available to customers.
It all works.
==============================
Then we get paid to convert all the systems\_on\_PCB to systems\_on\_silicon, and the fun learning starts all over again, not forgetting the "ground" is outside the Integrated Circuit, several millimeters away. Thus vast differential circuits become our tools. And wide substrate/well rings, to minimize gradients on silicon surface, become a tool.
Then, with everything located only 100 microns from any other circuit (well, maybe 1,000 micron or 5,000 microns), we get to rethink Heavyside and Maxwell, and realize magnetic fields are just a result of slight delays in the Efields, thus we can SHIELD magnetic fields using the SKIN EFFECT.
Thus circuit design and system design require constant digging down into the fundamentals, to rethink what we have been taught. There is a need to detect "folklore", and understand why the folklore exists, to explore that particular design space and find exceptions to the rules, and exploit them. Folklore about substrate noise control is plentious; challenge them.
Also we might ponder "harmonics". Harmonics are merely an expression of the correlation between a non-linear behavior and various linearly\_spaced sinusoids.
A step function correlates with ANYTHING, to some degree. We happily indicate the peaks and nulls in the amount of correlation, because of lossless energy storage(infinite Q); this realization lets us ponder FINITE\_Q systems, and realize harmonics do not exist; harmonics are just the result of "correlation".
Get thee to the lab, with a Spectrum Analyzer and Pulse Generator. And play with pulse\_frequency and pulse\_width and pulse\_risetime, and learn about "harmonics". Respect the input power limit of the SA.
Most importantly, alter the Resolution Bandwidth and Video Bandwidth of the SA, which lets you in essence alter\_the\_Q of the system; this may be the crucial takeaway thought from your lab tinkering. | For every electronic system, the output voltage or current is limited. So if the response gets very close to those limitations, the system is not linear. A system may be linear if the response is much smaller than those limits. |
125,169 | ```
function _mint(string memory _name, bool _isOnSale, uint _price) public{
MyNft storage nft = fetchNft[_name];
require(!nft.exists, "The Nft already Exists");
uint counter;
nft.id += counter++;
nft.name = _name;
nft.isOnSale = _isOnSale;
nft.owner = msg.sender;
nft.price = _price * 1 ether;
nft.exists = true;
counter = nft.id;
}
```
In the above function, I'm trying to assign the value of the counter variable to nft.id, However the value that is assigned to nft.id always remains 0, No matter how many times I execute the mint function.
Please help me in knowing the reason behind this issue and how can i solve it. | 2022/04/01 | [
"https://ethereum.stackexchange.com/questions/125169",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/90519/"
] | This is a value unique to each domain that is ‘mixed in’ the signature. It makes signatures from different domains incompatible because **is designed to include bits of DApp unique information such as the name of the DApp, the intended validator contract address, the expected DApp domain name, etc.**
Source:<https://eips.ethereum.org/EIPS/eip-712> | >
> It is possible that two DApps come up with an identical structure like
> Transfer(address from,address to,uint256 amount) that should not be
> compatible. By introducing a domain separator the dApp developers are
> guaranteed that there can be no signature collision.
>
>
>
You can see a practical example of how Uniswap uses it in [ERC721Permit.sol](https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/ERC721Permit.sol)
```
function DOMAIN_SEPARATOR() public view override returns (bytes32) {
return
keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
nameHash,
versionHash,
ChainId.get(),
address(this)
)
);
}
```
`DOMAIN_SEPARATOR` returns a hash value (bytes32) and this is hash value is used in `permit` function
```
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
require(_blockTimestamp() <= deadline, 'Permit expired');
// it is used to create another hash value to make it unique
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, spender, tokenId, _getAndIncrementNonce(tokenId), deadline))
)
);
address owner = ownerOf(tokenId);
require(spender != owner, 'ERC721Permit: approval to current owner');
if (Address.isContract(owner)) {
require(IERC1271(owner).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e, 'Unauthorized');
} else {
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), 'Invalid signature');
require(recoveredAddress == owner, 'Unauthorized');
}
_approve(spender, tokenId);
}
``` |
15,898,011 | IF I set the deployment target for my app to iOS 6 and when submitting to app store, will users with iOS 4.3 (or ios5) be not able to download install the app itself?how can i deploy app that work on ios4.3 to ios6 .please help. | 2013/04/09 | [
"https://Stackoverflow.com/questions/15898011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764589/"
] | With your query, you are trying to insert a phone number in a column that doesn't exist in the table `ng_school`. `ng_school` only contains a REFERENCE to a phone number(`phone_id`) , but not the phone number itself.
What you'll need to do is insert the phone number first in `ng_phone_number`, get the `PHONE_NUMBER_ID` value and insert that in `ng_school`.
In short:
1/ `INSERT INTO ng_phone_number ....`
2/ `SELECT LAST PHONE_NUMBER_ID or LAST_INSERT_ID()`
3/ `INSERT INTO ng_school(PHONE_ID) VALUES ([phone_number_id goes here])` | ```
INSERT INTO ng_school (SCHOOL_ID, SCHOOL_SYSTEM_ID, NAME, ZIP, CITY, **PHONE**, LEAGUE_NAME, MINIMUM_GRADE_ID, MAXIMUM_GRADE_ID) VALUES ('testSchoolA','testSchoolSystem1','Elementary School A','90210','City of Los Angeles','213 555 1000','School A Athletic','K','GRADE6');
```
Cause you don't have phone column in your table.. it's **PHONE\_ID** |
47,364,102 | I have a simple model below:
```
class Ingredient(models.Model):
name = models.CharField(max_length=30)
```
I am using django rest framework for api endpoints.
```
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all()
serializer_class = IngredientListSerializer
filter_backends = [OrderingFilter]
```
I wanted my two end points to output as:
```
?ordering=name -- i want the ordering to be case-insensitive
?ordering=-name -- i want the ordering to be case-insensitive
```
the only way to achieve this is create
```
class CaseInsensitiveOrderingFilter(OrderingFilter):
def filter_queryset(self, request, queryset, view):
ordering = self.get_ordering(request, queryset, view)
if ordering:
new_ordering = []
for field in ordering:
if field.startswith('-'):
new_ordering.append(Lower(field[1:]).desc())
else:
new_ordering.append(Lower(field).asc())
return queryset.order_by(*new_ordering)
return queryset
```
and then
```
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all().order_by(Lower('name'))
serializer_class = IngredientListSerializer
filter_backends = [CaseInsensitiveOrderingFilter]
```
But now when i access the following endpoints
```
?ordering=id -- it shows 1,10,11,12
?ordering=-id -- it shows 99,98 ..100..
```
If i use `filter_backends = [OrderingFilter]` instead of `filter_backends = [CaseInsensitiveOrderingFilter]`
```
?ordering=id -- it shows 1,2,3,4,
?ordering=-id -- it shows 220,221,220
```
so how to tell Django to use
```
filter_backends = [CaseInsensitiveOrderingFilter] for name field and
filter_backends = [OrderingFilter] for id field
``` | 2017/11/18 | [
"https://Stackoverflow.com/questions/47364102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897115/"
] | I suggest having a specific class attribute for case insensitive fields
```
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all().order_by(Lower('name'))
serializer_class = IngredientListSerializer
filter_backends = [CaseInsensitiveOrderingFilter]
ordering_fields = () # include both normal and case insensitive fields
ordering_case_insensitive_fields = () # put here only case insensitive fields
```
Then your custom ordering class will be:
```
class CaseInsensitiveOrderingFilter(OrderingFilter):
def filter_queryset(self, request, queryset, view):
ordering = self.get_ordering(request, queryset, view)
insensitive_ordering = getattr(view, 'ordering_case_insensitive_fields', ())
if ordering:
new_ordering = []
for field in ordering:
if field in insensitive_ordering:
new_ordering.append(Lower(field[1:]).desc() if field.startswith('-') else Lower(field).asc())
else:
new_ordering.append(field)
return queryset.order_by(*new_ordering)
return queryset
``` | **views.py**
```
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all()
serializer_class = IngredientListSerializer
def filter_queryset(self, queryset):
if "name" in self.request.query_params.get("ordering"):
return CaseInsensitiveOrderingFilter().filter_queryset(self.request, queryset, self)
else:
queryset = OrderingFilter().filter_queryset(self.request, queryset, self)
return SearchFilter().filter_queryset(self.request, queryset, self)
``` |
47,364,102 | I have a simple model below:
```
class Ingredient(models.Model):
name = models.CharField(max_length=30)
```
I am using django rest framework for api endpoints.
```
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all()
serializer_class = IngredientListSerializer
filter_backends = [OrderingFilter]
```
I wanted my two end points to output as:
```
?ordering=name -- i want the ordering to be case-insensitive
?ordering=-name -- i want the ordering to be case-insensitive
```
the only way to achieve this is create
```
class CaseInsensitiveOrderingFilter(OrderingFilter):
def filter_queryset(self, request, queryset, view):
ordering = self.get_ordering(request, queryset, view)
if ordering:
new_ordering = []
for field in ordering:
if field.startswith('-'):
new_ordering.append(Lower(field[1:]).desc())
else:
new_ordering.append(Lower(field).asc())
return queryset.order_by(*new_ordering)
return queryset
```
and then
```
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all().order_by(Lower('name'))
serializer_class = IngredientListSerializer
filter_backends = [CaseInsensitiveOrderingFilter]
```
But now when i access the following endpoints
```
?ordering=id -- it shows 1,10,11,12
?ordering=-id -- it shows 99,98 ..100..
```
If i use `filter_backends = [OrderingFilter]` instead of `filter_backends = [CaseInsensitiveOrderingFilter]`
```
?ordering=id -- it shows 1,2,3,4,
?ordering=-id -- it shows 220,221,220
```
so how to tell Django to use
```
filter_backends = [CaseInsensitiveOrderingFilter] for name field and
filter_backends = [OrderingFilter] for id field
``` | 2017/11/18 | [
"https://Stackoverflow.com/questions/47364102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897115/"
] | I suggest having a specific class attribute for case insensitive fields
```
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all().order_by(Lower('name'))
serializer_class = IngredientListSerializer
filter_backends = [CaseInsensitiveOrderingFilter]
ordering_fields = () # include both normal and case insensitive fields
ordering_case_insensitive_fields = () # put here only case insensitive fields
```
Then your custom ordering class will be:
```
class CaseInsensitiveOrderingFilter(OrderingFilter):
def filter_queryset(self, request, queryset, view):
ordering = self.get_ordering(request, queryset, view)
insensitive_ordering = getattr(view, 'ordering_case_insensitive_fields', ())
if ordering:
new_ordering = []
for field in ordering:
if field in insensitive_ordering:
new_ordering.append(Lower(field[1:]).desc() if field.startswith('-') else Lower(field).asc())
else:
new_ordering.append(field)
return queryset.order_by(*new_ordering)
return queryset
``` | Here is fixed ordering class from answer by @Gabriel Muj
```
class MyOrderingFilter(filters.OrderingFilter):
def filter_queryset(self, request, queryset, view):
ordering = self.get_ordering(request, queryset, view)
insensitive_ordering = getattr(view, 'ordering_case_insensitive_fields', ())
if ordering:
new_ordering = []
for field in ordering:
if field in insensitive_ordering or (field.startswith('-') and field[1:] in insensitive_ordering):
# Use case insensitive ordering for listed fields
new_ordering.append(Lower(field[1:]).desc() if field.startswith('-') else Lower(field).asc())
else:
new_ordering.append(field)
return queryset.order_by(*new_ordering)
return queryset
``` |
50,934,897 | When discussing the syntax of an enum, I want to know the names of the two halves that make up its syntax.
```
public enum Suits { Diamonds, Clubs, Hearts, Spades}
...
Suits card = Suits.Clubs;
```
My guess is that the `Suits` to the left of the period would be called the enum type and the `Clubs` after the period would be a member. But I didn't see anything official that confirms this. | 2018/06/19 | [
"https://Stackoverflow.com/questions/50934897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439320/"
] | [Microsoft wording](https://learn.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/enum):
>
> The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.
>
>
>
So `Suits` is the *type name*, `Diamonds, Clubs, Hearts, Spades` is the *enumeration list* and `Clubs` is a *named constant*. Its *value* is 1.
>
> By default, the first enumerator has the value 0, [...]
>
>
>
So the named constants are also called *enumerator*. | According to the [Official documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum) you could call:
* Suits: The Enumeration or Enumerator list.
* Clubs: An Enumerator.
>
> The enum keyword is used to declare an enumeration, a distinct type
> that consists of a set of named constants called the enumerator list.
>
>
> By default, the first enumerator has the value 0, and the value of
> each successive enumerator is increased by 1. For example, in the
> following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.
>
>
> |
1,315,771 | So right now I'm bashing my head - at the moment we use an element for a button to give it our own custom font, fine - this works, but as we're using Cufon on the rest of the site, we're wondering if it's possible to get Cufon working on a button.
So far I've changed the button to an and using standard css styles on an 'input' or 'input[type="submit"]' element work fine - but I've tried both of these in cufon to no avail.
This is a button - so as Cufon generates images, this should work, but maybe I'm doing it wrong - can anyone help? | 2009/08/22 | [
"https://Stackoverflow.com/questions/1315771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159131/"
] | Using the element in the following way:
```
<button type="buton">value</button>
```
worked when applying the Cufon style:
```
Cufon.replace('button', {color: '-linear-gradient(#999, 0.45=#666, 0.45=#555, #999)'});
```
Thanks very much :) | The only solution I found to use Cufon on `<input type="submit"/>` buttons was to use Javascript (jQuery personally).
1. Copy the input button's text (the "value" attribute) to a span .
2. Replace the span using Cufon.replace()
3. Remove the input button's text
4. Position the span over the button
5. Propagate the click() event from the span to the button
Done ! |
1,315,771 | So right now I'm bashing my head - at the moment we use an element for a button to give it our own custom font, fine - this works, but as we're using Cufon on the rest of the site, we're wondering if it's possible to get Cufon working on a button.
So far I've changed the button to an and using standard css styles on an 'input' or 'input[type="submit"]' element work fine - but I've tried both of these in cufon to no avail.
This is a button - so as Cufon generates images, this should work, but maybe I'm doing it wrong - can anyone help? | 2009/08/22 | [
"https://Stackoverflow.com/questions/1315771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159131/"
] | Using the element in the following way:
```
<button type="buton">value</button>
```
worked when applying the Cufon style:
```
Cufon.replace('button', {color: '-linear-gradient(#999, 0.45=#666, 0.45=#555, #999)'});
```
Thanks very much :) | I believe there is no way to make Cufon work with `<input type="submit" />`.
Main reason being that there is no place to insert the canvas...
However you could simply switch to the more semantically fit `<button>`, that need closure `</button>` and thus creates the place for the canvas.
Very important though, make sure you specify the type with it as well, since IE7 and below won't submit the form if you don't. It also seems that specifying the type leads to uniform behavior throughout all browsers.
Let me know if the above helped!
Cheers |
1,315,771 | So right now I'm bashing my head - at the moment we use an element for a button to give it our own custom font, fine - this works, but as we're using Cufon on the rest of the site, we're wondering if it's possible to get Cufon working on a button.
So far I've changed the button to an and using standard css styles on an 'input' or 'input[type="submit"]' element work fine - but I've tried both of these in cufon to no avail.
This is a button - so as Cufon generates images, this should work, but maybe I'm doing it wrong - can anyone help? | 2009/08/22 | [
"https://Stackoverflow.com/questions/1315771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159131/"
] | Using the element in the following way:
```
<button type="buton">value</button>
```
worked when applying the Cufon style:
```
Cufon.replace('button', {color: '-linear-gradient(#999, 0.45=#666, 0.45=#555, #999)'});
```
Thanks very much :) | ```
$('.input-button').each(function(){
$(this).hide().after('<span class="input-button">').next('span.input-button').text($(this).val()).click(function(){
$(this).prev('input.input-button').click();
});
});
```
I used the above code to copy my inputs value into a span, which allows me to use cufon. It works great and still falls back to the 'submit' input with javascript disabled. |
1,315,771 | So right now I'm bashing my head - at the moment we use an element for a button to give it our own custom font, fine - this works, but as we're using Cufon on the rest of the site, we're wondering if it's possible to get Cufon working on a button.
So far I've changed the button to an and using standard css styles on an 'input' or 'input[type="submit"]' element work fine - but I've tried both of these in cufon to no avail.
This is a button - so as Cufon generates images, this should work, but maybe I'm doing it wrong - can anyone help? | 2009/08/22 | [
"https://Stackoverflow.com/questions/1315771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159131/"
] | I believe there is no way to make Cufon work with `<input type="submit" />`.
Main reason being that there is no place to insert the canvas...
However you could simply switch to the more semantically fit `<button>`, that need closure `</button>` and thus creates the place for the canvas.
Very important though, make sure you specify the type with it as well, since IE7 and below won't submit the form if you don't. It also seems that specifying the type leads to uniform behavior throughout all browsers.
Let me know if the above helped!
Cheers | The only solution I found to use Cufon on `<input type="submit"/>` buttons was to use Javascript (jQuery personally).
1. Copy the input button's text (the "value" attribute) to a span .
2. Replace the span using Cufon.replace()
3. Remove the input button's text
4. Position the span over the button
5. Propagate the click() event from the span to the button
Done ! |
1,315,771 | So right now I'm bashing my head - at the moment we use an element for a button to give it our own custom font, fine - this works, but as we're using Cufon on the rest of the site, we're wondering if it's possible to get Cufon working on a button.
So far I've changed the button to an and using standard css styles on an 'input' or 'input[type="submit"]' element work fine - but I've tried both of these in cufon to no avail.
This is a button - so as Cufon generates images, this should work, but maybe I'm doing it wrong - can anyone help? | 2009/08/22 | [
"https://Stackoverflow.com/questions/1315771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159131/"
] | ```
$('.input-button').each(function(){
$(this).hide().after('<span class="input-button">').next('span.input-button').text($(this).val()).click(function(){
$(this).prev('input.input-button').click();
});
});
```
I used the above code to copy my inputs value into a span, which allows me to use cufon. It works great and still falls back to the 'submit' input with javascript disabled. | The only solution I found to use Cufon on `<input type="submit"/>` buttons was to use Javascript (jQuery personally).
1. Copy the input button's text (the "value" attribute) to a span .
2. Replace the span using Cufon.replace()
3. Remove the input button's text
4. Position the span over the button
5. Propagate the click() event from the span to the button
Done ! |
1,315,771 | So right now I'm bashing my head - at the moment we use an element for a button to give it our own custom font, fine - this works, but as we're using Cufon on the rest of the site, we're wondering if it's possible to get Cufon working on a button.
So far I've changed the button to an and using standard css styles on an 'input' or 'input[type="submit"]' element work fine - but I've tried both of these in cufon to no avail.
This is a button - so as Cufon generates images, this should work, but maybe I'm doing it wrong - can anyone help? | 2009/08/22 | [
"https://Stackoverflow.com/questions/1315771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159131/"
] | ```
$('.input-button').each(function(){
$(this).hide().after('<span class="input-button">').next('span.input-button').text($(this).val()).click(function(){
$(this).prev('input.input-button').click();
});
});
```
I used the above code to copy my inputs value into a span, which allows me to use cufon. It works great and still falls back to the 'submit' input with javascript disabled. | I believe there is no way to make Cufon work with `<input type="submit" />`.
Main reason being that there is no place to insert the canvas...
However you could simply switch to the more semantically fit `<button>`, that need closure `</button>` and thus creates the place for the canvas.
Very important though, make sure you specify the type with it as well, since IE7 and below won't submit the form if you don't. It also seems that specifying the type leads to uniform behavior throughout all browsers.
Let me know if the above helped!
Cheers |
70,641,367 | I want to fetch array from the product file but it is showing
`'Uncaught TypeError: _product__WEBPACK_IMPORTED_MODULE_1___default(...).map is not a function'`
I have even tried using key in Col but still it is showing the same.
My react code is
```
import product from '../product'
export default function HomeScreen() {
return (
<>
<h1>Latest Products</h1>
<Row>
{product.map((products)=>(
<Col sm={12} md={6} lg={4} xl={3}>
<h3>{products.name}</h3>
</Col>
))}
</Row>
</>
)
}
```
and product file is
```
const product=[
{
_id:'1',
name : 'Shoes',
images : './img.shoe4.jfif',
discription : 'Lorem10j,jdscjscjc nxkd kdn ddksad asdkjdhsadb',
brand : 'Apple',
category : 'Electronics',
price : 89.3,
countInStocks : 3,
rating: 4.5,
numReviews: 4
}
];
``` | 2022/01/09 | [
"https://Stackoverflow.com/questions/70641367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16777689/"
] | For Japanese you should use the wider ideographic space (U+3000) instead normal space. That is, `?right_pad(12, '\x3000')`.
If you need a similarly wide dash, that's U+30FC, so like `?right_pad(12, '\x30FC')`.
All these can of course be typed directly as well, like `?right_pad(12, 'ー')`, but in that case be careful with the template file encoding. | It is not ending at the same place because the length of a Japanese character is different from the length of the `-`.
The solution would be to use a Japanese character with the same width as a kanji, and the same meaning as the dash. I don't know if such a character exists (maybe U+30FB: `・` ) |
26,842,477 | I am using below command to join two files using first two columns.
```
awk 'NR==FNR{a[$1,$2]=substr($0,3);next} ($1,$2) in a{print $0, a[$1,$2] > "br0102_3.txt"}' br01.txt br02.txt
```
Now, by default AWk command uses whitespaces as the separators. But my file may contain single space between two words, e.g.
File 1:
```
ABCD TEXT1 TEXT2 123123112312312312312312312312312312
BCDEFG TEXT3TEXT4 133123123123123123123123123125423423
QWERT TEXT5TEXT6 123123123123125456678786789698758567
```
File 2:
```
ABCD TEXT1 TEXT2 12312312312312312312312312312
BCDEFG TEXT3TEXT4 31242342342342342342342342343
MNHT TEXT8 TEXT9 31242342342342342342342342343
```
I want the result file as ;
```
ABCD TEXT1 TEXT2 123123112312312312312312312312312312 12312312312312312312312312312
BCDEFG TEXT3TEXT4 133123123123123123123123123125423423 31242342342342342342342342343
QWERT TEXT5TEXT6 123123123123125456678786789698758567
MNHT TEXT8 TEXT9 31242342342342342342342342343
```
Any hints ? | 2014/11/10 | [
"https://Stackoverflow.com/questions/26842477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/960778/"
] | awk supports a regular expression as the value of `FS` so you can specify a regular expression that matches at least two spaces. Something like `-F '[[:space:]][[:space:]]+'`.
```
$ awk '{print NF}' File2
4
3
4
$ awk -F '[[:space:]][[:space:]]+' '{print NF}' File2
3
3
3
``` | You are using fixed width fields so you should be using gnu awk FIELDWIDTHS (or similar) to separate the fields, e.g. if the 2nd field is the 15 chars from char 8 to char 23 inclusive in this file:
```
$ cat file
abc def ghi klm
AAAAAAAB C D E F G H IJJJJ
abc def ghi klm
$ awk -v FIELDWIDTHS="7 15 4" '{print "<" $2 ">"}' file
<def ghi >
<B C D E F G H I>
< def ghi >
```
Any solution that relies on a certain number of spaces between fields will fail when you have 1 or zero spaces between your fields.
If you want to strip leading/trailing blanks from your target field(s):
```
$ awk -v FIELDWIDTHS="7 15 4" '{gsub(/^\s+|\s+$/,"",$2); print "<" $2 ">"}' file
<def ghi>
<B C D E F G H I>
<def ghi>
``` |
26,842,477 | I am using below command to join two files using first two columns.
```
awk 'NR==FNR{a[$1,$2]=substr($0,3);next} ($1,$2) in a{print $0, a[$1,$2] > "br0102_3.txt"}' br01.txt br02.txt
```
Now, by default AWk command uses whitespaces as the separators. But my file may contain single space between two words, e.g.
File 1:
```
ABCD TEXT1 TEXT2 123123112312312312312312312312312312
BCDEFG TEXT3TEXT4 133123123123123123123123123125423423
QWERT TEXT5TEXT6 123123123123125456678786789698758567
```
File 2:
```
ABCD TEXT1 TEXT2 12312312312312312312312312312
BCDEFG TEXT3TEXT4 31242342342342342342342342343
MNHT TEXT8 TEXT9 31242342342342342342342342343
```
I want the result file as ;
```
ABCD TEXT1 TEXT2 123123112312312312312312312312312312 12312312312312312312312312312
BCDEFG TEXT3TEXT4 133123123123123123123123123125423423 31242342342342342342342342343
QWERT TEXT5TEXT6 123123123123125456678786789698758567
MNHT TEXT8 TEXT9 31242342342342342342342342343
```
Any hints ? | 2014/11/10 | [
"https://Stackoverflow.com/questions/26842477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/960778/"
] | awk supports a regular expression as the value of `FS` so you can specify a regular expression that matches at least two spaces. Something like `-F '[[:space:]][[:space:]]+'`.
```
$ awk '{print NF}' File2
4
3
4
$ awk -F '[[:space:]][[:space:]]+' '{print NF}' File2
3
3
3
``` | awk automatically detects multiple spaces if `field seperator` is set to " "
Thus, this simply works:
```
awk -F' ' '{ print $2 }'
```
to get the second column if you have a table like the one mentioned. |
26,842,477 | I am using below command to join two files using first two columns.
```
awk 'NR==FNR{a[$1,$2]=substr($0,3);next} ($1,$2) in a{print $0, a[$1,$2] > "br0102_3.txt"}' br01.txt br02.txt
```
Now, by default AWk command uses whitespaces as the separators. But my file may contain single space between two words, e.g.
File 1:
```
ABCD TEXT1 TEXT2 123123112312312312312312312312312312
BCDEFG TEXT3TEXT4 133123123123123123123123123125423423
QWERT TEXT5TEXT6 123123123123125456678786789698758567
```
File 2:
```
ABCD TEXT1 TEXT2 12312312312312312312312312312
BCDEFG TEXT3TEXT4 31242342342342342342342342343
MNHT TEXT8 TEXT9 31242342342342342342342342343
```
I want the result file as ;
```
ABCD TEXT1 TEXT2 123123112312312312312312312312312312 12312312312312312312312312312
BCDEFG TEXT3TEXT4 133123123123123123123123123125423423 31242342342342342342342342343
QWERT TEXT5TEXT6 123123123123125456678786789698758567
MNHT TEXT8 TEXT9 31242342342342342342342342343
```
Any hints ? | 2014/11/10 | [
"https://Stackoverflow.com/questions/26842477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/960778/"
] | You are using fixed width fields so you should be using gnu awk FIELDWIDTHS (or similar) to separate the fields, e.g. if the 2nd field is the 15 chars from char 8 to char 23 inclusive in this file:
```
$ cat file
abc def ghi klm
AAAAAAAB C D E F G H IJJJJ
abc def ghi klm
$ awk -v FIELDWIDTHS="7 15 4" '{print "<" $2 ">"}' file
<def ghi >
<B C D E F G H I>
< def ghi >
```
Any solution that relies on a certain number of spaces between fields will fail when you have 1 or zero spaces between your fields.
If you want to strip leading/trailing blanks from your target field(s):
```
$ awk -v FIELDWIDTHS="7 15 4" '{gsub(/^\s+|\s+$/,"",$2); print "<" $2 ">"}' file
<def ghi>
<B C D E F G H I>
<def ghi>
``` | awk automatically detects multiple spaces if `field seperator` is set to " "
Thus, this simply works:
```
awk -F' ' '{ print $2 }'
```
to get the second column if you have a table like the one mentioned. |
15,616,415 | Recently, we are facing a strange problem where some XHR requests, sent from Passenger to our application server, fail to execute properly.
Please have look at following chain of events:
1. LB Passenger sends a request to the application server.
2. Rails returns a NoMethodError exception when trying to figure out which controller action this request is supposed to be processed by.
```
Rails error log:
Started POST "/user/" for 194.29.65.21 at 2013-03-25 13:14:38 +0100
NoMethodError (undefined method `[]' for nil:NilClass):
```
Here is a log when Rails is able to figure out which controller/action a request should be routed to:
```
Started POST "/User/" for 194.29.65.21 at 2013-03-25 13:14:38 +0100
Processing by Web::UserController#index as
Parameters: {"c"=>"1", "fref"=>""}
```
3. This error gets propagated to the application server passenger which throws the following error:
```
[ pid=20071 thr=3074915216 file=ext/nginx/HelperAgent.cpp:577
time=2013-03-24 22:25:58.257 ]: Uncaught exception in PassengerServer
client thread: exception: Cannot read response from backend
process: Connection reset by peer (104) backtrace:
in 'void Client::forwardResponse(Passenger::SessionPtr&, Passenger::FileDescriptor&)' (HelperAgent.cpp:361)
in 'void Client::handleRequest(Passenger::FileDescriptor&)' (HelperAgent.cpp:503)
in 'void Client::threadMain()' (HelperAgent.cpp:596)
```
4. And finally LB Nginx gives this error: `up stream status = 500 error`.
This error comes randomly for a given route. Even the frequency of occurrence of this error changes randomly.
System details:
* Ruby: 1.9.2p180
* Rails : 3.0.5
* Phusion Passenger version 3.0.5
* nginx version: n
We think this happens because Passenger is failing to send the whole request data to Rails which results in Rails failing to decide the valid controller action. | 2013/03/25 | [
"https://Stackoverflow.com/questions/15616415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1903272/"
] | Found out a workaround. (*note target browser*)
Mesh(grid/skeleton) of table is not shown when popupPanel is hidden only when table has style attribute:
```
style="border-collapse:separate"
``` | Thanks for your workaround!
However, the table afterwards has some gaps between the table cells.
In order to get the same appearance of the table back, you may also want to use a simple jQuery function to remove the style when the popup is first shown:
```
<a4j:commandButton id="showPopupButton" value="Show Details" render="detailsPopup"
limitRender="true"
oncomplete="#{rich:jQuery('detailsPopupDataTable')}.css('border-collapse','');
#{rich:component('detailsPopup')}.show(); return true;"/>
``` |
18,411,554 | I’m fairly new to TypeScript and trying to setup some unit tests for my TypeScript code base. The problem is that my code depends on other's work and all these references are done in the form of hard coded relative paths like “......\somefile.d.ts”. When come to unit test, I want to fake out some of the dependencies but don’t know how to make TypeScript take my Fakes instead of hard coded referenced files.
My question is: is there a way not to hard coding the reference path in source code? Are there things like preprocessor or Macro in TypeScript, or could I use the project system to help resolving dependency, rather than hard coding them in source code? | 2013/08/23 | [
"https://Stackoverflow.com/questions/18411554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471031/"
] | Check out grunt-ts reference file generation : <https://github.com/basarat/grunt-ts#reference-file-generation>
What you can do is that have seperate targets, one for dev and one for test :
```
dev: {
src: ["app/**/*.ts", "!app/**/*.spec.ts"], // Exclude your spec files
reference: "./app/reference.ts",
out: 'app/out.js',
},
test: {
src: ["app/**/*.ts"], // Include all files
reference: "./app/reference.ts",
out: 'app/out.js',
},
```
Now you only reference `app/reference.ts`from all your files. When you want to run tests, build for tests, when you want to release / dev build for dev.
Also check out this video tutorial : <http://www.youtube.com/watch?v=0-6vT7xgE4Y&hd=1> | Instead of loading different files have you considered using a test or spy framework to swap out the implementation for a test implementation?
In our TypeScript projects we used jasmine spies (<https://github.com/pivotal/jasmine/wiki/Spies>, <http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/>) to fake out dependencies. We loaded the main source code as normal and then used the createSpyObj, and spyOn functions to replace the dependencies with new TypeScript defined in our test files.
Using this approach you don't need to make any modifications to the main source code or include paths - everything is done in the test files. |
48,147,422 | Pointer arithmetics between consecutive members of same type in a struct used to be a common practice while pointer arithmetics is only valid inside an array. In C++ it would be explicitely Undefined Behaviour because an array can only be created by a declaration or a new expression. But C language defines an array as *a contiguously allocated nonempty set of objects with a
particular member object type, called the element type.* (n1570 draft for C11, 6.2.5 types §20). So provided we can make sure that that the members are consecutive (meaning no padding between them) it could be legal to see that as an array.
Here is a simplified example, that compiles without a warning and gives expected results at run time:
```
#include <stdio.h>
#include <stddef.h>
#include <assert.h>
struct quad {
int x;
int y;
int z;
int t;
};
int main() {
// ensure members are consecutive (note 1)
static_assert(offsetof(struct quad, t) == 3 * sizeof(int),
"unexpected padding in quad struct");
struct quad q;
int *ix = &q.x;
for(int i=0; i<4; i++) {
ix[i] = i;
}
printf("Quad: %d %d %d %d\n", q.x, q.y, q.z, q.t);
return 0;
}
```
It does not really make sense here, but I have already seen real world example where iterating among members of a struct allows simpler code with less risk of typo.
Question:
In the above example, is the `static_assert` enough to make legal the aliasing of the struct with an array?
---
(note 1) As a struct *describes a sequentially allocated nonempty set of member objects*, later members must have increasing addresses. Simply the compiler could include padding between them. So the offset of last member (here `t`) if 3 times `sizeof(int)` plus the total padding before it. If the offset is exactly `3 * sizeof(int)` then there is no padding in struct
---
The question proposed as a duplicate contains both an accepted answer that let think that it would be UB, and a [+1 answer](https://stackoverflow.com/a/47224798/3545273) that let think that it could be legal because I could ensure that no padding could exist | 2018/01/08 | [
"https://Stackoverflow.com/questions/48147422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3545273/"
] | The problem here is your definition of *contiguously allocated*: "we can make sure that that the members are consecutive (meaning no padding between them)".
Although that is a corollary of being contiguously allocated, it does not define the property.
Your structure members are separate variables with automatic storage duration, in a particular order with or without padding depending on how you are able to control your compiler, that's all. As such you can't use pointer arithmetic to reach one member given the address of another, and the behaviour on doing so is undefined. | To start with -
Quoting `C11`, chapter [§6.5.2.1p2](http://port70.net/~nsz/c/c11/n1570.html#6.5.2.1p2)
>
> A postfix expression followed by an expression in square brackets `[]` is a subscripted designation of an element of an array object. The definition of the subscript operator `[]` is that `E1[E2]` is identical to `(*((E1)+(E2)))`. `...`
>
>
>
Which means `ix[i]` evaluates to `*(ix + i)`. A subexpression here is `ix + i`.
`ix` has type `pointer to integer`.
Now,
Quoting `C11`, chapter [§6.5.6p7](http://port70.net/~nsz/c/c11/n1570.html#6.5.6p7)
>
> For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
>
>
>
We know thus that `ix` is pointing to an array of size one. And even constructing a pointer to beyond the length (except the off by one) is Undefined Behavior, let alone dereferencing it.
Which leads me to interpret that is indeed not allowed. |
48,147,422 | Pointer arithmetics between consecutive members of same type in a struct used to be a common practice while pointer arithmetics is only valid inside an array. In C++ it would be explicitely Undefined Behaviour because an array can only be created by a declaration or a new expression. But C language defines an array as *a contiguously allocated nonempty set of objects with a
particular member object type, called the element type.* (n1570 draft for C11, 6.2.5 types §20). So provided we can make sure that that the members are consecutive (meaning no padding between them) it could be legal to see that as an array.
Here is a simplified example, that compiles without a warning and gives expected results at run time:
```
#include <stdio.h>
#include <stddef.h>
#include <assert.h>
struct quad {
int x;
int y;
int z;
int t;
};
int main() {
// ensure members are consecutive (note 1)
static_assert(offsetof(struct quad, t) == 3 * sizeof(int),
"unexpected padding in quad struct");
struct quad q;
int *ix = &q.x;
for(int i=0; i<4; i++) {
ix[i] = i;
}
printf("Quad: %d %d %d %d\n", q.x, q.y, q.z, q.t);
return 0;
}
```
It does not really make sense here, but I have already seen real world example where iterating among members of a struct allows simpler code with less risk of typo.
Question:
In the above example, is the `static_assert` enough to make legal the aliasing of the struct with an array?
---
(note 1) As a struct *describes a sequentially allocated nonempty set of member objects*, later members must have increasing addresses. Simply the compiler could include padding between them. So the offset of last member (here `t`) if 3 times `sizeof(int)` plus the total padding before it. If the offset is exactly `3 * sizeof(int)` then there is no padding in struct
---
The question proposed as a duplicate contains both an accepted answer that let think that it would be UB, and a [+1 answer](https://stackoverflow.com/a/47224798/3545273) that let think that it could be legal because I could ensure that no padding could exist | 2018/01/08 | [
"https://Stackoverflow.com/questions/48147422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3545273/"
] | The problem here is your definition of *contiguously allocated*: "we can make sure that that the members are consecutive (meaning no padding between them)".
Although that is a corollary of being contiguously allocated, it does not define the property.
Your structure members are separate variables with automatic storage duration, in a particular order with or without padding depending on how you are able to control your compiler, that's all. As such you can't use pointer arithmetic to reach one member given the address of another, and the behaviour on doing so is undefined. | It would be UB. As established in [that other question](https://stackoverflow.com/q/48148477/3545273), the static\_assert can test for possible padding in a conformant way. So yes the 4 members of the struct are indeed consecutively allocated.
But the real problem is that consecutive allocation is necessary but not enough to constitute an array. Even if I could not find a clear reference for it in C standard, objects cannot overlap during their lifetime - this is more clearly explicited in C++ standard. They can be members of an aggregate (struct or array) but aggregates are not allowed to overlap. This is coherent with the response to Defect Report #017 dated 10 Dec 1992 to C89 cited by Antti Haapala in its [answer](https://stackoverflow.com/a/47224596/3545273) to the proposed duplicate.
Even if C has no `new` statement, allocated storage has has the particular property of having no declared type. That allows to create dynamically objects in that storage, but the lifetime of an allocated object ends when an object of a different type is created at its address. So even in allocated memory we cannot have at the same time both an array and a struct.
According to [Lundin's answer](https://stackoverflow.com/a/48148933/3545273), type punning through an union between an array and a struct should work, because a (non normative) note says
>
> If the member used to read the contents of a union object is not the same as the member last used to
> store a value in the object, the appropriate part of the object representation of the value is reinterpreted
> as an object representation in the new type
>
>
>
and both type will have same representation: 4 consecutive integers
Without unions, an way to iterate through members of an array would be at the byte level because 6.3.2.3 Conversions/Pointers says:
>
> 7 ... When a pointer to an object is converted to a pointer to a character type,
> the result points to the lowest addressed byte of the object. Successive increments of the
> result, up to the size of the object, yield pointers to the remaining bytes of the object.
>
>
>
```
char *p = q;
for (i=0; i<4; i++) {
int *ix = (int *) (p + i * sizeof(int)); // Ok: points to the expected int member
*ix = i;
}
```
But pointer arithmetics on non character types to iterate over members of a struct is UB simply because individual members of a struct cannot be at the same time members of an array. |
48,147,422 | Pointer arithmetics between consecutive members of same type in a struct used to be a common practice while pointer arithmetics is only valid inside an array. In C++ it would be explicitely Undefined Behaviour because an array can only be created by a declaration or a new expression. But C language defines an array as *a contiguously allocated nonempty set of objects with a
particular member object type, called the element type.* (n1570 draft for C11, 6.2.5 types §20). So provided we can make sure that that the members are consecutive (meaning no padding between them) it could be legal to see that as an array.
Here is a simplified example, that compiles without a warning and gives expected results at run time:
```
#include <stdio.h>
#include <stddef.h>
#include <assert.h>
struct quad {
int x;
int y;
int z;
int t;
};
int main() {
// ensure members are consecutive (note 1)
static_assert(offsetof(struct quad, t) == 3 * sizeof(int),
"unexpected padding in quad struct");
struct quad q;
int *ix = &q.x;
for(int i=0; i<4; i++) {
ix[i] = i;
}
printf("Quad: %d %d %d %d\n", q.x, q.y, q.z, q.t);
return 0;
}
```
It does not really make sense here, but I have already seen real world example where iterating among members of a struct allows simpler code with less risk of typo.
Question:
In the above example, is the `static_assert` enough to make legal the aliasing of the struct with an array?
---
(note 1) As a struct *describes a sequentially allocated nonempty set of member objects*, later members must have increasing addresses. Simply the compiler could include padding between them. So the offset of last member (here `t`) if 3 times `sizeof(int)` plus the total padding before it. If the offset is exactly `3 * sizeof(int)` then there is no padding in struct
---
The question proposed as a duplicate contains both an accepted answer that let think that it would be UB, and a [+1 answer](https://stackoverflow.com/a/47224798/3545273) that let think that it could be legal because I could ensure that no padding could exist | 2018/01/08 | [
"https://Stackoverflow.com/questions/48147422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3545273/"
] | I'm gonna argue UB. First and foremost, the mandatory quote from **6.5.6 Additive operators**:
>
> When an expression that has integer type is added to or subtracted
> from a pointer, the result has the type of the pointer operand. If the
> pointer operand points to an element of an **array object**, and the array
> is large enough, the result points to an element offset from the
> original element such that the difference of the subscripts of the
> resulting and original array elements equals the integer expression.
> In other words, if the expression P points to the i-th element of an
> **array object**, the expressions (P)+N (equivalently, N+(P)) and (P)-N
> (where N has the value n) point to, respectively, the i+n-th and
> i-n-th elements of the **array object**, provided they exist. Moreover, if
> the expression P points to the last element of an array object, the
> expression (P)+1 points one past the last element of the **array object**,
> and if the expression Q points one past the last element of an **array
> object**, the expression (Q)-1 points to the last element of the array
> object. If both the pointer operand and the result point to elements
> of the same **array object**, or one past the last element of the **array
> object**, the evaluation shall not produce an overflow; otherwise, the
> behavior is undefined. If the result points one past the last element
> of the **array object**, it shall not be used as the operand of a unary \*
> operator that is evaluated.
>
>
>
I emphasized what I consider the crux of the matter. You are right when you say that an array object is *"a contiguously allocated nonempty set of objects with a particular member object type, called the element type"*. But is the converse true? Does a consecutively allocated set of objects constitute an array object?
I'm going to say no. Objects need to be explicitly created.
So for your example, there is no array object. There are generally two ways to create objects in C. Declare them with automatic, static or thread local duration. Or allocate them and give the storage an effective type. You did neither to create an array. That makes the arithmetic officially undefined. | To start with -
Quoting `C11`, chapter [§6.5.2.1p2](http://port70.net/~nsz/c/c11/n1570.html#6.5.2.1p2)
>
> A postfix expression followed by an expression in square brackets `[]` is a subscripted designation of an element of an array object. The definition of the subscript operator `[]` is that `E1[E2]` is identical to `(*((E1)+(E2)))`. `...`
>
>
>
Which means `ix[i]` evaluates to `*(ix + i)`. A subexpression here is `ix + i`.
`ix` has type `pointer to integer`.
Now,
Quoting `C11`, chapter [§6.5.6p7](http://port70.net/~nsz/c/c11/n1570.html#6.5.6p7)
>
> For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
>
>
>
We know thus that `ix` is pointing to an array of size one. And even constructing a pointer to beyond the length (except the off by one) is Undefined Behavior, let alone dereferencing it.
Which leads me to interpret that is indeed not allowed. |
48,147,422 | Pointer arithmetics between consecutive members of same type in a struct used to be a common practice while pointer arithmetics is only valid inside an array. In C++ it would be explicitely Undefined Behaviour because an array can only be created by a declaration or a new expression. But C language defines an array as *a contiguously allocated nonempty set of objects with a
particular member object type, called the element type.* (n1570 draft for C11, 6.2.5 types §20). So provided we can make sure that that the members are consecutive (meaning no padding between them) it could be legal to see that as an array.
Here is a simplified example, that compiles without a warning and gives expected results at run time:
```
#include <stdio.h>
#include <stddef.h>
#include <assert.h>
struct quad {
int x;
int y;
int z;
int t;
};
int main() {
// ensure members are consecutive (note 1)
static_assert(offsetof(struct quad, t) == 3 * sizeof(int),
"unexpected padding in quad struct");
struct quad q;
int *ix = &q.x;
for(int i=0; i<4; i++) {
ix[i] = i;
}
printf("Quad: %d %d %d %d\n", q.x, q.y, q.z, q.t);
return 0;
}
```
It does not really make sense here, but I have already seen real world example where iterating among members of a struct allows simpler code with less risk of typo.
Question:
In the above example, is the `static_assert` enough to make legal the aliasing of the struct with an array?
---
(note 1) As a struct *describes a sequentially allocated nonempty set of member objects*, later members must have increasing addresses. Simply the compiler could include padding between them. So the offset of last member (here `t`) if 3 times `sizeof(int)` plus the total padding before it. If the offset is exactly `3 * sizeof(int)` then there is no padding in struct
---
The question proposed as a duplicate contains both an accepted answer that let think that it would be UB, and a [+1 answer](https://stackoverflow.com/a/47224798/3545273) that let think that it could be legal because I could ensure that no padding could exist | 2018/01/08 | [
"https://Stackoverflow.com/questions/48147422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3545273/"
] | I'm gonna argue UB. First and foremost, the mandatory quote from **6.5.6 Additive operators**:
>
> When an expression that has integer type is added to or subtracted
> from a pointer, the result has the type of the pointer operand. If the
> pointer operand points to an element of an **array object**, and the array
> is large enough, the result points to an element offset from the
> original element such that the difference of the subscripts of the
> resulting and original array elements equals the integer expression.
> In other words, if the expression P points to the i-th element of an
> **array object**, the expressions (P)+N (equivalently, N+(P)) and (P)-N
> (where N has the value n) point to, respectively, the i+n-th and
> i-n-th elements of the **array object**, provided they exist. Moreover, if
> the expression P points to the last element of an array object, the
> expression (P)+1 points one past the last element of the **array object**,
> and if the expression Q points one past the last element of an **array
> object**, the expression (Q)-1 points to the last element of the array
> object. If both the pointer operand and the result point to elements
> of the same **array object**, or one past the last element of the **array
> object**, the evaluation shall not produce an overflow; otherwise, the
> behavior is undefined. If the result points one past the last element
> of the **array object**, it shall not be used as the operand of a unary \*
> operator that is evaluated.
>
>
>
I emphasized what I consider the crux of the matter. You are right when you say that an array object is *"a contiguously allocated nonempty set of objects with a particular member object type, called the element type"*. But is the converse true? Does a consecutively allocated set of objects constitute an array object?
I'm going to say no. Objects need to be explicitly created.
So for your example, there is no array object. There are generally two ways to create objects in C. Declare them with automatic, static or thread local duration. Or allocate them and give the storage an effective type. You did neither to create an array. That makes the arithmetic officially undefined. | It would be UB. As established in [that other question](https://stackoverflow.com/q/48148477/3545273), the static\_assert can test for possible padding in a conformant way. So yes the 4 members of the struct are indeed consecutively allocated.
But the real problem is that consecutive allocation is necessary but not enough to constitute an array. Even if I could not find a clear reference for it in C standard, objects cannot overlap during their lifetime - this is more clearly explicited in C++ standard. They can be members of an aggregate (struct or array) but aggregates are not allowed to overlap. This is coherent with the response to Defect Report #017 dated 10 Dec 1992 to C89 cited by Antti Haapala in its [answer](https://stackoverflow.com/a/47224596/3545273) to the proposed duplicate.
Even if C has no `new` statement, allocated storage has has the particular property of having no declared type. That allows to create dynamically objects in that storage, but the lifetime of an allocated object ends when an object of a different type is created at its address. So even in allocated memory we cannot have at the same time both an array and a struct.
According to [Lundin's answer](https://stackoverflow.com/a/48148933/3545273), type punning through an union between an array and a struct should work, because a (non normative) note says
>
> If the member used to read the contents of a union object is not the same as the member last used to
> store a value in the object, the appropriate part of the object representation of the value is reinterpreted
> as an object representation in the new type
>
>
>
and both type will have same representation: 4 consecutive integers
Without unions, an way to iterate through members of an array would be at the byte level because 6.3.2.3 Conversions/Pointers says:
>
> 7 ... When a pointer to an object is converted to a pointer to a character type,
> the result points to the lowest addressed byte of the object. Successive increments of the
> result, up to the size of the object, yield pointers to the remaining bytes of the object.
>
>
>
```
char *p = q;
for (i=0; i<4; i++) {
int *ix = (int *) (p + i * sizeof(int)); // Ok: points to the expected int member
*ix = i;
}
```
But pointer arithmetics on non character types to iterate over members of a struct is UB simply because individual members of a struct cannot be at the same time members of an array. |
48,147,422 | Pointer arithmetics between consecutive members of same type in a struct used to be a common practice while pointer arithmetics is only valid inside an array. In C++ it would be explicitely Undefined Behaviour because an array can only be created by a declaration or a new expression. But C language defines an array as *a contiguously allocated nonempty set of objects with a
particular member object type, called the element type.* (n1570 draft for C11, 6.2.5 types §20). So provided we can make sure that that the members are consecutive (meaning no padding between them) it could be legal to see that as an array.
Here is a simplified example, that compiles without a warning and gives expected results at run time:
```
#include <stdio.h>
#include <stddef.h>
#include <assert.h>
struct quad {
int x;
int y;
int z;
int t;
};
int main() {
// ensure members are consecutive (note 1)
static_assert(offsetof(struct quad, t) == 3 * sizeof(int),
"unexpected padding in quad struct");
struct quad q;
int *ix = &q.x;
for(int i=0; i<4; i++) {
ix[i] = i;
}
printf("Quad: %d %d %d %d\n", q.x, q.y, q.z, q.t);
return 0;
}
```
It does not really make sense here, but I have already seen real world example where iterating among members of a struct allows simpler code with less risk of typo.
Question:
In the above example, is the `static_assert` enough to make legal the aliasing of the struct with an array?
---
(note 1) As a struct *describes a sequentially allocated nonempty set of member objects*, later members must have increasing addresses. Simply the compiler could include padding between them. So the offset of last member (here `t`) if 3 times `sizeof(int)` plus the total padding before it. If the offset is exactly `3 * sizeof(int)` then there is no padding in struct
---
The question proposed as a duplicate contains both an accepted answer that let think that it would be UB, and a [+1 answer](https://stackoverflow.com/a/47224798/3545273) that let think that it could be legal because I could ensure that no padding could exist | 2018/01/08 | [
"https://Stackoverflow.com/questions/48147422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3545273/"
] | No, it isn't legal to alias a `struct` and array like this, it violates strict aliasing. The work-around is to wrap the struct in a union, which contains both an array and the individual members:
```
union something {
struct quad {
int x;
int y;
int z;
int t;
};
int array [4];
};
```
This dodges the strict aliasing violation, but you may still have padding bytes. Which you can detect with the static assert.
Another issue remains, and that is that you can't use pointer arithmetic on an `int*` pointing at the first member of the struct, for various obscure reasons outlined in the specified behavior of the additive operators - they require that the pointer points at an array type.
The best way to dodge all of this is to simply use the array member of the union above. This together with a static assert results in well-defined, rugged and portable code.
(In theory, you could also use a pointer to character type to iterate through the struct - unlike `int*` this would be allowed as per 6.3.2.3/7. But this is a more messy solution if you have no interest in the individual bytes.) | To start with -
Quoting `C11`, chapter [§6.5.2.1p2](http://port70.net/~nsz/c/c11/n1570.html#6.5.2.1p2)
>
> A postfix expression followed by an expression in square brackets `[]` is a subscripted designation of an element of an array object. The definition of the subscript operator `[]` is that `E1[E2]` is identical to `(*((E1)+(E2)))`. `...`
>
>
>
Which means `ix[i]` evaluates to `*(ix + i)`. A subexpression here is `ix + i`.
`ix` has type `pointer to integer`.
Now,
Quoting `C11`, chapter [§6.5.6p7](http://port70.net/~nsz/c/c11/n1570.html#6.5.6p7)
>
> For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
>
>
>
We know thus that `ix` is pointing to an array of size one. And even constructing a pointer to beyond the length (except the off by one) is Undefined Behavior, let alone dereferencing it.
Which leads me to interpret that is indeed not allowed. |
48,147,422 | Pointer arithmetics between consecutive members of same type in a struct used to be a common practice while pointer arithmetics is only valid inside an array. In C++ it would be explicitely Undefined Behaviour because an array can only be created by a declaration or a new expression. But C language defines an array as *a contiguously allocated nonempty set of objects with a
particular member object type, called the element type.* (n1570 draft for C11, 6.2.5 types §20). So provided we can make sure that that the members are consecutive (meaning no padding between them) it could be legal to see that as an array.
Here is a simplified example, that compiles without a warning and gives expected results at run time:
```
#include <stdio.h>
#include <stddef.h>
#include <assert.h>
struct quad {
int x;
int y;
int z;
int t;
};
int main() {
// ensure members are consecutive (note 1)
static_assert(offsetof(struct quad, t) == 3 * sizeof(int),
"unexpected padding in quad struct");
struct quad q;
int *ix = &q.x;
for(int i=0; i<4; i++) {
ix[i] = i;
}
printf("Quad: %d %d %d %d\n", q.x, q.y, q.z, q.t);
return 0;
}
```
It does not really make sense here, but I have already seen real world example where iterating among members of a struct allows simpler code with less risk of typo.
Question:
In the above example, is the `static_assert` enough to make legal the aliasing of the struct with an array?
---
(note 1) As a struct *describes a sequentially allocated nonempty set of member objects*, later members must have increasing addresses. Simply the compiler could include padding between them. So the offset of last member (here `t`) if 3 times `sizeof(int)` plus the total padding before it. If the offset is exactly `3 * sizeof(int)` then there is no padding in struct
---
The question proposed as a duplicate contains both an accepted answer that let think that it would be UB, and a [+1 answer](https://stackoverflow.com/a/47224798/3545273) that let think that it could be legal because I could ensure that no padding could exist | 2018/01/08 | [
"https://Stackoverflow.com/questions/48147422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3545273/"
] | No, it isn't legal to alias a `struct` and array like this, it violates strict aliasing. The work-around is to wrap the struct in a union, which contains both an array and the individual members:
```
union something {
struct quad {
int x;
int y;
int z;
int t;
};
int array [4];
};
```
This dodges the strict aliasing violation, but you may still have padding bytes. Which you can detect with the static assert.
Another issue remains, and that is that you can't use pointer arithmetic on an `int*` pointing at the first member of the struct, for various obscure reasons outlined in the specified behavior of the additive operators - they require that the pointer points at an array type.
The best way to dodge all of this is to simply use the array member of the union above. This together with a static assert results in well-defined, rugged and portable code.
(In theory, you could also use a pointer to character type to iterate through the struct - unlike `int*` this would be allowed as per 6.3.2.3/7. But this is a more messy solution if you have no interest in the individual bytes.) | It would be UB. As established in [that other question](https://stackoverflow.com/q/48148477/3545273), the static\_assert can test for possible padding in a conformant way. So yes the 4 members of the struct are indeed consecutively allocated.
But the real problem is that consecutive allocation is necessary but not enough to constitute an array. Even if I could not find a clear reference for it in C standard, objects cannot overlap during their lifetime - this is more clearly explicited in C++ standard. They can be members of an aggregate (struct or array) but aggregates are not allowed to overlap. This is coherent with the response to Defect Report #017 dated 10 Dec 1992 to C89 cited by Antti Haapala in its [answer](https://stackoverflow.com/a/47224596/3545273) to the proposed duplicate.
Even if C has no `new` statement, allocated storage has has the particular property of having no declared type. That allows to create dynamically objects in that storage, but the lifetime of an allocated object ends when an object of a different type is created at its address. So even in allocated memory we cannot have at the same time both an array and a struct.
According to [Lundin's answer](https://stackoverflow.com/a/48148933/3545273), type punning through an union between an array and a struct should work, because a (non normative) note says
>
> If the member used to read the contents of a union object is not the same as the member last used to
> store a value in the object, the appropriate part of the object representation of the value is reinterpreted
> as an object representation in the new type
>
>
>
and both type will have same representation: 4 consecutive integers
Without unions, an way to iterate through members of an array would be at the byte level because 6.3.2.3 Conversions/Pointers says:
>
> 7 ... When a pointer to an object is converted to a pointer to a character type,
> the result points to the lowest addressed byte of the object. Successive increments of the
> result, up to the size of the object, yield pointers to the remaining bytes of the object.
>
>
>
```
char *p = q;
for (i=0; i<4; i++) {
int *ix = (int *) (p + i * sizeof(int)); // Ok: points to the expected int member
*ix = i;
}
```
But pointer arithmetics on non character types to iterate over members of a struct is UB simply because individual members of a struct cannot be at the same time members of an array. |
27,648,391 | **HTML**
```
<body>
<div class="wordsmith">
<p>WORDSMITH: dummy text here.</p>
</div>
<div class="menu">
<ul>
<li><a id="wordsmith">The Wordsmith</a></li>
<li><a id="tracksmith">The Tracksmith</a></li>
<li><a id="nerdsmith">The Nerdsmith</a></li>
<li><a id="family">The Family Man</li>
</ul>
</div>
```
**CSS**
```
.menu {
background: rgba(0,0,0,0.6);
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
text-align: center;
}
.wordsmith {
background: rgba(0,0,0,0.6);
max-width: 500px;
margin: 0 auto;
padding: 15px;
display: none;
}
.menu #wordsmith:hover ~ .wordsmith {
display: block;
}
```
I have a menu centered in the middle of the page with text links in an UL. What I'm trying to achieve is on hovering over one of the menu items, a div with information will appear up top. The original solution to this I found [here](http://jsfiddle.net/gaby/n5fzB/2/) (JS Fiddle). If I try to achieve this outside of a div and UL, everything works. As soon as I put the menu items in a div OR an UL, the CSS breaks. Am I calling the CSS selector correctly with the ".menu #wordsmith" part? Any help is appreciated! Keep in mind, I'm trying to do this strictly with CSS and html, not JS. Thanks. | 2014/12/25 | [
"https://Stackoverflow.com/questions/27648391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2525633/"
] | AFAIK the are no predecessor or ancestor combinators/selectors so this is not possible in CSS. [`~`](http://www.w3.org/TR/css3-selectors/#general-sibling-combinators) is the general sibling combinator and `#wordsmith` and `.wordsmith` are not siblings, `.wordsmith` is a predecessor of an ancestor of `#wordsmith`.
If you really need to do this you'll have to use JavaScript or re-factor your HTML. | demo - <http://jsfiddle.net/n5fzB/229/>
with jQuery you can do this
```js
$("#f").hover(
function() {
$('.ab').css('display', 'block');
$('.a').css('display', 'none');
},
function() {
$('.ab').css('display', 'none');
$('.a').css('display', 'block');
}
);
$("#s").hover(
function() {
$('.abc').css('display', 'block');
$('.a').css('display', 'none');
},
function() {
$('.abc').css('display', 'none');
$('.a').css('display', 'block');
}
);
```
```css
.abc,.ab {
display: none;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><a id="f">Show First content!</a></li>
<li><a id="s">Show Second content!!</a></li>
</ul>
<div class="a">Default Content</div>
<div class="ab">First content</div>
<div class="abc">Second content</div>
``` |
27,648,391 | **HTML**
```
<body>
<div class="wordsmith">
<p>WORDSMITH: dummy text here.</p>
</div>
<div class="menu">
<ul>
<li><a id="wordsmith">The Wordsmith</a></li>
<li><a id="tracksmith">The Tracksmith</a></li>
<li><a id="nerdsmith">The Nerdsmith</a></li>
<li><a id="family">The Family Man</li>
</ul>
</div>
```
**CSS**
```
.menu {
background: rgba(0,0,0,0.6);
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
text-align: center;
}
.wordsmith {
background: rgba(0,0,0,0.6);
max-width: 500px;
margin: 0 auto;
padding: 15px;
display: none;
}
.menu #wordsmith:hover ~ .wordsmith {
display: block;
}
```
I have a menu centered in the middle of the page with text links in an UL. What I'm trying to achieve is on hovering over one of the menu items, a div with information will appear up top. The original solution to this I found [here](http://jsfiddle.net/gaby/n5fzB/2/) (JS Fiddle). If I try to achieve this outside of a div and UL, everything works. As soon as I put the menu items in a div OR an UL, the CSS breaks. Am I calling the CSS selector correctly with the ".menu #wordsmith" part? Any help is appreciated! Keep in mind, I'm trying to do this strictly with CSS and html, not JS. Thanks. | 2014/12/25 | [
"https://Stackoverflow.com/questions/27648391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2525633/"
] | AFAIK the are no predecessor or ancestor combinators/selectors so this is not possible in CSS. [`~`](http://www.w3.org/TR/css3-selectors/#general-sibling-combinators) is the general sibling combinator and `#wordsmith` and `.wordsmith` are not siblings, `.wordsmith` is a predecessor of an ancestor of `#wordsmith`.
If you really need to do this you'll have to use JavaScript or re-factor your HTML. | Musa is right, you can't target `#wordsmith` and do something with another element that isn't a sibling or child. But you can do something else. (disclaimer: I don't love using `absolute` positioning and I treat it as a last result) But if this *has* to be done with CSS only...you could put the text inside the `li` and use `position:absolute` to display it above like you wanted. Check out the fiddle below to see what I mean:
HTML
```
<div class="menu">
<ul>
<li>
<a id="wordsmith">The Wordsmith</a>
<p>WORDSMITH: dummy text here.</p>
</li>
<li>
<a id="tracksmith">The Tracksmith</a>
<p>TRACKSMITH: dummy text here.</p>
</li>
<li>
<a id="nerdsmith">The Nerdsmith</a>
<p>NERDSMITH: dummy text here.</p>
</li>
<li>
<a id="family">The Family Man</a>
<p>FAMILY: dummy text here.</p>
</li>
</ul>
</div>
```
CSS
```
.menu {
background: rgba(0,0,0,0.6);
margin: auto;
position: absolute;
top: 100px; left: 0; bottom: 0; right: 0;
text-align: center;
padding: 100px 0 0;
}
.wordsmith {
background: rgba(0,0,0,0.6);
max-width: 500px;
margin: 0 auto;
padding: 15px;
}
.menu ul{
position: relative;
}
.menu li p{
display: none;
position: absolute;
top: -100px;
left: 0;
right: 0;
}
.menu li a:hover + p{
display: block;
}
```
[FIDDLE](http://jsfiddle.net/b54osvqq/1/) |
1,504,459 | I need to find the screen resolution of a users screen who visits my website? | 2009/10/01 | [
"https://Stackoverflow.com/questions/1504459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] | Use JavaScript (`screen.width` and `screen.height` IIRC, but I may be wrong, haven't done JS in a while). PHP cannot do it. | The quick answer is no, then you are probably asking why can't I do that with php. OK here is a longer answer. PHP is a serverside scripting language and therefor has nothing to do with the type of a specific client. Then you might ask "why can I then get the browser agent from php?", thats because that information is sent with the initial HTTP headers upon request to the server. So if you want client information that's not sent with the HTTP header you must you a client scripting language like javascript. |
1,504,459 | I need to find the screen resolution of a users screen who visits my website? | 2009/10/01 | [
"https://Stackoverflow.com/questions/1504459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] | I don't think you can detect the screen size purely with PHP but you can detect the user-agent..
```
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<link rel="stylesheet" href="/css/mobile.css" />'
}
?>
```
Here's a link to a more detailed script: [PHP Mobile Detect](https://gist.github.com/dcondrey/11342487) | The quick answer is no, then you are probably asking why can't I do that with php. OK here is a longer answer. PHP is a serverside scripting language and therefor has nothing to do with the type of a specific client. Then you might ask "why can I then get the browser agent from php?", thats because that information is sent with the initial HTTP headers upon request to the server. So if you want client information that's not sent with the HTTP header you must you a client scripting language like javascript. |
1,504,459 | I need to find the screen resolution of a users screen who visits my website? | 2009/10/01 | [
"https://Stackoverflow.com/questions/1504459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] | I found using CSS inside my html inside my php did the trick for me.
```
<?php
echo '<h2 media="screen and (max-width: 480px)">';
echo 'My headline';
echo '</h2>';
echo '<h1 media="screen and (min-width: 481px)">';
echo 'My headline';
echo '</h1>';
?>
```
This will output a smaller sized headline if the screen is 480px or less.
So no need to pass any vars using JS or similar. | PHP works only on server side, not on user host. Use JavaScript or jQuery to get this info and send via AJAX or URL (?x=1024&y=640). |
1,504,459 | I need to find the screen resolution of a users screen who visits my website? | 2009/10/01 | [
"https://Stackoverflow.com/questions/1504459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] | Directly with PHP is not possible but...
I write this simple code to save screen resolution on a PHP session to use on an image gallery.
```
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
} else if(isset($_REQUEST['width']) AND isset($_REQUEST['height'])) {
$_SESSION['screen_width'] = $_REQUEST['width'];
$_SESSION['screen_height'] = $_REQUEST['height'];
header('Location: ' . $_SERVER['PHP_SELF']);
} else {
echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}
?>
```
**New Solution If you need to send another parameter in Get Method** (by Guddu Modok)
```
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
print_r($_GET);
} else if(isset($_GET['width']) AND isset($_GET['height'])) {
$_SESSION['screen_width'] = $_GET['width'];
$_SESSION['screen_height'] = $_GET['height'];
$x=$_SERVER["REQUEST_URI"];
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['width']);
unset($params['height']);
$string = http_build_query($params);
$domain=$_SERVER['PHP_SELF']."?".$string;
header('Location: ' . $domain);
} else {
$x=$_SERVER["REQUEST_URI"];
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['width']);
unset($params['height']);
$string = http_build_query($params);
$domain=$_SERVER['PHP_SELF']."?".$string;
echo '<script type="text/javascript">window.location = "' . $domain . '&width="+screen.width+"&height="+screen.height;</script>';
}
?>
``` | I don't think you can detect the screen size purely with PHP but you can detect the user-agent..
```
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<link rel="stylesheet" href="/css/mobile.css" />'
}
?>
```
Here's a link to a more detailed script: [PHP Mobile Detect](https://gist.github.com/dcondrey/11342487) |
1,504,459 | I need to find the screen resolution of a users screen who visits my website? | 2009/10/01 | [
"https://Stackoverflow.com/questions/1504459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] | I found using CSS inside my html inside my php did the trick for me.
```
<?php
echo '<h2 media="screen and (max-width: 480px)">';
echo 'My headline';
echo '</h2>';
echo '<h1 media="screen and (min-width: 481px)">';
echo 'My headline';
echo '</h1>';
?>
```
This will output a smaller sized headline if the screen is 480px or less.
So no need to pass any vars using JS or similar. | In PHP there is no standard way to get this information. However, it is possible if you are using a 3rd party solution. 51Degrees device detector for PHP has the properties you need:
* [$\_51d['ScreenPixelsHeight']](https://51degrees.com/Resources/Property-Dictionary#ScreenPixelsHeight)
* [$\_51d['ScreenPixelsWidth']](https://51degrees.com/Resources/Property-Dictionary#ScreenPixelsWidth)
Gives you Width and Height of user's screen in pixels. In order to use these properties you need to download the detector from [sourceforge](http://sourceforge.net/projects/fiftyone/). Then you need to include the following 2 lines in your file/files where it's necessary to detect screen height and width:
```
<?php
require_once 'path/to/core/51Degrees.php';
require_once 'path/to/core/51Degrees_usage.php';
?>
```
Where path/to/core is path to 'Core' directory which you downloaded from sourceforge. Finally, to use the properties:
```
<?php
echo $_51d['ScreenPixelsHeight']; //Output screen height.
echo $_51d['ScreenPixelsWidth']; //Output screen width.
?>
```
Keep in mind these variables can contain 'Unknown' value some times, when the device could not be identified. |
1,504,459 | I need to find the screen resolution of a users screen who visits my website? | 2009/10/01 | [
"https://Stackoverflow.com/questions/1504459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] | This is a very simple process. Yes, you cannot get the width and height in PHP. It is true that JQuery can provide the screen's width and height. First go to <https://github.com/carhartl/jquery-cookie> and get jquery.cookie.js. Here is example using php to get the screen width and height:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script type=text/javascript>
function setScreenHWCookie() {
$.cookie('sw',screen.width);
$.cookie('sh',screen.height);
return true;
}
setScreenHWCookie();
</script>
</head>
<body>
<h1>Using jquery.cookie.js to store screen height and width</h1>
<?php
if(isset($_COOKIE['sw'])) { echo "Screen width: ".$_COOKIE['sw']."<br/>";}
if(isset($_COOKIE['sh'])) { echo "Screen height: ".$_COOKIE['sh']."<br/>";}
?>
</body>
</html>
```
I have a test that you can execute: <http://rw-wrd.net/test.php> | For get the width screen or the height screen
1- Create a PHP file (getwidthscreen.php) and write the following commands in it
**PHP (getwidthscreen.php)**
```php
<div id="widthscreenid"></div>
<script>
document.getElementById("widthscreenid").innerHTML=screen.width;
</script>
```
2- Get the width screen through a cURL session by the following commands
**PHP (main.php)**
```php
$ch = curl_init( 'http://hostname/getwidthscreen.php' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec( $ch );
print_r($result);
curl_close( $ch );
``` |
1,504,459 | I need to find the screen resolution of a users screen who visits my website? | 2009/10/01 | [
"https://Stackoverflow.com/questions/1504459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] | PHP is a server side language - it's executed on the server only, and the resultant program output is sent to the client. As such, there's no "client screen" information available.
That said, you can have the client tell you what their screen resolution is via JavaScript. Write a small scriptlet to send you screen.width and screen.height - possibly via AJAX, or more likely with an initial "jump page" that finds it, then redirects to <http://example.net/index.php?size=AxB>
Though speaking as a user, I'd much prefer you to design a site to fluidly handle any screen resolution. I browse in different sized windows, mostly not maximized. | Here is the Javascript Code: (index.php)
```
<script>
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/sqldb.php", true);
xhttp.send("screensize=",screen.width,screen.height);
</script>
```
Here is the PHP Code: (sqldb.php)
```
$data = $_POST['screensize'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$statement = $pdo->prepare("UPDATE users SET screen= :screen WHERE id = $userid");
$statement->execute(array('screen' => $data));
```
I hope that you know how to get the $userid from the Session,
and for that you need an Database with the Table called users, and an Table inside users called screen ;=)
Regards KSP |
1,504,459 | I need to find the screen resolution of a users screen who visits my website? | 2009/10/01 | [
"https://Stackoverflow.com/questions/1504459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] | I don't think you can detect the screen size purely with PHP but you can detect the user-agent..
```
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<link rel="stylesheet" href="/css/mobile.css" />'
}
?>
```
Here's a link to a more detailed script: [PHP Mobile Detect](https://gist.github.com/dcondrey/11342487) | ```
<script type="text/javascript">
if(screen.width <= 699){
<?php $screen = 'mobile';?>
}else{
<?php $screen = 'default';?>
}
</script>
<?php echo $screen; ?>
``` |
1,504,459 | I need to find the screen resolution of a users screen who visits my website? | 2009/10/01 | [
"https://Stackoverflow.com/questions/1504459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] | You can check it like below:
```
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
echo "mobile web browser!";
} else {
echo "web browser!";
}
``` | PHP works only on server side, not on user host. Use JavaScript or jQuery to get this info and send via AJAX or URL (?x=1024&y=640). |
1,504,459 | I need to find the screen resolution of a users screen who visits my website? | 2009/10/01 | [
"https://Stackoverflow.com/questions/1504459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] | This is a very simple process. Yes, you cannot get the width and height in PHP. It is true that JQuery can provide the screen's width and height. First go to <https://github.com/carhartl/jquery-cookie> and get jquery.cookie.js. Here is example using php to get the screen width and height:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script type=text/javascript>
function setScreenHWCookie() {
$.cookie('sw',screen.width);
$.cookie('sh',screen.height);
return true;
}
setScreenHWCookie();
</script>
</head>
<body>
<h1>Using jquery.cookie.js to store screen height and width</h1>
<?php
if(isset($_COOKIE['sw'])) { echo "Screen width: ".$_COOKIE['sw']."<br/>";}
if(isset($_COOKIE['sh'])) { echo "Screen height: ".$_COOKIE['sh']."<br/>";}
?>
</body>
</html>
```
I have a test that you can execute: <http://rw-wrd.net/test.php> | You can try RESS (RESponsive design + Server side components), see this tutorial:
<http://www.lukew.com/ff/entry.asp?1392> |
58,607 | As you can see in the picture, I'm selecting the "Ads" object, it is at the top of the screen, but the position is (0,-82).
If I change by manual, mean I change -82 to 0, the "Ads"object will move down by 82 pixel, which is wrong.
How I can set my position number to normal ( which is 0,0)?
Thank you fro your help
[](https://i.stack.imgur.com/joDcq.png) | 2015/08/25 | [
"https://graphicdesign.stackexchange.com/questions/58607",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/48878/"
] | What you're seeing is actually correct. In software like Sketch, Photoshop, and Illustrator (0,0) is considered to be the top left corner of your canvas or artboard, and anything positioned above or to the left of that goes into negative values.
If you turn on your rulers (View > Canvas > Show Rulers) it might make more sense. | It seems that it is a bug in Sketch, try to reload it.
Positions of shapes inside artboards are calculated from top left corner of the artboard not canvas.
Also, there is a good practice to start your design workflow from positioning your first artboard at (0, 0). |
58,607 | As you can see in the picture, I'm selecting the "Ads" object, it is at the top of the screen, but the position is (0,-82).
If I change by manual, mean I change -82 to 0, the "Ads"object will move down by 82 pixel, which is wrong.
How I can set my position number to normal ( which is 0,0)?
Thank you fro your help
[](https://i.stack.imgur.com/joDcq.png) | 2015/08/25 | [
"https://graphicdesign.stackexchange.com/questions/58607",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/48878/"
] | What you're seeing is actually correct. In software like Sketch, Photoshop, and Illustrator (0,0) is considered to be the top left corner of your canvas or artboard, and anything positioned above or to the left of that goes into negative values.
If you turn on your rulers (View > Canvas > Show Rulers) it might make more sense. | I think what's causing this is that you've accidentally changed the ruler's point of origin. (I find that this happens quite easily when adding smart guides.) To solve this, turn on your rulers, as suggested above, (View > Canvas > Show Rulers) and double-click the empty square in the top left corner of the canvas. (See image.)[](https://i.stack.imgur.com/SbPuI.png) |
58,607 | As you can see in the picture, I'm selecting the "Ads" object, it is at the top of the screen, but the position is (0,-82).
If I change by manual, mean I change -82 to 0, the "Ads"object will move down by 82 pixel, which is wrong.
How I can set my position number to normal ( which is 0,0)?
Thank you fro your help
[](https://i.stack.imgur.com/joDcq.png) | 2015/08/25 | [
"https://graphicdesign.stackexchange.com/questions/58607",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/48878/"
] | I think what's causing this is that you've accidentally changed the ruler's point of origin. (I find that this happens quite easily when adding smart guides.) To solve this, turn on your rulers, as suggested above, (View > Canvas > Show Rulers) and double-click the empty square in the top left corner of the canvas. (See image.)[](https://i.stack.imgur.com/SbPuI.png) | It seems that it is a bug in Sketch, try to reload it.
Positions of shapes inside artboards are calculated from top left corner of the artboard not canvas.
Also, there is a good practice to start your design workflow from positioning your first artboard at (0, 0). |
35,893,550 | im trying to get a function to find the max item in a sequence using recursion but I keep getting an error,like when i try
Max(range(100)):
```
TypeError: unorderable types: int() > list()
```
Im a programming newbie btw so any help is much appreciated.
```
def Max(s)
if len(s) == 1:
return s[0]
else:
m = Max(s[1:])
if m > s:
return m
else:
return s[0]
``` | 2016/03/09 | [
"https://Stackoverflow.com/questions/35893550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3975231/"
] | You seem to forget to put the index:
```
def Max(s):
if len(s) == 1:
return s[0]
else:
m = Max(s[1:])
if m > s[0]: #put index 0 here
return m
else:
return s[0]
```
`m` is a single number, therefore it cannot be compared with `s` which is a `list`. Thus you got your error.
Side note, consider of using ternary operation `[true_val if true_cond else false_val]` to simplify your notation. Also you do not need the last `else` block since your `if` clause has definite `return` before leaving the block:
```
def Max(s):
if len(s) == 1:
return s[0]
m = Max(s[1:])
return m if m > s[0] else s[0] #put index 0 here
```
Then your code will become a lot simpler. | This variant will reduce the stack size by slicing the problem in half at each level of the recursion, and recursively solving for both halves. This allows you to evaluate lists with thousands of elements, where the approach of reducing the problem size by one would cause stack overflows.
```
def Max(lst):
l = len(lst)
if l > 1:
mid = l / 2
m1 = Max(lst[:mid]) # find max of first half of the list
m2 = Max(lst[mid:]) # find max of second half of the list
# max of the list is the larger of these two values
return m1 if m1 > m2 else m2
return lst[0]
``` |
71,044,718 | I am new to Blazor and trying to show File Saveas Dialog as shown in following link on a button click.
[Save as Image](https://i.stack.imgur.com/OWOJo.png)
The requirement is - **upon clicking the Saveas button above Saveas dialog should be popped up where user can choose the destination of file and file name**.
I have tried "enabling the setting to check the save location in the download settings of the browser" and it works. **But we do not want to depend on the Browser settings.**
Please add your thoughts on below..
1. **Instead of depending on the browser settings is there any other way to show Saveas dialog?**
2. **Are there any open source Nuget packages available to help on this?**
**NOTE: I am using .NET 6.0 for building my application**
Thanks in advance,
Bhargavi Gowri. | 2022/02/09 | [
"https://Stackoverflow.com/questions/71044718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15831663/"
] | Yes, it's called `flexible array member`. It's usually used with dynamically allocated objects. However, you cannot return `Minefield` by value. The compiler will copy only `sizeof(Minefield)` data what is the size of object if length of array `Minefield::field` was `0`.
You can do:
```
Minefield* NewGame(int columns, int rows, int mines)
{
Cell cells[columns*rows];
...
// allocate memory for Minefield and cells array just after it
Minefield* minefield = malloc(sizeof(*minefield) + sizeof cells);
if (!minefield) { ... error handling ... }
// set normal fields using compund literal
*minefield = (Minefield){columns, rows, mines};
// copy cells `array` to `minefield->field` array
memcpy(minefield->field, cells, sizeof cells);
return minefield;
}
```
The `memcpy` can be avoided by first allocating `Minefield` and writing directly to `field` member.
```
Minefield* NewGame(int columns, int rows, int mines)
{
Minefield* minefield = malloc(sizeof(Minefield) + rows * columns * sizeof(Cell));
if (!minefield) { ... error handling ... }
*minefield = (Minefield){columns, rows, mines};
Cell *cells = minefield->field;
...
return minefield;
}
``` | Unfortunately, C doesn't have any built-in dynamic array like python. However, if you want to use some dynamic array either you can implement your self or you can see the answer to that link [C dynamically growing array](https://stackoverflow.com/questions/3536153/c-dynamically-growing-array) which explains that you need to have starting array with a default size, and then you can increase the size of the array which depends on your algorithm. After you import that header file provided by @casablance, you can simply use it for your minesweeper game. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.