qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
25,457,631 |
Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image.
But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image.
And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why.

Do you know how can I have an effect like this my image below?

**I forget to create a fiddle with my issue:** <http://jsfiddle.net/ejjtepfo/2/>
**My Html:**
```
<div class="modal">
<h2>Title of news</h2>
<span id="data">20/10/2014</span><br />
<img class="img" src=""/>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
<div class="clear_p"></div>
<div id="pdfs">
<h3>Links</h3>
<ul class="links">
<li> <a href=""></a>Link 1</li>
<li> <a href=""></a>Link 2</li>http://jsfiddle.net/#tidy
<li> <a href=""></a>Link 3</li>
</ul>
</div>
</div>
```
|
2014/08/23
|
['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']
|
Just add **float:right; position:relative** for your paragraph and adjust the width of paragraph if it is positioning below the image.
|
Add a div for your image in html file and add this in your css
```
#image{
width:210px;
height:1000px;
float:left;
}
```
|
25,457,631 |
Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image.
But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image.
And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why.

Do you know how can I have an effect like this my image below?

**I forget to create a fiddle with my issue:** <http://jsfiddle.net/ejjtepfo/2/>
**My Html:**
```
<div class="modal">
<h2>Title of news</h2>
<span id="data">20/10/2014</span><br />
<img class="img" src=""/>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
<div class="clear_p"></div>
<div id="pdfs">
<h3>Links</h3>
<ul class="links">
<li> <a href=""></a>Link 1</li>
<li> <a href=""></a>Link 2</li>http://jsfiddle.net/#tidy
<li> <a href=""></a>Link 3</li>
</ul>
</div>
</div>
```
|
2014/08/23
|
['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']
|
You could wrap the paragraph in a div tag:
```
<img src="http://www.peacethroughpie.org/wp-content/uploads/2013/09/baked-pie.jpg">
<div><p> ... </p></div>
```
Then you could set the div to a width of 100% - width of image and float it to the right.
```
img {
float: left;
width: 20%;
}
div {
display: block;
width: 80%;
float: right;
}
```
It would look like this:
<http://imgur.com/zL5v33z>
|
Add a div for your image in html file and add this in your css
```
#image{
width:210px;
height:1000px;
float:left;
}
```
|
1,860,155 |
If the name is like "david" it comes within the allotted space....
but if the name is like "john pal abraham desouza" the allotted space increases automatically..
So i need to have the name occupied in the allotted space by auto resizing the font..
Suggest me a solution..
|
2009/12/07
|
['https://Stackoverflow.com/questions/1860155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174796/']
|
It sounds to me like what you want to do is roll your own Custom .NET Membership Provider.
It will allow you to use the built-in ASP.NET Authentication/Authorization attributes on your Controller Actions while giving you complete control over the implementation inside the provider (which will allow you to code it to meet the requirements stated above).
Direct from MSDN...
[Implementing a Membership Provider](http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx)
|
If you go ahead and create your own custom solution, you will have a better idea of how difficult it is and what features you want. This will help you to evaluate off-the-shelf solutions for future projects.
OTOH, spending time developing functionality that is already readily available means you won't be spending that time working on the major functionality of your project. Unless authentication and authorization are a major component of your project, you might consider investing your time, and expanding your knowledge, in another area.
|
1,860,155 |
If the name is like "david" it comes within the allotted space....
but if the name is like "john pal abraham desouza" the allotted space increases automatically..
So i need to have the name occupied in the allotted space by auto resizing the font..
Suggest me a solution..
|
2009/12/07
|
['https://Stackoverflow.com/questions/1860155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174796/']
|
It sounds to me like what you want to do is roll your own Custom .NET Membership Provider.
It will allow you to use the built-in ASP.NET Authentication/Authorization attributes on your Controller Actions while giving you complete control over the implementation inside the provider (which will allow you to code it to meet the requirements stated above).
Direct from MSDN...
[Implementing a Membership Provider](http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx)
|
I think you recognize where the thin parts in your consideration are: namely in that you've included how to do what you're doing as motive in why you're doing it and the NIH (funny: I'd never seen that before) issue.
Putting those aside, your provider is something that you could potentially reuse and it may simplify some of your future efforts. It should also serve to familiarize you further with the issue. As long as you understand the ASP.NET framework so you can work with it too if you need to (and aren't specialized such that you don't know what you're doing if you're not using your tool) then I believe you've already crafted your defense.
As DOK mentioned, be cautious that you're not rolling your own here to avoid a larger task at hand in whatever your other functionality is. Don't let this be a distraction: it should be something your application really needs. If it's not, then I'd lean towards focusing on your software's core mission instead.
|
1,860,155 |
If the name is like "david" it comes within the allotted space....
but if the name is like "john pal abraham desouza" the allotted space increases automatically..
So i need to have the name occupied in the allotted space by auto resizing the font..
Suggest me a solution..
|
2009/12/07
|
['https://Stackoverflow.com/questions/1860155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174796/']
|
It sounds to me like what you want to do is roll your own Custom .NET Membership Provider.
It will allow you to use the built-in ASP.NET Authentication/Authorization attributes on your Controller Actions while giving you complete control over the implementation inside the provider (which will allow you to code it to meet the requirements stated above).
Direct from MSDN...
[Implementing a Membership Provider](http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx)
|
I too am working on a pet Project using ASP.net MVC and db4o and did the same thing, so you're at least not alone in going down that route :). One of the biggest reasons for me to start playing around with db4o as persistence layer is that especially authorization on field level (i.e I'm allowed to see Person A's first name but not Person B's first name) is though to achieve if you're forced into complex SQL statements and an anemic domain model.
Since I had complex authorization needs that needed to be persisted (and synchronized) in both db4o and Solr indexes I started working on rolling out my own, but only because I knew up front it was one of the key features of my pet project that I wanted 100% control over.
Now I might still use the .Net Membership provider for authentication but not (solely) for authorization of objects but only after i POC'd my authorization needs using my own.
|
2,568,467 |
In our organization, we are still on .net 1.1 environment, using javascript, a few open source applications/widgets. Development is done using Visual Studio 2003, grid view, and iframes. Our application works in Internet Explorer 7 and IE 8 (in compatibilily mode). Can anyone give any basic steps we can take to get our application to work cross browsers? What are the starting locations we can get at to start making existing code work in different browsers?
|
2010/04/02
|
['https://Stackoverflow.com/questions/2568467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
Use jQuery for reliable cross browser JavaScript
Was it VS 2k or VS 2k3 that "helped" the developer by rewriting their HTML (in all CAPS no less)?
|
Make your HTML markup standards compliant. I find that developing my website following W3C standards ensure that my sites work in all major browsers.
I also develop in Firefox and then fix IE using conditional stylesheets.
The .NET version does not matter on browser compatibility.
|
2,568,467 |
In our organization, we are still on .net 1.1 environment, using javascript, a few open source applications/widgets. Development is done using Visual Studio 2003, grid view, and iframes. Our application works in Internet Explorer 7 and IE 8 (in compatibilily mode). Can anyone give any basic steps we can take to get our application to work cross browsers? What are the starting locations we can get at to start making existing code work in different browsers?
|
2010/04/02
|
['https://Stackoverflow.com/questions/2568467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
Use jQuery for reliable cross browser JavaScript
Was it VS 2k or VS 2k3 that "helped" the developer by rewriting their HTML (in all CAPS no less)?
|
.Net in its 2.0 iteration got *a lot* better (compared to 1.1) at producing cross-browser, and certainly *more* standards-compliant code (although not perfect by any means).
If you can upgrade to 2.0 this will get you a lot of progress on the standards compliance front for free (unless your own controls / html render as non-cross-browser html and/or javascript; then that would be the first main problem to tackle).
In .Net 2.0 don't forget to appropriately set the `xhtmlconformance` [attribute](http://msdn.microsoft.com/en-us/library/ms228268.aspx) in your `web.config` (if you're for example aiming for xhtml). This globally affects the produced html your controls produce.
|
2,568,467 |
In our organization, we are still on .net 1.1 environment, using javascript, a few open source applications/widgets. Development is done using Visual Studio 2003, grid view, and iframes. Our application works in Internet Explorer 7 and IE 8 (in compatibilily mode). Can anyone give any basic steps we can take to get our application to work cross browsers? What are the starting locations we can get at to start making existing code work in different browsers?
|
2010/04/02
|
['https://Stackoverflow.com/questions/2568467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
Use jQuery for reliable cross browser JavaScript
Was it VS 2k or VS 2k3 that "helped" the developer by rewriting their HTML (in all CAPS no less)?
|
1. Install and Run Firefox (and get the Firebug addon).
2. Enter your application and open the Firebug console (F12) to see what issues your application is encountering. (in the Console Tab)
3. Start with the Errors.
1. Change any JavaScript that is doing things like *document.all.xxxx* to use **document.getElementById()** or **document.forms['name'].elements['name']** etc.
2. Change any CSS that is using IE only styles. e.g. "*cursor:hand*" should be "**cursor:pointer**" etc.
4. Repeat for Warnings once all the Errors are gone
5. If your app was running in Quirks mode, consider adding a doctype so that you can render in Standards mode (makes CSS/JS much more compliant)... however note that this will very likely "screw up" your pages for a bit until you iron out the kinks.
6. In the future, be sure to test in all major browsers. I'd recommend developing in Firefox or Chrome first, then tweaking if needed for IE.
|
2,568,467 |
In our organization, we are still on .net 1.1 environment, using javascript, a few open source applications/widgets. Development is done using Visual Studio 2003, grid view, and iframes. Our application works in Internet Explorer 7 and IE 8 (in compatibilily mode). Can anyone give any basic steps we can take to get our application to work cross browsers? What are the starting locations we can get at to start making existing code work in different browsers?
|
2010/04/02
|
['https://Stackoverflow.com/questions/2568467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
Make your HTML markup standards compliant. I find that developing my website following W3C standards ensure that my sites work in all major browsers.
I also develop in Firefox and then fix IE using conditional stylesheets.
The .NET version does not matter on browser compatibility.
|
.Net in its 2.0 iteration got *a lot* better (compared to 1.1) at producing cross-browser, and certainly *more* standards-compliant code (although not perfect by any means).
If you can upgrade to 2.0 this will get you a lot of progress on the standards compliance front for free (unless your own controls / html render as non-cross-browser html and/or javascript; then that would be the first main problem to tackle).
In .Net 2.0 don't forget to appropriately set the `xhtmlconformance` [attribute](http://msdn.microsoft.com/en-us/library/ms228268.aspx) in your `web.config` (if you're for example aiming for xhtml). This globally affects the produced html your controls produce.
|
2,568,467 |
In our organization, we are still on .net 1.1 environment, using javascript, a few open source applications/widgets. Development is done using Visual Studio 2003, grid view, and iframes. Our application works in Internet Explorer 7 and IE 8 (in compatibilily mode). Can anyone give any basic steps we can take to get our application to work cross browsers? What are the starting locations we can get at to start making existing code work in different browsers?
|
2010/04/02
|
['https://Stackoverflow.com/questions/2568467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
1. Install and Run Firefox (and get the Firebug addon).
2. Enter your application and open the Firebug console (F12) to see what issues your application is encountering. (in the Console Tab)
3. Start with the Errors.
1. Change any JavaScript that is doing things like *document.all.xxxx* to use **document.getElementById()** or **document.forms['name'].elements['name']** etc.
2. Change any CSS that is using IE only styles. e.g. "*cursor:hand*" should be "**cursor:pointer**" etc.
4. Repeat for Warnings once all the Errors are gone
5. If your app was running in Quirks mode, consider adding a doctype so that you can render in Standards mode (makes CSS/JS much more compliant)... however note that this will very likely "screw up" your pages for a bit until you iron out the kinks.
6. In the future, be sure to test in all major browsers. I'd recommend developing in Firefox or Chrome first, then tweaking if needed for IE.
|
.Net in its 2.0 iteration got *a lot* better (compared to 1.1) at producing cross-browser, and certainly *more* standards-compliant code (although not perfect by any means).
If you can upgrade to 2.0 this will get you a lot of progress on the standards compliance front for free (unless your own controls / html render as non-cross-browser html and/or javascript; then that would be the first main problem to tackle).
In .Net 2.0 don't forget to appropriately set the `xhtmlconformance` [attribute](http://msdn.microsoft.com/en-us/library/ms228268.aspx) in your `web.config` (if you're for example aiming for xhtml). This globally affects the produced html your controls produce.
|
9,699,529 |
In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form.
Data expected to be big in the database and records are spread over several tables in a very normalized fashion.
Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries?
Thank you
|
2012/03/14
|
['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']
|
The purpose of `final` but non-`static` variables is to have an object-wide constant. It should be initialized in the constructor:
```
class Passenger {
final int b;
Passenger(int b) {
this.b = b;
}
}
```
If you are always assigning a constant literal value (`0`) to the `final` variable, it doesn't make much sense. Using `static` is preferred so that you are only having a single copy of `b`:
```
static final int b = 0;
```
BTW I don't think having default access modifier was your intention.
|
If you have multiple instances of `Passenger` class, I would go for making it static. While this has little benefit when talking about an `int` variable, this could save some memory if you have complex objects. This is because a static variable belongs to a class, not to an instance, thus memory space for it will be reserved only once, and it will be referred by the class object itself, not by the instances. Of course, you should be aware that having `b` as a static variable means that the changes made on this variable will be reflected on all the classes that access this variable, but since you made it `final` this won't be the case.
Note also that with the code you've written, classes in the same package as `Passenger` will be able to read the `b` value by accessing it via `Passenger.b` (if static).
|
9,699,529 |
In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form.
Data expected to be big in the database and records are spread over several tables in a very normalized fashion.
Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries?
Thank you
|
2012/03/14
|
['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']
|
If you have multiple instances of `Passenger` class, I would go for making it static. While this has little benefit when talking about an `int` variable, this could save some memory if you have complex objects. This is because a static variable belongs to a class, not to an instance, thus memory space for it will be reserved only once, and it will be referred by the class object itself, not by the instances. Of course, you should be aware that having `b` as a static variable means that the changes made on this variable will be reflected on all the classes that access this variable, but since you made it `final` this won't be the case.
Note also that with the code you've written, classes in the same package as `Passenger` will be able to read the `b` value by accessing it via `Passenger.b` (if static).
|
A `final` primitive is the same as a `static final` primitive (except more efficient)
A `final` reference to an immutable object the same as a `static final` reference of the same.
A `final` reference to a mutable object is NOT the same as a `static final` reference of the same.
```
final int i = 0;
// same as
static final int = 0;
final String hi = "Hello";
// same as
static final String hi = "Hello";
final List<String> list = new ArrayList<String>();
// is NOT the same as
static final List<String> list = new ArrayList<String>();
```
The only time the last example is the same is when you have a singleton. It is fairly common for singletons to be written with a confusion of static and non static fields and methods as the difference is not obvious. :|
|
9,699,529 |
In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form.
Data expected to be big in the database and records are spread over several tables in a very normalized fashion.
Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries?
Thank you
|
2012/03/14
|
['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']
|
The purpose of `final` but non-`static` variables is to have an object-wide constant. It should be initialized in the constructor:
```
class Passenger {
final int b;
Passenger(int b) {
this.b = b;
}
}
```
If you are always assigning a constant literal value (`0`) to the `final` variable, it doesn't make much sense. Using `static` is preferred so that you are only having a single copy of `b`:
```
static final int b = 0;
```
BTW I don't think having default access modifier was your intention.
|
A `final` primitive is the same as a `static final` primitive (except more efficient)
A `final` reference to an immutable object the same as a `static final` reference of the same.
A `final` reference to a mutable object is NOT the same as a `static final` reference of the same.
```
final int i = 0;
// same as
static final int = 0;
final String hi = "Hello";
// same as
static final String hi = "Hello";
final List<String> list = new ArrayList<String>();
// is NOT the same as
static final List<String> list = new ArrayList<String>();
```
The only time the last example is the same is when you have a singleton. It is fairly common for singletons to be written with a confusion of static and non static fields and methods as the difference is not obvious. :|
|
9,699,529 |
In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form.
Data expected to be big in the database and records are spread over several tables in a very normalized fashion.
Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries?
Thank you
|
2012/03/14
|
['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']
|
It depends on the purpose of b. Usually constants are there for a specific purpose. If you make it static you could accidentally change it in some instance of that class and that will affect all the others.
|
In java, the `static` attribute basically means: **associated with the type itself, rather than an instance of the type**.
In other words you can reference a static variable without creating instances of that type... Whereas in the case of just using `final` you'd need to instantiate the class.
So, yes, to answer your question, I'd say that you're right. :)
|
9,699,529 |
In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form.
Data expected to be big in the database and records are spread over several tables in a very normalized fashion.
Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries?
Thank you
|
2012/03/14
|
['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']
|
The purpose of `final` but non-`static` variables is to have an object-wide constant. It should be initialized in the constructor:
```
class Passenger {
final int b;
Passenger(int b) {
this.b = b;
}
}
```
If you are always assigning a constant literal value (`0`) to the `final` variable, it doesn't make much sense. Using `static` is preferred so that you are only having a single copy of `b`:
```
static final int b = 0;
```
BTW I don't think having default access modifier was your intention.
|
In java, the `static` attribute basically means: **associated with the type itself, rather than an instance of the type**.
In other words you can reference a static variable without creating instances of that type... Whereas in the case of just using `final` you'd need to instantiate the class.
So, yes, to answer your question, I'd say that you're right. :)
|
9,699,529 |
In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form.
Data expected to be big in the database and records are spread over several tables in a very normalized fashion.
Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries?
Thank you
|
2012/03/14
|
['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']
|
It depends on the purpose of b. Usually constants are there for a specific purpose. If you make it static you could accidentally change it in some instance of that class and that will affect all the others.
|
A `final` variable is defined when you need a constant, so you can assign a value just once.
Using `static`, instead, you are defining a variable shared by all the objects of that type (like a global variable) and it is not associated with a certain object itself.
|
9,699,529 |
In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form.
Data expected to be big in the database and records are spread over several tables in a very normalized fashion.
Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries?
Thank you
|
2012/03/14
|
['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']
|
The purpose of `final` but non-`static` variables is to have an object-wide constant. It should be initialized in the constructor:
```
class Passenger {
final int b;
Passenger(int b) {
this.b = b;
}
}
```
If you are always assigning a constant literal value (`0`) to the `final` variable, it doesn't make much sense. Using `static` is preferred so that you are only having a single copy of `b`:
```
static final int b = 0;
```
BTW I don't think having default access modifier was your intention.
|
It depends on the purpose of b. Usually constants are there for a specific purpose. If you make it static you could accidentally change it in some instance of that class and that will affect all the others.
|
9,699,529 |
In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form.
Data expected to be big in the database and records are spread over several tables in a very normalized fashion.
Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries?
Thank you
|
2012/03/14
|
['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']
|
It depends on the purpose of b. Usually constants are there for a specific purpose. If you make it static you could accidentally change it in some instance of that class and that will affect all the others.
|
A `final` primitive is the same as a `static final` primitive (except more efficient)
A `final` reference to an immutable object the same as a `static final` reference of the same.
A `final` reference to a mutable object is NOT the same as a `static final` reference of the same.
```
final int i = 0;
// same as
static final int = 0;
final String hi = "Hello";
// same as
static final String hi = "Hello";
final List<String> list = new ArrayList<String>();
// is NOT the same as
static final List<String> list = new ArrayList<String>();
```
The only time the last example is the same is when you have a singleton. It is fairly common for singletons to be written with a confusion of static and non static fields and methods as the difference is not obvious. :|
|
9,699,529 |
In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form.
Data expected to be big in the database and records are spread over several tables in a very normalized fashion.
Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries?
Thank you
|
2012/03/14
|
['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']
|
The purpose of `final` but non-`static` variables is to have an object-wide constant. It should be initialized in the constructor:
```
class Passenger {
final int b;
Passenger(int b) {
this.b = b;
}
}
```
If you are always assigning a constant literal value (`0`) to the `final` variable, it doesn't make much sense. Using `static` is preferred so that you are only having a single copy of `b`:
```
static final int b = 0;
```
BTW I don't think having default access modifier was your intention.
|
A `final` variable is defined when you need a constant, so you can assign a value just once.
Using `static`, instead, you are defining a variable shared by all the objects of that type (like a global variable) and it is not associated with a certain object itself.
|
9,699,529 |
In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form.
Data expected to be big in the database and records are spread over several tables in a very normalized fashion.
Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries?
Thank you
|
2012/03/14
|
['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']
|
If you have multiple instances of `Passenger` class, I would go for making it static. While this has little benefit when talking about an `int` variable, this could save some memory if you have complex objects. This is because a static variable belongs to a class, not to an instance, thus memory space for it will be reserved only once, and it will be referred by the class object itself, not by the instances. Of course, you should be aware that having `b` as a static variable means that the changes made on this variable will be reflected on all the classes that access this variable, but since you made it `final` this won't be the case.
Note also that with the code you've written, classes in the same package as `Passenger` will be able to read the `b` value by accessing it via `Passenger.b` (if static).
|
A `final` variable is defined when you need a constant, so you can assign a value just once.
Using `static`, instead, you are defining a variable shared by all the objects of that type (like a global variable) and it is not associated with a certain object itself.
|
64,261,847 |
So I wrote a model that computes results over various parameters via a nested loop. Each computation returns a list of `len(columns) = 10` elements, which is added to a list of lists (`res`).
Say I compute my results for some parameters `len(alpha) = 2`, `len(gamma) = 2`, `rep = 3`, where rep is the number of repetitions that I run. This yields results in the form of a list of lists like this:
```
res = [ [elem_1, ..., elem_10], ..., [elem_1, ..., elem_10] ]
```
I know that `len(res) = len(alpha) * len(gamma) * repetitions = 12` and that each inner list has `len(columns) = 10` elements. I also know that every 3rd list in `res` is going to be a repetition (which I know from the way I set up my nested loops to iterate over all parameter combinations, in fact I am using itertools).
I now want to average the result list of lists. What I need to do is to take every `(len(res) // repetitions) = 4`th list , add them together element-wise, and divide by the number of repetitions (3). Sounded easier than done, for me.
Here is my ugly attempt to do so:
```
# create a list of lists of lists, where the inner list of lists are lists of the runs with the identical parameters alpha and gamma
res = [res[i::(len(res)//rep)] for i in range(len(res)//rep)]
avg_res = []
for i in res:
result = []
for j in (zip(*i)):
result.append(sum(j))
avg_res.append([i/repetitions for i in result])
print(len(result_list), avg_res)
```
This actually yields, what I want, but it surely is not the pythonic way to do it. Ugly as hell and 5 minutes later I can hardly make sense of my own code...
What would be the most pythonic way to do it? Thanks in advance!
|
2020/10/08
|
['https://Stackoverflow.com/questions/64261847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11436649/']
|
In some cases a pythonic code is a matter of style, one of its idioms is using list comprehension instead of loop so writing `result = [sum(j) for j in (zip(*i))]` is simpler than iterating over `zip(*i)`.
On the other hand nested list comprehension looks more complex so **don't** do
```
avg_res = [[i/repetitions for i in [sum(j) for j in (zip(*j))]] for j in res]
```
You can write:
```
res = [res[i::(len(res)//rep)] for i in range(len(res)//rep)]
avg_res = []
for i in res:
result = [sum(j) for j in (zip(*i))]
avg_res.append([i/repetitions for i in result])
print(len(result_list), avg_res)
```
Another idiom in Programming in general (and in python in particular) is naming operations with functions, and variable names, to make the code more **readable**:
```
def sum_columns(list_of_rows):
return [sum(col) for col in (zip(*list_of_rows))]
def align_alpha_and_gamma(res):
return [res[i::(len(res)//rep)] for i in range(len(res)//rep)]
aligned_lists = align_alpha_and_gamma(res)
avg_res = []
for aligned_list in aligned_lists:
sums_of_column= sum_columns(aligned_list)
avg_res.append([sum_of_column/repetitions for sum_of_column in sums_of_column])
print(len(result_list), avg_res)
```
Off course you can choose better names according to what you want to do in the code.
|
It was a bit hard to follow your instructions, but as I caught, you attempt to try sum over all element in N'th list and divide it by repetitions.
```
res = [list(range(i,i+10)) for i in range(10)]
N = 4
repetitions = 3
average_of_Nth_lists = sum([num for iter,item in enumerate(res) for num in item if iter%N==0])/repetitions
print(average_of_Nth_lists)
```
output:
```
85.0
```
explanation for the result: equals to `sum(0-9)+sum(4-13)+sum(8-17) = 255` --> `255/3=85.0`
created `res` as a list of lists, iterate over N'th list (in my case, 1,5,9 you can transform it to 4,8 etc if that what you are wish, find out where in the code or ask for help if you don't get it), sum them up and divide by `repetitions`
|
9,450,204 |
I need create a link to `users/id/microposts` where `id` is the user id. I was wondering how I could do that with `link_to`?
The HTML code is I am using for the moment is :
```
<strong><a href="/users/<%= @user.id %>/microposts">Microposts</a></strong> <%= user.microposts.count %>
```
Which renders the following :
```
<a href="/users/1/microposts">Microposts</a>
```
|
2012/02/26
|
['https://Stackoverflow.com/questions/9450204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146764/']
|
Python uses dictionaries to keep local and global variables in. When looking up a variable reference, it will look into the local dict first. If you want to reference a variable in the global dictionary, put the global keyword in front of it.
Also see answers to [this](https://stackoverflow.com/questions/370357/python-variable-scope-question) question for more elaborate info.
|
I agree with user18044, however, is your confusion about the ’f(f)’? I agree that can be really confusing, especially in a non typed language. The argument to ’f’ is a function handle that has a local type scope with name ’f’. The way python decides which ’f’ gets used is explained by 18044. Python looks at the name ’f’ on the function definition and the local parameter ’f’ takes precidence over the global name ’f’ just like would be done if we had a global variable ’dude’ and a local variable ’dude’ in a function. The local overrides the global. Hopes this helps, and makes sense. :-)
|
9,450,204 |
I need create a link to `users/id/microposts` where `id` is the user id. I was wondering how I could do that with `link_to`?
The HTML code is I am using for the moment is :
```
<strong><a href="/users/<%= @user.id %>/microposts">Microposts</a></strong> <%= user.microposts.count %>
```
Which renders the following :
```
<a href="/users/1/microposts">Microposts</a>
```
|
2012/02/26
|
['https://Stackoverflow.com/questions/9450204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146764/']
|
Python uses dictionaries to keep local and global variables in. When looking up a variable reference, it will look into the local dict first. If you want to reference a variable in the global dictionary, put the global keyword in front of it.
Also see answers to [this](https://stackoverflow.com/questions/370357/python-variable-scope-question) question for more elaborate info.
|
The locals for a function consist of everything that was passed in, and every variable that is assigned to and not explicitly tagged as `global` (or `nonlocal` in 3.x).
The globals consist of everything that can be seen at global scope, including the function itself.
When a name is referenced, it is looked up in the locals first, and then in the globals if not found in the locals.
When the statement `f(g)` is run, the statement itself is at global scope, so there are no locals. `f` and `g` are both found in the globals: they are both functions. The function defined by `def f...` is called, with the function defined by `def g...` being passed as an argument.
When `f(f)` runs, `f` is in the locals for the function. It is bound to the passed-in value, which is the function defined by `def g...`. The body of the function has the statement `f(1)`. `1` is a constant and no lookup is required. `f` is looked up in the locals, and the passed-in function is found. It - being the function known at global scope as `g` - is called.
Thus `g` is, likewise, run with the value `1` bound to the local variable `x`. That is forwarded to the function `print` (in 3.x; in 2.x, `print` is a keyword, so `print x` is a statement), which prints the value `1`.
|
56,877,001 |
As I clarify code, I rename and edit a file *so much* that git doesn't recognize it as a rename.
A fix: commit rename of old file; then, commit the new file.
How can I do this nicely with git, *after* all the editing?
---
`git stash` doesn't recognize the new filename.
Currently I do this:
* move the new file elsewhere
-`git reset oldfile` to get the old file
* rename it
* commit it
* now, get the new file back, overwriting the above
* commit that
I've described that as one file, but usually it's many files, in different directories. I don't know about you, but for me it's so easy to accidently overwrite and lose the new versions... which aren't commited yet, so no `reflog` rescue.
This seems *just* the kind of thing git could help me with...
*EDIT* I could commit it to a temp branch, for `reflog` safety.
|
2019/07/03
|
['https://Stackoverflow.com/questions/56877001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4930344/']
|
Git doesn't provide a really nice way to do this, but this works. Assumptions:
* `foo` is the old name of the file, and the name the modified file still has on disk
* `bar` is the new name you want it to have
* There are no changes staged in the index
Then do:
```
git update-index --add --cacheinfo "$(git ls-files --full-name -s foo \
| awk '{print $1 "," $2 ",bar"}')"
git rm --cached foo
git commit -m "rename foo to bar"
mv foo bar
git add bar
git commit -m "make changes to bar"
```
The `git update-index` tells git to stage a new file in the index with the same hash and mode as the indexed version `foo`, but a new name `bar`. It doesn't consult the disk, it just assumes an object exists with that hash (which it does). The `git rm --cached` tells git to stage a removal of `foo` without touching the disk. Together, they make up a rename, which we can commit. Then we move the file for real, use `git add` to inform git about its new contents, and commit again. Naturally you can also add other changes to this commit.
in between the `git update-index` and the `mv`, `git status` will show an un-staged change of `deleted: bar` because the file exists in the index but not on disk (at least not yet under that name), but this isn't a problem.
Note that the name `bar` has to be a path relative to the root of the repository, even if you're operating from a sub-directory. For simplicity, operate from the repo root and use the full path for both `foo` and `bar`.
None of this is really *simpler* than what you're doing, but it does avoid the need to revert changes from your working tree.
|
I guess it will sound simplistic, but the simplest solution is: When you're editing a file, and have a bunch of pending edits, and you decide the file needs to be renamed,
(1) make a note that you need to rename it
(2) get the file to a state where you can commit the changes you have
(3) commit it
(4) rename it
(5) commit the rename
(6) if necessary, continue editing
That is - if you don't want to commit a rename at the same time as you commit changes to the affected file... then don't.
In a very few cases, there may be a reason to commit a rename with a change. For example, a public class name in Java should match its filename. But that's fine - the rename detection change threshold isn't (by default) 100% match anyway. Small changes will rarely hurt anything. But that's not really the issue, because you've already decided you want to do separate commits.
So the issue is just a little bit of planning ahead. At the moment you're going to rename a significantly edited file (or significantly edit a renamed file), that's the moment to decide "oh, I'll want to separate this next step into a different commit from what I've already done".
If you really can't do that, then stash is actually fine. Stash your edits, rename the file, commit, pop the stash. Yes, the popped file will be at the wrong path, so rename it again (overwriting the original).
By the way, depending on your workflow this may all be for naught. A merge will not look at the individual commits and will see exactly the same situation as if you had done everything in one commit. If you use a rebase-driven workflow you might find that it really does help (though that has other costs). But overall I'd say there are other strategies that do more to reduce this problem - such as making sure divergent branches are short lived so taht any conflict resolution is kept to a minimum even when rename detection is not successful.
|
58,065,328 |
I'm using NuxtJS's auth module and trying to get the Bearer token and a custom cookie that contains a sessionType on nuxtServerInit so I can update the `store` with a `mutation`, but it only works when I reload the page.
If I close the browser and go directly to my app url, I keep getting undefined for auth.\_token.local because `nuxtServerInit` executes before the cookies are ready.
My code in store/index.js looks like this:
```
export const actions = {
async nuxtServerInit({ commit, dispatch }, { req }) {
// Parse cookies with cookie-universal-nuxt
const token = this.$cookies.get('token')
const sessionType = this.$cookies.get('sessionType')
// Check if Cookie user and token exists to set them in 'auth'
if (token && user) {
commit('auth/SET_TOKEN', token)
commit('auth/SET_SESSION_TYPE', user)
}
}
}
```
I'm using nuxt-universal-cookies library.
What's the way to execute the action after the cookies are loaded on the browser?
|
2019/09/23
|
['https://Stackoverflow.com/questions/58065328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7666951/']
|
Having it work with F5 and not by hitting enter makes me suspect that it just works sometimes and sometimes it doesn't, because `F5` and `Enter` should trigger same behaviour on Nuxt (apart from some cache headers).
The only suspicious thing about you code is the usage of an `async` function when the function is not returning or awaiting any promise.
So you either `await` for an `action`
```
export const actions = {
async nuxtServerInit({ commit, dispatch }, { req }) {
// Parse cookies with cookie-universal-nuxt
const token = this.$cookies.get('token')
const sessionType = this.$cookies.get('sessionType')
// Check if Cookie user and token exists to set them in 'auth'
if (token && user) {
await dispatch('SET_SESSION', {token, user})
//commit('auth/SET_TOKEN', token)
//commit('auth/SET_SESSION_TYPE', user)
}
}
}
```
or you remove the async from the declaration
```
export const actions = {
nuxtServerInit({ commit, dispatch }, { req }) {
// Parse cookies with cookie-universal-nuxt
const token = this.$cookies.get('token')
const sessionType = this.$cookies.get('sessionType')
// Check if Cookie user and token exists to set them in 'auth'
if (token && user) {
commit('auth/SET_TOKEN', token)
commit('auth/SET_SESSION_TYPE', user)
}
}
}
```
|
I've had the same issue and found out that `nuxtServerInit` is triggered first before the cookie was set like via a express middleware.
|
140,021 |
How to get number of subsites in a site collection using Powershell?
|
2015/04/29
|
['https://sharepoint.stackexchange.com/questions/140021', 'https://sharepoint.stackexchange.com', 'https://sharepoint.stackexchange.com/users/41443/']
|
or simply:
```
$site = Get-SPSite http://YourSharePointSite
$site.AllWebs.Count
```
|
```
if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"}
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$sites = Get-SPSite <SiteCollectionUrl>
$noOfWebs = 0
foreach ($web in $sites.AllWebs)
{
$noOfWebs++
}
If ($sites -ne $null)
{
$sites.Dispose();
}
If ($web -ne $null)
{
$web.Dispose();
}
Write-Host "Total No of Subsites: " $noOfWebs
```
|
140,021 |
How to get number of subsites in a site collection using Powershell?
|
2015/04/29
|
['https://sharepoint.stackexchange.com/questions/140021', 'https://sharepoint.stackexchange.com', 'https://sharepoint.stackexchange.com/users/41443/']
|
```
if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"}
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$sites = Get-SPSite <SiteCollectionUrl>
$noOfWebs = 0
foreach ($web in $sites.AllWebs)
{
$noOfWebs++
}
If ($sites -ne $null)
{
$sites.Dispose();
}
If ($web -ne $null)
{
$web.Dispose();
}
Write-Host "Total No of Subsites: " $noOfWebs
```
|
Using the following code, within the SharePoint Management Shell, you can get the count of Web Applications in the Farm, Site Collections in Web Application, Sites in Site Collection.
```
Write-Host "Web Applications in Farm"
$WebApplications = Get-SPWebApplication
$WebApplications | Measure-Object | Format-List Count
ForEach($WebApplication in $WebApplications) {
Write-Host "Site Collections in the Web Application named " $WebApplication.Name
$WebApplication.Sites | Measure-Object | Format-List Count
ForEach($SiteCollection in $WebApplication.Sites) {
Write-Host "Webs (Sub-Sites) in the Site Collection with the URL " $SiteCollection.Url
Write-Host "`nCount : " $SiteCollection.AllWebs.Count "`n`n`n"
}
}
```
|
140,021 |
How to get number of subsites in a site collection using Powershell?
|
2015/04/29
|
['https://sharepoint.stackexchange.com/questions/140021', 'https://sharepoint.stackexchange.com', 'https://sharepoint.stackexchange.com/users/41443/']
|
or simply:
```
$site = Get-SPSite http://YourSharePointSite
$site.AllWebs.Count
```
|
Using the following code, within the SharePoint Management Shell, you can get the count of Web Applications in the Farm, Site Collections in Web Application, Sites in Site Collection.
```
Write-Host "Web Applications in Farm"
$WebApplications = Get-SPWebApplication
$WebApplications | Measure-Object | Format-List Count
ForEach($WebApplication in $WebApplications) {
Write-Host "Site Collections in the Web Application named " $WebApplication.Name
$WebApplication.Sites | Measure-Object | Format-List Count
ForEach($SiteCollection in $WebApplication.Sites) {
Write-Host "Webs (Sub-Sites) in the Site Collection with the URL " $SiteCollection.Url
Write-Host "`nCount : " $SiteCollection.AllWebs.Count "`n`n`n"
}
}
```
|
20,010,268 |
I have base structure as given below
```
Sales.Customers Sales.Orders Sales.OrderDetails
--------------- ------------ ------------------
country orderid orderid
custid custid qty
```
So I need return United States customers, and for each customer return the total number of orders and total quantities. I wrote such query:
```
SELECT
C.custid, SUM(O.orderid) as numorders,
SUM(OD.qty) as totalqty
FROM Sales.Customers AS C
JOIN Sales.Orders AS O
ON C.custid = O.custid
JOIN Sales.OrderDetails AS OD
ON O.orderid = OD.orderid
WHERE country = 'USA'
GROUP BY C.custid;
```
Unfortunately I get such result:
```
custid numorders totalqty
----------- ----------- -----------
32 235946 345
36 94228 122
43 21027 20
....... ..... ....
```
Instead of
```
custid numorders totalqty
----------- ----------- -----------
32 11 345
36 5 122
```
I can`t understand where mistake is.
|
2013/11/15
|
['https://Stackoverflow.com/questions/20010268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1739325/']
|
This should do:
```
SELECT C.custid,
COUNT(DISTINCT O.orderid) as numorders,
SUM(OD.qty) as totalqty
FROM Sales.Customers AS C
INNER JOIN Sales.Orders AS O
ON C.custid = O.custid
INNER JOIN Sales.OrderDetails AS OD
ON O.orderid = OD.orderid
WHERE country = 'USA'
GROUP BY C.custid
ORDER BY C.custid;
```
|
Upon a bit more reading, you have two things wrong. You're summing orders instead of counting, and you're grouping on quantity.
Try:
```
SELECT
C.custid,
COUNT(distinct O.orderid) as numorders,
SUM(OD.qty) as totalqty
FROM Sales.Customers AS C
JOIN Sales.Orders AS O
ON C.custid = O.custid
JOIN Sales.OrderDetails AS OD
ON O.orderid = OD.orderid
WHERE country = 'USA'
GROUP BY C.custid
ORDER BY C.custid;
```
|
3,875,021 |
This is a general best practice question about creating parent / child relationships with objects.
Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object
```
public class Car{
private List<Wheel> wheels = new List<Wheel>();
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd)
//Some Other logic relating to adding wheels here
}
}
}
```
So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this
```
public class Wheel {
private Car parentCar;
public Car
{
get
{
return parentCar
}
}
}
```
When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.
Any thoughts, many thanks in advance
|
2010/10/06
|
['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']
|
You might want to consider having a setter that only sets `Wheel.parentCar` if that setting is null, but only if you're able to assume that your first setting will be valid and are thus able to disregard any other attempts.
Edit: but yes, that would be the proper place to add the `Car` object. You could also do a check such that you create (for example) `Wheel.validateCar(Car carInQuestion)`, where it enforces that the `parentCar` property is only set where the current `Wheel` object exists in `Car`. This implies that you would have a public method for searching `Car.wheels` for membership based on a particular instance of a wheel. But that's only if you really feel the need to be strict.
|
I'm going to go with "Don't". A wheel isn't just a property of a `Car`. A wheel could be used on a `Trailer` or a `Cart` or a `FerrisWheel` (ok, maybe that's a bit of a stretch). The point is, by making the car which uses the wheel a property of the wheel itself, you couple your wheel's design to being used on a car, and at that point, you lose any reusability for the class.
In this case, it seems like there's a lot to lose and little to gain by letting the wheel know what it's actually used on.
|
3,875,021 |
This is a general best practice question about creating parent / child relationships with objects.
Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object
```
public class Car{
private List<Wheel> wheels = new List<Wheel>();
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd)
//Some Other logic relating to adding wheels here
}
}
}
```
So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this
```
public class Wheel {
private Car parentCar;
public Car
{
get
{
return parentCar
}
}
}
```
When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.
Any thoughts, many thanks in advance
|
2010/10/06
|
['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']
|
You might want to consider having a setter that only sets `Wheel.parentCar` if that setting is null, but only if you're able to assume that your first setting will be valid and are thus able to disregard any other attempts.
Edit: but yes, that would be the proper place to add the `Car` object. You could also do a check such that you create (for example) `Wheel.validateCar(Car carInQuestion)`, where it enforces that the `parentCar` property is only set where the current `Wheel` object exists in `Car`. This implies that you would have a public method for searching `Car.wheels` for membership based on a particular instance of a wheel. But that's only if you really feel the need to be strict.
|
May be a little left of centre but conceptually a wheel is a "part" of a car. Did you consider using partial classes? A passenger is a "part" of a queue. I find the use of partial classes and well defined interfaces is very useful in some scenarios. You can abstract out aspects of whole object into interfaces and implement each interface as a partial class. The result is a complete object that is able to be abstracted by its partial interface to meet an array of contractual scenarios.
|
3,875,021 |
This is a general best practice question about creating parent / child relationships with objects.
Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object
```
public class Car{
private List<Wheel> wheels = new List<Wheel>();
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd)
//Some Other logic relating to adding wheels here
}
}
}
```
So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this
```
public class Wheel {
private Car parentCar;
public Car
{
get
{
return parentCar
}
}
}
```
When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.
Any thoughts, many thanks in advance
|
2010/10/06
|
['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']
|
Bidirectional relationships tend to be very difficult to implement correctly. The prevailing advice here should be "don't do that, most likely you don't actually need it, and it will do you more harm than good."
If, after much careful consideration, you decide a bidirectional relationship is warranted, you can make the setter of the `Car` property `internal`, which doesn't fully protect against rogues setting unwanted values but it does limit the surface area significantly.
|
I'm going to go with "Don't". A wheel isn't just a property of a `Car`. A wheel could be used on a `Trailer` or a `Cart` or a `FerrisWheel` (ok, maybe that's a bit of a stretch). The point is, by making the car which uses the wheel a property of the wheel itself, you couple your wheel's design to being used on a car, and at that point, you lose any reusability for the class.
In this case, it seems like there's a lot to lose and little to gain by letting the wheel know what it's actually used on.
|
3,875,021 |
This is a general best practice question about creating parent / child relationships with objects.
Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object
```
public class Car{
private List<Wheel> wheels = new List<Wheel>();
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd)
//Some Other logic relating to adding wheels here
}
}
}
```
So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this
```
public class Wheel {
private Car parentCar;
public Car
{
get
{
return parentCar
}
}
}
```
When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.
Any thoughts, many thanks in advance
|
2010/10/06
|
['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']
|
Bidirectional relationships tend to be very difficult to implement correctly. The prevailing advice here should be "don't do that, most likely you don't actually need it, and it will do you more harm than good."
If, after much careful consideration, you decide a bidirectional relationship is warranted, you can make the setter of the `Car` property `internal`, which doesn't fully protect against rogues setting unwanted values but it does limit the surface area significantly.
|
May be a little left of centre but conceptually a wheel is a "part" of a car. Did you consider using partial classes? A passenger is a "part" of a queue. I find the use of partial classes and well defined interfaces is very useful in some scenarios. You can abstract out aspects of whole object into interfaces and implement each interface as a partial class. The result is a complete object that is able to be abstracted by its partial interface to meet an array of contractual scenarios.
|
3,875,021 |
This is a general best practice question about creating parent / child relationships with objects.
Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object
```
public class Car{
private List<Wheel> wheels = new List<Wheel>();
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd)
//Some Other logic relating to adding wheels here
}
}
}
```
So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this
```
public class Wheel {
private Car parentCar;
public Car
{
get
{
return parentCar
}
}
}
```
When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.
Any thoughts, many thanks in advance
|
2010/10/06
|
['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']
|
You might want to consider having a setter that only sets `Wheel.parentCar` if that setting is null, but only if you're able to assume that your first setting will be valid and are thus able to disregard any other attempts.
Edit: but yes, that would be the proper place to add the `Car` object. You could also do a check such that you create (for example) `Wheel.validateCar(Car carInQuestion)`, where it enforces that the `parentCar` property is only set where the current `Wheel` object exists in `Car`. This implies that you would have a public method for searching `Car.wheels` for membership based on a particular instance of a wheel. But that's only if you really feel the need to be strict.
|
Take a look at [Is it bad practice for a child object to have a pointer to its parent?](https://stackoverflow.com/questions/3724092/is-it-bad-practice-for-a-child-object-to-have-a-pointer-to-its-parent)
|
3,875,021 |
This is a general best practice question about creating parent / child relationships with objects.
Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object
```
public class Car{
private List<Wheel> wheels = new List<Wheel>();
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd)
//Some Other logic relating to adding wheels here
}
}
}
```
So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this
```
public class Wheel {
private Car parentCar;
public Car
{
get
{
return parentCar
}
}
}
```
When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.
Any thoughts, many thanks in advance
|
2010/10/06
|
['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']
|
Bidirectional relationships tend to be very difficult to implement correctly. The prevailing advice here should be "don't do that, most likely you don't actually need it, and it will do you more harm than good."
If, after much careful consideration, you decide a bidirectional relationship is warranted, you can make the setter of the `Car` property `internal`, which doesn't fully protect against rogues setting unwanted values but it does limit the surface area significantly.
|
Question: Can the Wheel instance be assigned to a different Car instance later in time?
1) If yes, the expose a public method to set the parentCar. You *could* make it a fluent method, for ease of code:
```
public class Wheel
{
private Car parentCar;
public ParentCar
{
get
{
return parentCar;
}
}
public void SetParentCar(Car _parentCar)
{
parentCar = _parentCar;
return this;
}
}
```
Where you assign add the wheel, make the assignment:
```
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd.SetParentCar(this));
//Some Other logic relating to adding wheels here
}
```
2) If not, just set the parent in the constructor.
```
public class Wheel
{
private Car parentCar;
public ParentCar
{
get
{
return parentCar;
}
}
public Wheel(Car _parentCar)
{
parentCar = _parentCar;
}
}
```
|
3,875,021 |
This is a general best practice question about creating parent / child relationships with objects.
Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object
```
public class Car{
private List<Wheel> wheels = new List<Wheel>();
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd)
//Some Other logic relating to adding wheels here
}
}
}
```
So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this
```
public class Wheel {
private Car parentCar;
public Car
{
get
{
return parentCar
}
}
}
```
When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.
Any thoughts, many thanks in advance
|
2010/10/06
|
['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']
|
Bidirectional relationships tend to be very difficult to implement correctly. The prevailing advice here should be "don't do that, most likely you don't actually need it, and it will do you more harm than good."
If, after much careful consideration, you decide a bidirectional relationship is warranted, you can make the setter of the `Car` property `internal`, which doesn't fully protect against rogues setting unwanted values but it does limit the surface area significantly.
|
It makes sense to me for the Car property of the Wheel object to be writable because there's nothing to stop you moving a Wheel from one ToyotaCamry (subclass of Car) to another. Though you might want to have a Drivable property on the original car to check that List.Count is still 4 before allowing Car.Drive() to be called.
Do you create Wheels with Cars? if so set the property at that time. Otherwise set it when Wheel is attached to Car.
|
3,875,021 |
This is a general best practice question about creating parent / child relationships with objects.
Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object
```
public class Car{
private List<Wheel> wheels = new List<Wheel>();
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd)
//Some Other logic relating to adding wheels here
}
}
}
```
So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this
```
public class Wheel {
private Car parentCar;
public Car
{
get
{
return parentCar
}
}
}
```
When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.
Any thoughts, many thanks in advance
|
2010/10/06
|
['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']
|
A better design methodology, (Domain Driven Design) specifies that you should first decide what the domain model requirements are for these entities... Not all entities need to be independantly accessible, and if `Wheel` falls into this category, every instance of it will always be a child member of a `Car` object and you don't need to put a Parent property on it... `Car` becomes what is referred to as a *root entity*, and the only way to access a `Wheel` is through a `Car` object.
Even when the `Wheel` object needs to be independantly accessible, the domain model requirements should tell you what the usage patterns require. Will any `Wheel` ever be passed around as a separate object, without it's parent ? In those cases is the `Car` parent relevant? If the identity of the parent `Car` *is* relevant to some piece of functionality, why aren't you simply passing the complete composite `Car` object to that method or module? Cases where a contained composite object (like a `Wheel`) must be passed on it's own, but the identity of the parent (the object it is part of) is needed and/or relevant, are in fact not a common scenario, and approaching your design using the above type of analysis can save you from adding unnessary code to you system.
|
Question: Can the Wheel instance be assigned to a different Car instance later in time?
1) If yes, the expose a public method to set the parentCar. You *could* make it a fluent method, for ease of code:
```
public class Wheel
{
private Car parentCar;
public ParentCar
{
get
{
return parentCar;
}
}
public void SetParentCar(Car _parentCar)
{
parentCar = _parentCar;
return this;
}
}
```
Where you assign add the wheel, make the assignment:
```
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd.SetParentCar(this));
//Some Other logic relating to adding wheels here
}
```
2) If not, just set the parent in the constructor.
```
public class Wheel
{
private Car parentCar;
public ParentCar
{
get
{
return parentCar;
}
}
public Wheel(Car _parentCar)
{
parentCar = _parentCar;
}
}
```
|
3,875,021 |
This is a general best practice question about creating parent / child relationships with objects.
Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object
```
public class Car{
private List<Wheel> wheels = new List<Wheel>();
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd)
//Some Other logic relating to adding wheels here
}
}
}
```
So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this
```
public class Wheel {
private Car parentCar;
public Car
{
get
{
return parentCar
}
}
}
```
When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.
Any thoughts, many thanks in advance
|
2010/10/06
|
['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']
|
You might want to consider having a setter that only sets `Wheel.parentCar` if that setting is null, but only if you're able to assume that your first setting will be valid and are thus able to disregard any other attempts.
Edit: but yes, that would be the proper place to add the `Car` object. You could also do a check such that you create (for example) `Wheel.validateCar(Car carInQuestion)`, where it enforces that the `parentCar` property is only set where the current `Wheel` object exists in `Car`. This implies that you would have a public method for searching `Car.wheels` for membership based on a particular instance of a wheel. But that's only if you really feel the need to be strict.
|
It makes sense to me for the Car property of the Wheel object to be writable because there's nothing to stop you moving a Wheel from one ToyotaCamry (subclass of Car) to another. Though you might want to have a Drivable property on the original car to check that List.Count is still 4 before allowing Car.Drive() to be called.
Do you create Wheels with Cars? if so set the property at that time. Otherwise set it when Wheel is attached to Car.
|
3,875,021 |
This is a general best practice question about creating parent / child relationships with objects.
Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object
```
public class Car{
private List<Wheel> wheels = new List<Wheel>();
void AddWheel ( Wheel WheelToAdd)
{
wheels.Add(WheelToAdd)
//Some Other logic relating to adding wheels here
}
}
}
```
So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this
```
public class Wheel {
private Car parentCar;
public Car
{
get
{
return parentCar
}
}
}
```
When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency.
Any thoughts, many thanks in advance
|
2010/10/06
|
['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']
|
A better design methodology, (Domain Driven Design) specifies that you should first decide what the domain model requirements are for these entities... Not all entities need to be independantly accessible, and if `Wheel` falls into this category, every instance of it will always be a child member of a `Car` object and you don't need to put a Parent property on it... `Car` becomes what is referred to as a *root entity*, and the only way to access a `Wheel` is through a `Car` object.
Even when the `Wheel` object needs to be independantly accessible, the domain model requirements should tell you what the usage patterns require. Will any `Wheel` ever be passed around as a separate object, without it's parent ? In those cases is the `Car` parent relevant? If the identity of the parent `Car` *is* relevant to some piece of functionality, why aren't you simply passing the complete composite `Car` object to that method or module? Cases where a contained composite object (like a `Wheel`) must be passed on it's own, but the identity of the parent (the object it is part of) is needed and/or relevant, are in fact not a common scenario, and approaching your design using the above type of analysis can save you from adding unnessary code to you system.
|
It makes sense to me for the Car property of the Wheel object to be writable because there's nothing to stop you moving a Wheel from one ToyotaCamry (subclass of Car) to another. Though you might want to have a Drivable property on the original car to check that List.Count is still 4 before allowing Car.Drive() to be called.
Do you create Wheels with Cars? if so set the property at that time. Otherwise set it when Wheel is attached to Car.
|
575,755 |
I am running a regression model in R including the following variables:
* Intent = continuous DV
* Attitude = continuous IV
* Story = categorical
IV in 4 levels: Consumer, Heritage, Vision and Product
* Style =
categorical IV in 4 levels: Amiable, Analytical, Driver and
Expressive
Categorical variables are dummy coded. I ran the following regression in R:
```
model 4 = glm(Intent ~ Story + Style + Attitude + Story*Style)
```
Results of this regression are found here under model 4:
[](https://i.stack.imgur.com/gd9Cv.png)
Naturally, R sets one story type and one style as reference groups, in my case the Consumer story and the Amiable style. My only issue is, how can I draw conclusions for these reference groups?
My goal is to be able to say "For Analytical styles, purchase intent is most positive when presented with a Product story". As the results show with a coefficient of 1.063 for Product\*Analytical. But how can I derive a similar conclusion for Amiable people?
Any help is welcome <3
|
2022/05/18
|
['https://stats.stackexchange.com/questions/575755', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/358498/']
|
I agree this is odd, but I suppose it could be caused by tied scores showing up in particular quartiles. Suppose we have 100 subjects that get scores from 1 to 100 in 1-point intervals, except that everybody who would have had a score between 26 and 50 instead gets a score of 30. In this case, the average score percentile among the second quartile is either 26 or 50, depending on how you handle endpoints in the percentile calculation. For a dataset with only distinct scores, the average percentile of the second quartile must be 37.5, but it would be possible to find a different average percentile within a quartile that contains tied scores. Not sure if this is the case, or if it's just an error in plotting - even Figures 1 and 4 don't look exactly the same in "actual test score" values (the second quantile in Fig 1 is near 35, but it's closer to 40 in Fig 4).
|
You said: "*The message is the perceived scores, and the actual scores are shown as a line for reference*" but I disagree.
**It doesn't matter that they aren't straight.**
Consider this, a variant of the upper left subplot:
[](https://i.stack.imgur.com/Vxxcg.png)
The yellow-colored region is where the perceived ability is higher than the actual ability. The green region is where the perceived ability is lower than the actual.
I think the important point is that when actual skill is low, estimate of performance is falsely very high, but this decreases as skill increases until the skill is very high, and estimated skill is moderately lower than actual skill.
Distribution of the measured variable can vary with population. It is easy to make a pathological example, where 25% of values get grades of 10% and the remainder get 100% to make a curve that is concave down. Similarly if 75% of all grades are 10% and the last quarter are 100% then it is strongly concave up. There are many general forms of curves and only a subset are linear.
Here is some code for exploring this a little bit, numerically.
```
#library stuff
if(!require(pacman)) {
install.packages("pacman");
require(pacman) }
p_load(dplyr, #munging
ggplot2)
#reproducibility
set.seed(575743)
#uniformly random sample of grades
y <- runif(100, min=0, max=100)
# y <- rnorm(100, mean=80, sd=10)
# y <- ifelse(y>100,100,y)
#make background points
q_list_all <- numeric(100)
q_store <- data.frame(q=0:100, y=0*(0:100), bin=0)
for(i in 1:101){
q_val <- (i-1)/100
q_store$y[i] <- quantile(y,q_val)
}
q_store$bin <- ceiling(q\_store$y/round(diff(range(q_store$y))/3.5))
#make the plot
ggplot(data=q_store, aes(x=q, y=y) ) +
geom_path(color="blue") + geom_point(color="blue") +
geom_boxplot(aes(group=bin), alpha=0.5) +
xlab("Quartile") + ylab("grade on test")
```
This is the plot that it makes:
[](https://i.stack.imgur.com/uIkD9.png)
If instead of using a uniform distribution, you were to use a normal one centered at 80% with a standard deviation of 10% and a maximum of 100%, then the plot looks more like this:
[](https://i.stack.imgur.com/DDWDt.png)
|
114,415 |
Voldemort couldn't kill Harry as long as he called the Dursleys home. Why didn't he just murder the Dursleys? This would prevent Harry from being able to live there.
|
2016/01/11
|
['https://scifi.stackexchange.com/questions/114415', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/55866/']
|
The traditional fanon answer is "there were blood wards protecting the house". It would not, however, have stopped Voldemort (or his Death Eaters) from attacking the Dursleys when they were out (as proved by Umbridge's dementor attack).
That said, Voldemort would have needed to figure out 1) that Harry lived at the Dursleys (which itself might not have been common knowledge), and 2) that the blood protection was tied to that fact (that's assuming it was, which we only have Dumbledore's word on, IIRC, so that might not even be true).
And after the ritual at the end of Harry's fourth year, Voldemort, specifically, had little to worry about from the blood protection anyway.
|
The Dursleys were safe by the same form of magic that kept Harry safe. However, all of them were only safe within the bounds of their home, till Harry came of age(i.e., he turned 17). Harry or any one of the Dursleys could have been attacked outside their home. Thus, when Harry was about to turn 17, the Order of Phoenix took the Dursleys some place safe. On that night, Harry and his protective guard were attacked as soon as they crossed the 'boundary' that protected the house, since they could not be attacked within that boundary. It was the house which had the protection.
Harry Potter and the Half Blood Prince:
Chapter 3: Will and Won't
>
> ..but Dumbledore raised his finger for silence, a silence which fell as though he had struck Uncle Vernon dumb.
> “The magic I evoked fifteen years ago means that Harry has powerful protection while he can still call this house ‘home.’ However miserable he has been here, however unwelcome, however badlytreated, you have at least, grudgingly, allowed him houseroom. This magic will cease to operate the moment that Harry turns seventeen; in other words, at the moment he becomes a man. I ask only this: that you allow Harry to return, once more, to this house, before his seventeenth birthday, which will ensure that the protection continues until that time.”
>
>
>
Harry Potter and the Deathly Hallows:
Chapter 3: The Dursleys Departing
>
> “You claim,” said Uncle Vernon, starting to pace yet again, “that this Lord
> Thing—”
>
>
> “—Voldemort,” said Harry impatiently, “and we’ve been through this about
> a hundred times already. This isn’t a claim, it’s fact, Dumbledore told you last
> year, and Kingsley and Mr. Weasley—”...
>
>
> ...“—Kingsley and Mr. Weasley explained it all as well,”Harry pressed on remorselessly. "Once I’m seventeen, the protective charm that keeps me safe will break, and that exposes you as well as me..."
>
>
>
|
114,415 |
Voldemort couldn't kill Harry as long as he called the Dursleys home. Why didn't he just murder the Dursleys? This would prevent Harry from being able to live there.
|
2016/01/11
|
['https://scifi.stackexchange.com/questions/114415', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/55866/']
|
The traditional fanon answer is "there were blood wards protecting the house". It would not, however, have stopped Voldemort (or his Death Eaters) from attacking the Dursleys when they were out (as proved by Umbridge's dementor attack).
That said, Voldemort would have needed to figure out 1) that Harry lived at the Dursleys (which itself might not have been common knowledge), and 2) that the blood protection was tied to that fact (that's assuming it was, which we only have Dumbledore's word on, IIRC, so that might not even be true).
And after the ritual at the end of Harry's fourth year, Voldemort, specifically, had little to worry about from the blood protection anyway.
|
What would he achieve with this?
According to Dumbledore:
>
> The magic I evoked fifteen years ago means that Harry has powerful
> protection while he can still call this house ‘home.’
>
>
>
Harry and Aunt Marge are the only living relatives of the Dursleys. So if the Dursleys are killed, then Harry will inherit the house or part of it.
Technically he will be still able to call the house his 'home' and the protection will stay.
There is also the possibility that Vernon and Petunia Dursley created a will that explicitly transfers the full ownership of the house to Aunt Marge in case they are all dead. In this case the Order of the Phoenix will have hard time persuading Aunt Marge to invite Harry to stay until he is seventeen.
Still I find this unlikely. Even the Dursleys, as horrible as they are, would not plan for what happens AFTER the death of their only child.
|
114,415 |
Voldemort couldn't kill Harry as long as he called the Dursleys home. Why didn't he just murder the Dursleys? This would prevent Harry from being able to live there.
|
2016/01/11
|
['https://scifi.stackexchange.com/questions/114415', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/55866/']
|
The Dursleys were safe by the same form of magic that kept Harry safe. However, all of them were only safe within the bounds of their home, till Harry came of age(i.e., he turned 17). Harry or any one of the Dursleys could have been attacked outside their home. Thus, when Harry was about to turn 17, the Order of Phoenix took the Dursleys some place safe. On that night, Harry and his protective guard were attacked as soon as they crossed the 'boundary' that protected the house, since they could not be attacked within that boundary. It was the house which had the protection.
Harry Potter and the Half Blood Prince:
Chapter 3: Will and Won't
>
> ..but Dumbledore raised his finger for silence, a silence which fell as though he had struck Uncle Vernon dumb.
> “The magic I evoked fifteen years ago means that Harry has powerful protection while he can still call this house ‘home.’ However miserable he has been here, however unwelcome, however badlytreated, you have at least, grudgingly, allowed him houseroom. This magic will cease to operate the moment that Harry turns seventeen; in other words, at the moment he becomes a man. I ask only this: that you allow Harry to return, once more, to this house, before his seventeenth birthday, which will ensure that the protection continues until that time.”
>
>
>
Harry Potter and the Deathly Hallows:
Chapter 3: The Dursleys Departing
>
> “You claim,” said Uncle Vernon, starting to pace yet again, “that this Lord
> Thing—”
>
>
> “—Voldemort,” said Harry impatiently, “and we’ve been through this about
> a hundred times already. This isn’t a claim, it’s fact, Dumbledore told you last
> year, and Kingsley and Mr. Weasley—”...
>
>
> ...“—Kingsley and Mr. Weasley explained it all as well,”Harry pressed on remorselessly. "Once I’m seventeen, the protective charm that keeps me safe will break, and that exposes you as well as me..."
>
>
>
|
What would he achieve with this?
According to Dumbledore:
>
> The magic I evoked fifteen years ago means that Harry has powerful
> protection while he can still call this house ‘home.’
>
>
>
Harry and Aunt Marge are the only living relatives of the Dursleys. So if the Dursleys are killed, then Harry will inherit the house or part of it.
Technically he will be still able to call the house his 'home' and the protection will stay.
There is also the possibility that Vernon and Petunia Dursley created a will that explicitly transfers the full ownership of the house to Aunt Marge in case they are all dead. In this case the Order of the Phoenix will have hard time persuading Aunt Marge to invite Harry to stay until he is seventeen.
Still I find this unlikely. Even the Dursleys, as horrible as they are, would not plan for what happens AFTER the death of their only child.
|
15,243,891 |
Hi,
I'm trying to do a simple app with Hibernate and Maven.
I've created hibernate.cfg.xml and mapping file contacts.hbm.xml.
**Once I start it I get an exception:**
```
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.hibernate.MappingException: invalid configuration
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2241)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2158)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2137)
at main.java.FirstHibernate.com.myhib.CRUDS.CrudsOps.main(CrudsOps.java:15)
Caused by: org.xml.sax.SAXParseException; lineNumber: 54; columnNumber: 129; Attribute "value" must be declared for element type "property".
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.addDTDDefaultAttrsAndValidate(XMLDTDValidator.java:1253)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1917)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(XMLDTDValidator.java:763)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:353)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2238)
... 3 more
```
**Here is my hibernate.cfg.xml**
```
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ Copyright (c) 2010, Red Hat Inc. or third-party contributors as
~ indicated by the @author tags or express copyright attribution
~ statements applied by the authors. All third-party contributions are
~ distributed under license by Red Hat Inc.
~
~ This copyrighted material is made available to anyone wishing to use, modify,
~ copy, or redistribute it subject to the terms and conditions of the GNU
~ Lesser General Public License, as published by the Free Software Foundation.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
~ for more details.
~
~ You should have received a copy of the GNU Lesser General Public License
~ along with this distribution; if not, write to:
~ Free Software Foundation, Inc.
~ 51 Franklin Street, Fifth Floor
~ Boston, MA 02110-1301 USA
-->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">postgres</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.connection.provider_class" value="org.hibernate.connection.DriverManagerConnectionProvider" />
<property name="propertyName">value</property>
<!-- Names the annotated entity class -->
<mapping resources="resources/hibernate/mapping/contacts.hbm.xml"/>
<mapping class="FirstHibernate.com.myhib.CRUDS.Contacts"/>
</session-factory>
</hibernate-configuration>
```
**contacts.hbm.xml**
```
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-mapping>
<class table="contacts" lazy="false" name="FirstHibernate.com.myhib.CRUDS.Contacts">
<id column="id" type="int" name="id">
<generator class="increment" />
</id>
<propetry name="fname" type="string" column="fname" />
<propetry name="lname" type="string" column="lname" />
</class>
</hibernate-mapping>
```
What can be a source of that exception?
P.S. Java classes could be posted if they are needed.
**--UPDATE--**
when I changed
```
<property name="hibernate.connection.provider_class" value="org.hibernate.connection.DriverManagerConnectionProvider"/>
```
to
```
<property name="hibernate.connection.provider_class">org.hibernate.connection.DriverManagerConnectionProvider</property>
```
I got such exception
```
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.hibernate.MappingException: invalid configuration
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2241)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2158)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2137)
at main.java.FirstHibernate.com.myhib.CRUDS.CrudsOps.main(CrudsOps.java:15)
Caused by: org.xml.sax.SAXParseException; lineNumber: 59; columnNumber: 76; Attribute "resources" must be declared for element type "mapping".
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.addDTDDefaultAttrsAndValidate(XMLDTDValidator.java:1253)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1917)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(XMLDTDValidator.java:763)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:353)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2238)
... 3 more
```
**--UPDATE 2--**
Once I changed
*Are you sure it's and not ? Because in the DTD I can only see 'resource' and not 'resources' attribute of the element 'mapping'. – Balázs Mária Németh 5 mins ago*
I got
```
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.hibernate.InvalidMappingException: Unable to read XML
at org.hibernate.util.xml.MappingReader.readMappingDocument(MappingReader.java:101)
at org.hibernate.cfg.Configuration.add(Configuration.java:513)
at org.hibernate.cfg.Configuration.add(Configuration.java:509)
at org.hibernate.cfg.Configuration.add(Configuration.java:716)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:801)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2344)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2310)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2290)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2243)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2158)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2137)
at main.java.FirstHibernate.com.myhib.CRUDS.CrudsOps.main(CrudsOps.java:15)
Caused by: org.xml.sax.SAXParseException; lineNumber: 6; columnNumber: 20; Document root element "hibernate-mapping", must match DOCTYPE root "hibernate-configuration".
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.rootElementSpecified(XMLDTDValidator.java:1599)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1877)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(XMLDTDValidator.java:742)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:376)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3063)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:881)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.util.xml.MappingReader.readMappingDocument(MappingReader.java:75)
... 11 more
```
**--UPDATE 3--**
That helped me
```
And finally it looks like there's a problem with contacts.hbm.xml. Change
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
to
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
```
Now I got such exception:
```
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.hibernate.InvalidMappingException: Unable to read XML
at org.hibernate.util.xml.MappingReader.readMappingDocument(MappingReader.java:101)
at org.hibernate.cfg.Configuration.add(Configuration.java:513)
at org.hibernate.cfg.Configuration.add(Configuration.java:509)
at org.hibernate.cfg.Configuration.add(Configuration.java:716)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:801)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2344)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2310)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2290)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2243)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2158)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2137)
at main.java.FirstHibernate.com.myhib.CRUDS.CrudsOps.main(CrudsOps.java:15)
Caused by: org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 63; Element type "propetry" must be declared.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1906)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(XMLDTDValidator.java:763)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:353)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.util.xml.MappingReader.readMappingDocument(MappingReader.java:75)
... 11 more
```
|
2013/03/06
|
['https://Stackoverflow.com/questions/15243891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304911/']
|
To get you started, I'll give an example with `S3` classes:
```
# create an S3 class using setClass:
setClass("S3_class", representation("list"))
# create an object of S3_class
S3_obj <- new("S3_class", list(x=sample(10), y=sample(10)))
```
Now, you can function-overload internal functions, for example, `length` function to your class as (you can also `operator-overload`):
```
length.S3_class <- function(x) sapply(x, length)
# which allows you to do:
length(S3_obj)
# x y
# 10 10
```
Or alternatively, you can have your own function with whatever name, where you can check if the object is of class `S3_class` and do something:
```
len <- function(x) {
if (class(x) != "S3_class") {
stop("object not of class S3_class")
}
sapply(x, length)
}
> len(S3_obj)
# x y
# 10 10
> len(1:10)
# Error in len(1:10) : object not of class S3_class
```
It is a bit hard to explain S4 (like S3) as there are quite a bit of terms and things to know of (they are not difficult, just different). I suggest you go through the links provided under comments for those (and for S3 as well, as my purpose here was to show you an example of how it's done).
|
R also has function closures, which fits your example quite nicely
```
test = function() {
len = 0
set_length = function(l = 0) len <<-l
get_length = function() len
return(list(set_length=set_length, get_length=get_length))
}
```
this gives:
```
R> m = test()
R> m$set_length(10)
R> m$get_length()
[1] 10
R> m$set_length()
R> m$get_length()
[1] 0
```
|
28,200,567 |
I'd like to disable some features of a web app I'm building, if the browser is Tor Browser. Can I inside the browser itself (client side, not server side) find out if the browser is Tor Browser?
I would prefer a solution that didn't issue any HTTP requests to match the browser's IP against Tor exit nodes.
Background: In my case, Tor Browser pops up a dialog that asks the user *"Should Tor Browser allow this website to extract HTML5 canvas image data?"*, because, says Tor Browser, canvas image data can be used to uniquely identify a browser.
**Update:** After reading the answers below: Perhaps the best solution in my case, is to keep a list of Tor exit nodes server side (an up-to-date list, refreshed periodically), and when a browser loads the page, I set a variable in a `<script>` tag, if the browser's IP matches such an exit node: `var isProbablyTorBrowser = true`. Then, client side, no additional requests, or complicated logic, is needed.
|
2015/01/28
|
['https://Stackoverflow.com/questions/28200567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/694469/']
|
The "official" way to detect tor is to check the user's IP address and see if it's a tor exit node. Tor runs [TorDNSEL](https://www.torproject.org/projects/tordnsel.html.en) for this purpose.
Here's a PHP implementation of a TorDNSEL lookup from a tutorial by [Irongeek](http://www.irongeek.com/i.php?page=security/detect-tor-exit-node-in-php)
```
function IsTorExitPoint(){
if (gethostbyname(ReverseIPOctets($_SERVER['REMOTE_ADDR']).".".$_SERVER['SERVER_PORT'].".".ReverseIPOctets($_SERVER['SERVER_ADDR']).".ip-port.exitlist.torproject.org")=="127.0.0.2") {
return true;
} else {
return false;
}
}
function ReverseIPOctets($inputip){
$ipoc = explode(".",$inputip);
return $ipoc[3].".".$ipoc[2].".".$ipoc[1].".".$ipoc[0];
}
```
If you're not using PHP, you should still be able to adapt this relatively easily.
***Another method of detecting Tor is to have a script download the list of Tor exit nodes every half hour or so, then check each user's IP address against that list. This may be less reliable, though, as not all exit nodes are published. There's a list you can use, and instructions, available at [dan.me.uk](https://www.dan.me.uk/tornodes).***
EDIT: Since you updated your question, the second option (a list you host locally) is going to be preferable.
|
There is no reliable way to detect the TOR Browser... That's kind of a goal of that browser. If you find a reliable way, chances are somebody else finds it too, tells the TOR developers and they close it.
E.g. all TOR Browser bundles report bogus, but reasonable User-Agents. The current release version e.g. says it is `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0` no matter what OS you're actually using.
You may apply some heuristics to detect a TOR Browser with a certain probability, but will also generate some false-positives...
* Check the user agent. TOR Browser will report the latest Firefox ESR on a certain OS, currently Windows 7 32-bit (but some users might have changed that again and other users might simply use the ESR release but not the TOR Browser)
* Plugins are disabled, so `navigator.plugins` will be empty (but some users might have re-enabled plugins again).
* etc.
* Detect the browser actually [uses the TOR network](https://www.torproject.org/docs/faq-abuse.html.en#Bans).
Of course, you'll have to keep your checks up to date, so it requires a fair amount of maintenance busywork.
Personally, given the less than stellar detection results, maintenance burden and very modest experience improvements for users, I wouldn't try to handle TOR Browser differently at all.
|
28,200,567 |
I'd like to disable some features of a web app I'm building, if the browser is Tor Browser. Can I inside the browser itself (client side, not server side) find out if the browser is Tor Browser?
I would prefer a solution that didn't issue any HTTP requests to match the browser's IP against Tor exit nodes.
Background: In my case, Tor Browser pops up a dialog that asks the user *"Should Tor Browser allow this website to extract HTML5 canvas image data?"*, because, says Tor Browser, canvas image data can be used to uniquely identify a browser.
**Update:** After reading the answers below: Perhaps the best solution in my case, is to keep a list of Tor exit nodes server side (an up-to-date list, refreshed periodically), and when a browser loads the page, I set a variable in a `<script>` tag, if the browser's IP matches such an exit node: `var isProbablyTorBrowser = true`. Then, client side, no additional requests, or complicated logic, is needed.
|
2015/01/28
|
['https://Stackoverflow.com/questions/28200567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/694469/']
|
The Tor browser is not designed to be undetectable (that's impossible to do). Rather, it is designed so that all copies are indistinguishable from each other: you cannot track a browser from one site to another, or from one visit to another, strictly through [browser fingerprinting](https://panopticlick.eff.org/).
This gives it a distinct fingerprint of its own. As of right now, a browser that
1. Has a User-Agent of `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0`
2. Has a screen resolution that matches the browser window size (particularly if that size is 1000x800)
3. Has a time zone of "0" (GMT)
4. Has no plugins (`navigator.plugins` is empty)
is probably the TBB browser. The User-Agent string may change when the next ESR version of Firefox comes out, most likely to `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/38.0`.
The screen resolution/browser window match alone may uniquely identify TBB: even in fullscreen mode, there's a one-pixel difference between window height and screen height in Firefox.
|
The "official" way to detect tor is to check the user's IP address and see if it's a tor exit node. Tor runs [TorDNSEL](https://www.torproject.org/projects/tordnsel.html.en) for this purpose.
Here's a PHP implementation of a TorDNSEL lookup from a tutorial by [Irongeek](http://www.irongeek.com/i.php?page=security/detect-tor-exit-node-in-php)
```
function IsTorExitPoint(){
if (gethostbyname(ReverseIPOctets($_SERVER['REMOTE_ADDR']).".".$_SERVER['SERVER_PORT'].".".ReverseIPOctets($_SERVER['SERVER_ADDR']).".ip-port.exitlist.torproject.org")=="127.0.0.2") {
return true;
} else {
return false;
}
}
function ReverseIPOctets($inputip){
$ipoc = explode(".",$inputip);
return $ipoc[3].".".$ipoc[2].".".$ipoc[1].".".$ipoc[0];
}
```
If you're not using PHP, you should still be able to adapt this relatively easily.
***Another method of detecting Tor is to have a script download the list of Tor exit nodes every half hour or so, then check each user's IP address against that list. This may be less reliable, though, as not all exit nodes are published. There's a list you can use, and instructions, available at [dan.me.uk](https://www.dan.me.uk/tornodes).***
EDIT: Since you updated your question, the second option (a list you host locally) is going to be preferable.
|
28,200,567 |
I'd like to disable some features of a web app I'm building, if the browser is Tor Browser. Can I inside the browser itself (client side, not server side) find out if the browser is Tor Browser?
I would prefer a solution that didn't issue any HTTP requests to match the browser's IP against Tor exit nodes.
Background: In my case, Tor Browser pops up a dialog that asks the user *"Should Tor Browser allow this website to extract HTML5 canvas image data?"*, because, says Tor Browser, canvas image data can be used to uniquely identify a browser.
**Update:** After reading the answers below: Perhaps the best solution in my case, is to keep a list of Tor exit nodes server side (an up-to-date list, refreshed periodically), and when a browser loads the page, I set a variable in a `<script>` tag, if the browser's IP matches such an exit node: `var isProbablyTorBrowser = true`. Then, client side, no additional requests, or complicated logic, is needed.
|
2015/01/28
|
['https://Stackoverflow.com/questions/28200567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/694469/']
|
The "official" way to detect tor is to check the user's IP address and see if it's a tor exit node. Tor runs [TorDNSEL](https://www.torproject.org/projects/tordnsel.html.en) for this purpose.
Here's a PHP implementation of a TorDNSEL lookup from a tutorial by [Irongeek](http://www.irongeek.com/i.php?page=security/detect-tor-exit-node-in-php)
```
function IsTorExitPoint(){
if (gethostbyname(ReverseIPOctets($_SERVER['REMOTE_ADDR']).".".$_SERVER['SERVER_PORT'].".".ReverseIPOctets($_SERVER['SERVER_ADDR']).".ip-port.exitlist.torproject.org")=="127.0.0.2") {
return true;
} else {
return false;
}
}
function ReverseIPOctets($inputip){
$ipoc = explode(".",$inputip);
return $ipoc[3].".".$ipoc[2].".".$ipoc[1].".".$ipoc[0];
}
```
If you're not using PHP, you should still be able to adapt this relatively easily.
***Another method of detecting Tor is to have a script download the list of Tor exit nodes every half hour or so, then check each user's IP address against that list. This may be less reliable, though, as not all exit nodes are published. There's a list you can use, and instructions, available at [dan.me.uk](https://www.dan.me.uk/tornodes).***
EDIT: Since you updated your question, the second option (a list you host locally) is going to be preferable.
|
By the firefox resource bundle you can check it.
The resource:// URI scheme is used by Firefox to call on-disk resources from internal modules and extensions.
But some of these resources may also be included to any web page and executed via script tag. Mozilla developers is not consider the resources as a fingerprinting vector, despite the fact that some of them can reveal what the user does not wish. For example, differences in built-in preferences files clearly indicates you are using Windows or Linux or Mac, even if you're behind Tor Browser.
<https://www.browserleaks.com/firefox>
|
28,200,567 |
I'd like to disable some features of a web app I'm building, if the browser is Tor Browser. Can I inside the browser itself (client side, not server side) find out if the browser is Tor Browser?
I would prefer a solution that didn't issue any HTTP requests to match the browser's IP against Tor exit nodes.
Background: In my case, Tor Browser pops up a dialog that asks the user *"Should Tor Browser allow this website to extract HTML5 canvas image data?"*, because, says Tor Browser, canvas image data can be used to uniquely identify a browser.
**Update:** After reading the answers below: Perhaps the best solution in my case, is to keep a list of Tor exit nodes server side (an up-to-date list, refreshed periodically), and when a browser loads the page, I set a variable in a `<script>` tag, if the browser's IP matches such an exit node: `var isProbablyTorBrowser = true`. Then, client side, no additional requests, or complicated logic, is needed.
|
2015/01/28
|
['https://Stackoverflow.com/questions/28200567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/694469/']
|
The "official" way to detect tor is to check the user's IP address and see if it's a tor exit node. Tor runs [TorDNSEL](https://www.torproject.org/projects/tordnsel.html.en) for this purpose.
Here's a PHP implementation of a TorDNSEL lookup from a tutorial by [Irongeek](http://www.irongeek.com/i.php?page=security/detect-tor-exit-node-in-php)
```
function IsTorExitPoint(){
if (gethostbyname(ReverseIPOctets($_SERVER['REMOTE_ADDR']).".".$_SERVER['SERVER_PORT'].".".ReverseIPOctets($_SERVER['SERVER_ADDR']).".ip-port.exitlist.torproject.org")=="127.0.0.2") {
return true;
} else {
return false;
}
}
function ReverseIPOctets($inputip){
$ipoc = explode(".",$inputip);
return $ipoc[3].".".$ipoc[2].".".$ipoc[1].".".$ipoc[0];
}
```
If you're not using PHP, you should still be able to adapt this relatively easily.
***Another method of detecting Tor is to have a script download the list of Tor exit nodes every half hour or so, then check each user's IP address against that list. This may be less reliable, though, as not all exit nodes are published. There's a list you can use, and instructions, available at [dan.me.uk](https://www.dan.me.uk/tornodes).***
EDIT: Since you updated your question, the second option (a list you host locally) is going to be preferable.
|
There might be a quite reliable way. Check if it returns you a blank (white) image when you try to Base64 it using canvas.
[When you do so an notification is shown.](https://i.stack.imgur.com/eMYJ9.png)
No matter what user chooses JS returns a white image. So you can try to base64 (<-- it's a verb ;)) a non white image and then check if a white base64 image returned.
UPD.
Here is an example I made for myself. For me it was important to detect if I have an access to the image, but it can be used for Tor detecting in some way.
UPD2.
There even might be no notification shown as it's shown in code snippet below. Maybe because it's ran in an iframe.
```js
function isTorBrowser() {
var img = document.createElement("img");
// Creates a black 1x1 px image
img.src = 'data:image/png;base64,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';
var canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = 1;
var ctx = canvas.getContext("2d");
var imagedata = ctx.getImageData(0, 0, canvas.width, canvas.height);
return imagedata.data[0] == 255
&& imagedata.data[1] == 255
&& imagedata.data[2] == 255
&& imagedata.data[3] == 255;
}
document.getElementById('tor-browser-test').innerHTML = isTorBrowser() ? 'Is Tor' : 'Not Tor';
```
```html
<div id="tor-browser-test"></div>
```
|
28,200,567 |
I'd like to disable some features of a web app I'm building, if the browser is Tor Browser. Can I inside the browser itself (client side, not server side) find out if the browser is Tor Browser?
I would prefer a solution that didn't issue any HTTP requests to match the browser's IP against Tor exit nodes.
Background: In my case, Tor Browser pops up a dialog that asks the user *"Should Tor Browser allow this website to extract HTML5 canvas image data?"*, because, says Tor Browser, canvas image data can be used to uniquely identify a browser.
**Update:** After reading the answers below: Perhaps the best solution in my case, is to keep a list of Tor exit nodes server side (an up-to-date list, refreshed periodically), and when a browser loads the page, I set a variable in a `<script>` tag, if the browser's IP matches such an exit node: `var isProbablyTorBrowser = true`. Then, client side, no additional requests, or complicated logic, is needed.
|
2015/01/28
|
['https://Stackoverflow.com/questions/28200567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/694469/']
|
The Tor browser is not designed to be undetectable (that's impossible to do). Rather, it is designed so that all copies are indistinguishable from each other: you cannot track a browser from one site to another, or from one visit to another, strictly through [browser fingerprinting](https://panopticlick.eff.org/).
This gives it a distinct fingerprint of its own. As of right now, a browser that
1. Has a User-Agent of `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0`
2. Has a screen resolution that matches the browser window size (particularly if that size is 1000x800)
3. Has a time zone of "0" (GMT)
4. Has no plugins (`navigator.plugins` is empty)
is probably the TBB browser. The User-Agent string may change when the next ESR version of Firefox comes out, most likely to `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/38.0`.
The screen resolution/browser window match alone may uniquely identify TBB: even in fullscreen mode, there's a one-pixel difference between window height and screen height in Firefox.
|
There is no reliable way to detect the TOR Browser... That's kind of a goal of that browser. If you find a reliable way, chances are somebody else finds it too, tells the TOR developers and they close it.
E.g. all TOR Browser bundles report bogus, but reasonable User-Agents. The current release version e.g. says it is `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0` no matter what OS you're actually using.
You may apply some heuristics to detect a TOR Browser with a certain probability, but will also generate some false-positives...
* Check the user agent. TOR Browser will report the latest Firefox ESR on a certain OS, currently Windows 7 32-bit (but some users might have changed that again and other users might simply use the ESR release but not the TOR Browser)
* Plugins are disabled, so `navigator.plugins` will be empty (but some users might have re-enabled plugins again).
* etc.
* Detect the browser actually [uses the TOR network](https://www.torproject.org/docs/faq-abuse.html.en#Bans).
Of course, you'll have to keep your checks up to date, so it requires a fair amount of maintenance busywork.
Personally, given the less than stellar detection results, maintenance burden and very modest experience improvements for users, I wouldn't try to handle TOR Browser differently at all.
|
28,200,567 |
I'd like to disable some features of a web app I'm building, if the browser is Tor Browser. Can I inside the browser itself (client side, not server side) find out if the browser is Tor Browser?
I would prefer a solution that didn't issue any HTTP requests to match the browser's IP against Tor exit nodes.
Background: In my case, Tor Browser pops up a dialog that asks the user *"Should Tor Browser allow this website to extract HTML5 canvas image data?"*, because, says Tor Browser, canvas image data can be used to uniquely identify a browser.
**Update:** After reading the answers below: Perhaps the best solution in my case, is to keep a list of Tor exit nodes server side (an up-to-date list, refreshed periodically), and when a browser loads the page, I set a variable in a `<script>` tag, if the browser's IP matches such an exit node: `var isProbablyTorBrowser = true`. Then, client side, no additional requests, or complicated logic, is needed.
|
2015/01/28
|
['https://Stackoverflow.com/questions/28200567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/694469/']
|
There is no reliable way to detect the TOR Browser... That's kind of a goal of that browser. If you find a reliable way, chances are somebody else finds it too, tells the TOR developers and they close it.
E.g. all TOR Browser bundles report bogus, but reasonable User-Agents. The current release version e.g. says it is `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0` no matter what OS you're actually using.
You may apply some heuristics to detect a TOR Browser with a certain probability, but will also generate some false-positives...
* Check the user agent. TOR Browser will report the latest Firefox ESR on a certain OS, currently Windows 7 32-bit (but some users might have changed that again and other users might simply use the ESR release but not the TOR Browser)
* Plugins are disabled, so `navigator.plugins` will be empty (but some users might have re-enabled plugins again).
* etc.
* Detect the browser actually [uses the TOR network](https://www.torproject.org/docs/faq-abuse.html.en#Bans).
Of course, you'll have to keep your checks up to date, so it requires a fair amount of maintenance busywork.
Personally, given the less than stellar detection results, maintenance burden and very modest experience improvements for users, I wouldn't try to handle TOR Browser differently at all.
|
By the firefox resource bundle you can check it.
The resource:// URI scheme is used by Firefox to call on-disk resources from internal modules and extensions.
But some of these resources may also be included to any web page and executed via script tag. Mozilla developers is not consider the resources as a fingerprinting vector, despite the fact that some of them can reveal what the user does not wish. For example, differences in built-in preferences files clearly indicates you are using Windows or Linux or Mac, even if you're behind Tor Browser.
<https://www.browserleaks.com/firefox>
|
28,200,567 |
I'd like to disable some features of a web app I'm building, if the browser is Tor Browser. Can I inside the browser itself (client side, not server side) find out if the browser is Tor Browser?
I would prefer a solution that didn't issue any HTTP requests to match the browser's IP against Tor exit nodes.
Background: In my case, Tor Browser pops up a dialog that asks the user *"Should Tor Browser allow this website to extract HTML5 canvas image data?"*, because, says Tor Browser, canvas image data can be used to uniquely identify a browser.
**Update:** After reading the answers below: Perhaps the best solution in my case, is to keep a list of Tor exit nodes server side (an up-to-date list, refreshed periodically), and when a browser loads the page, I set a variable in a `<script>` tag, if the browser's IP matches such an exit node: `var isProbablyTorBrowser = true`. Then, client side, no additional requests, or complicated logic, is needed.
|
2015/01/28
|
['https://Stackoverflow.com/questions/28200567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/694469/']
|
The Tor browser is not designed to be undetectable (that's impossible to do). Rather, it is designed so that all copies are indistinguishable from each other: you cannot track a browser from one site to another, or from one visit to another, strictly through [browser fingerprinting](https://panopticlick.eff.org/).
This gives it a distinct fingerprint of its own. As of right now, a browser that
1. Has a User-Agent of `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0`
2. Has a screen resolution that matches the browser window size (particularly if that size is 1000x800)
3. Has a time zone of "0" (GMT)
4. Has no plugins (`navigator.plugins` is empty)
is probably the TBB browser. The User-Agent string may change when the next ESR version of Firefox comes out, most likely to `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/38.0`.
The screen resolution/browser window match alone may uniquely identify TBB: even in fullscreen mode, there's a one-pixel difference between window height and screen height in Firefox.
|
By the firefox resource bundle you can check it.
The resource:// URI scheme is used by Firefox to call on-disk resources from internal modules and extensions.
But some of these resources may also be included to any web page and executed via script tag. Mozilla developers is not consider the resources as a fingerprinting vector, despite the fact that some of them can reveal what the user does not wish. For example, differences in built-in preferences files clearly indicates you are using Windows or Linux or Mac, even if you're behind Tor Browser.
<https://www.browserleaks.com/firefox>
|
28,200,567 |
I'd like to disable some features of a web app I'm building, if the browser is Tor Browser. Can I inside the browser itself (client side, not server side) find out if the browser is Tor Browser?
I would prefer a solution that didn't issue any HTTP requests to match the browser's IP against Tor exit nodes.
Background: In my case, Tor Browser pops up a dialog that asks the user *"Should Tor Browser allow this website to extract HTML5 canvas image data?"*, because, says Tor Browser, canvas image data can be used to uniquely identify a browser.
**Update:** After reading the answers below: Perhaps the best solution in my case, is to keep a list of Tor exit nodes server side (an up-to-date list, refreshed periodically), and when a browser loads the page, I set a variable in a `<script>` tag, if the browser's IP matches such an exit node: `var isProbablyTorBrowser = true`. Then, client side, no additional requests, or complicated logic, is needed.
|
2015/01/28
|
['https://Stackoverflow.com/questions/28200567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/694469/']
|
The Tor browser is not designed to be undetectable (that's impossible to do). Rather, it is designed so that all copies are indistinguishable from each other: you cannot track a browser from one site to another, or from one visit to another, strictly through [browser fingerprinting](https://panopticlick.eff.org/).
This gives it a distinct fingerprint of its own. As of right now, a browser that
1. Has a User-Agent of `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0`
2. Has a screen resolution that matches the browser window size (particularly if that size is 1000x800)
3. Has a time zone of "0" (GMT)
4. Has no plugins (`navigator.plugins` is empty)
is probably the TBB browser. The User-Agent string may change when the next ESR version of Firefox comes out, most likely to `Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/38.0`.
The screen resolution/browser window match alone may uniquely identify TBB: even in fullscreen mode, there's a one-pixel difference between window height and screen height in Firefox.
|
There might be a quite reliable way. Check if it returns you a blank (white) image when you try to Base64 it using canvas.
[When you do so an notification is shown.](https://i.stack.imgur.com/eMYJ9.png)
No matter what user chooses JS returns a white image. So you can try to base64 (<-- it's a verb ;)) a non white image and then check if a white base64 image returned.
UPD.
Here is an example I made for myself. For me it was important to detect if I have an access to the image, but it can be used for Tor detecting in some way.
UPD2.
There even might be no notification shown as it's shown in code snippet below. Maybe because it's ran in an iframe.
```js
function isTorBrowser() {
var img = document.createElement("img");
// Creates a black 1x1 px image
img.src = 'data:image/png;base64,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';
var canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = 1;
var ctx = canvas.getContext("2d");
var imagedata = ctx.getImageData(0, 0, canvas.width, canvas.height);
return imagedata.data[0] == 255
&& imagedata.data[1] == 255
&& imagedata.data[2] == 255
&& imagedata.data[3] == 255;
}
document.getElementById('tor-browser-test').innerHTML = isTorBrowser() ? 'Is Tor' : 'Not Tor';
```
```html
<div id="tor-browser-test"></div>
```
|
28,200,567 |
I'd like to disable some features of a web app I'm building, if the browser is Tor Browser. Can I inside the browser itself (client side, not server side) find out if the browser is Tor Browser?
I would prefer a solution that didn't issue any HTTP requests to match the browser's IP against Tor exit nodes.
Background: In my case, Tor Browser pops up a dialog that asks the user *"Should Tor Browser allow this website to extract HTML5 canvas image data?"*, because, says Tor Browser, canvas image data can be used to uniquely identify a browser.
**Update:** After reading the answers below: Perhaps the best solution in my case, is to keep a list of Tor exit nodes server side (an up-to-date list, refreshed periodically), and when a browser loads the page, I set a variable in a `<script>` tag, if the browser's IP matches such an exit node: `var isProbablyTorBrowser = true`. Then, client side, no additional requests, or complicated logic, is needed.
|
2015/01/28
|
['https://Stackoverflow.com/questions/28200567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/694469/']
|
There might be a quite reliable way. Check if it returns you a blank (white) image when you try to Base64 it using canvas.
[When you do so an notification is shown.](https://i.stack.imgur.com/eMYJ9.png)
No matter what user chooses JS returns a white image. So you can try to base64 (<-- it's a verb ;)) a non white image and then check if a white base64 image returned.
UPD.
Here is an example I made for myself. For me it was important to detect if I have an access to the image, but it can be used for Tor detecting in some way.
UPD2.
There even might be no notification shown as it's shown in code snippet below. Maybe because it's ran in an iframe.
```js
function isTorBrowser() {
var img = document.createElement("img");
// Creates a black 1x1 px image
img.src = 'data:image/png;base64,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';
var canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = 1;
var ctx = canvas.getContext("2d");
var imagedata = ctx.getImageData(0, 0, canvas.width, canvas.height);
return imagedata.data[0] == 255
&& imagedata.data[1] == 255
&& imagedata.data[2] == 255
&& imagedata.data[3] == 255;
}
document.getElementById('tor-browser-test').innerHTML = isTorBrowser() ? 'Is Tor' : 'Not Tor';
```
```html
<div id="tor-browser-test"></div>
```
|
By the firefox resource bundle you can check it.
The resource:// URI scheme is used by Firefox to call on-disk resources from internal modules and extensions.
But some of these resources may also be included to any web page and executed via script tag. Mozilla developers is not consider the resources as a fingerprinting vector, despite the fact that some of them can reveal what the user does not wish. For example, differences in built-in preferences files clearly indicates you are using Windows or Linux or Mac, even if you're behind Tor Browser.
<https://www.browserleaks.com/firefox>
|
425,836 |
What I mean by this question is, as we say that the electric field energy around a charge is the self energy of the charge, similarly can we say that the magnetic field energy around a current carrying wire is the Self Energy of the current? If yes, then following questions arise :
1. Why the current is associated with certain Self Energy?
2. Where does this magnetic field energy come from? Does it come from the battery the wire is connected to?
3. Why the self energy of a charge then called its interaction energy within and with other charges around?
4. Is the self energy of a charge equal to the integral of interaction energy over its volume? If yes, then what would be the Self Energy of an Electron?
5. Is there a difference between Self Energy and Potential Energy? Or they are just two names of the same basic underlying reality?
|
2018/08/31
|
['https://physics.stackexchange.com/questions/425836', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/185612/']
|
It would be inappropriate to say that a current carrying wire would have Self Energy, in form of Magnetic Field Energy. Self Energy of charges are different from this concept.
In electrical circuits, for a very small duration of time, when current was growing in the circuit, the current was variable, due to which the magnetic field associated with it was also variable, due to which induced non conservative electric field came into existence and this electric field, extracted some energy from the system (from battery) and stored this energy in form of magnetic field energy in the contour of circuit. We generally ignore this energy since this energy is very small, due to very small self inductance of a straight wire. Once the current becomes steady, no further storage of energy happens in magnetic field and magnetic field energy becomes steady. Now, all the further energy supplied by battery get consumed only in the resistance in joule heating. Now, if the circuit is broken or it is short circuited, then this stored magnetic field energy returns to the circuit and finally converts into joule heating.
|
Potential energy is a book-keeping device. Only *differences* in potential energy correspond to real energy. Since the electric and magnetic vector fields are defined by changes in potentials, any electromagnetic field with non-zero $\mathbf{E}$ or $\mathbf{B}$ has a (real) energy density, and this energy density is essentially $\mathbf{E}^2 + \mathbf{B}^2$ (ignoring some constants which I don't remember at the moment).
Self-energy can be defined as the energy of the electromagnetic field that surrounds an isolated charge, i.e. by integrating the field's energy density all over an otherwise empty space. If the charge is moving, part of that field energy comes from the magnetic field. However, a co-moving observer will only see a static electric field and a zero magnetic field, so the distinction between the electromagnetic field's electric and magnetic components is observer-dependent.
There is also a concept of self-energy in quantum field theory, which comes from a particle's interaction with itself. I don't really understand that stuff, so I'll just mention it here.
|
44,068,795 |
can we override Apache CXF generated HTML page
i tried
```
<init-param>
<param-name>hide-service-list-page</param-name>
<param-value>true</param-value>
</init-param>
```
but it shows "No service was found" instead of showing this how can we show different html page.
Thanks
|
2017/05/19
|
['https://Stackoverflow.com/questions/44068795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2088219/']
|
Apache cxf use a class called `FormattedServiceListWriter` to generate the html page that you are talking about, you can take a look of the code [here](https://github.com/apache/cxf/blob/a36af6323505211479c875fb9923cc6dcbc6ac95/rt/transports/http/src/main/java/org/apache/cxf/transport/servlet/servicelist/FormattedServiceListWriter.java).
What you can do to personalize that page is to create a class in your project with the exact same name in the same package `org.apache.cxf.transport.servlet.servicelist` (you have to create that package in your project also), and change the `writeServiceList` method for your own implementation, that class will have priority over the one in the cxf jar
new `FormattedServiceListWriter` class
```
package org.apache.cxf.transport.servlet.servicelist;
/*--imports--*/
public class FormattedServiceListWriter implements ServiceListWriter {
/*... this remains the same as in the original class*/
public void writeServiceList(PrintWriter writer,
String basePath,
AbstractDestination[] soapDestinations,
AbstractDestination[] restDestinations) throws IOException {
/*this is the method you should change*/
writer.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
+ "\"http://www.w3.org/TR/html4/loose.dtd\">");
writer.write("<HTML><HEAD>");
writer.write("<LINK type=\"text/css\" rel=\"stylesheet\" href=\"" + styleSheetPath + "\">");
writer.write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
if (title != null) {
writer.write("<title>" + title + "</title>");
} else {
writer.write("<title>CXF - Service list</title>");
}
writer.write("</head><body>");
writer.write("<span class=\"heading\">WHATEVER YOU WANT TO PUT HERE</span>");
writer.write("</body></html>");
}
/*... this remains the same as in the original class*/
}
```
|
You can try this in your **web.xml** to override the service list path
```
<init-param>
<param-name>service-list-path</param-name>
<param-value>/*</param-value>
</init-param>
```
|
20,331 |
Has anyone thought about the possibility of a programming language, and a compiler, such that the compiler can automatically do worst-case asymptotic analysis? The use case I have in mind is a programming language where I write code, and compile. The compiler tells me that my code runs in O(n^2) (for example). It does this by doing what the smart people who do algorithmic analysis do, possibly counting loops and so on.
* Because of halting problem issues, and since one can have programs that work by dovetailing, for example Levin's algorithm for SAT that runs in polynomial time iff P=NP, I suspect that one may have to design the programming language to be sufficiently restrictive to allow something like this. Are there negative results, which rule out certain kinds of programming languages from having such compilers.
* I would also be interested in systems that give not an exact asymptotic analysis, but an "interesting" upper bound.
* I am specifically *NOT* interested in black box and statistical methods that sample from inputs of particular length, and find out how long the program takes. These methods are very interesting, but they are not what I'm looking for. I am interested in *exact* methods that may give *approximate* bounds.
I would be very grateful if someone could point me to some references on work in this direction.
|
2013/12/26
|
['https://cstheory.stackexchange.com/questions/20331', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/492/']
|
Implicit Complexity has taught us that (some) complexity classes can be classified by type systems, in the sense that there are type systems that only accept polynomial programs, for example. One more practical-minded offshoot of this research is [RAML](http://raml.tcs.ifi.lmu.de/documentation/papers) (Resource Aware ML), a functional programming language with a type system that will give you precise information of the running times of its programs. It is more precise, in fact, than big-O complexity, are constant factors are also included, parametrized by a cost model for the base operations.
You may think that this is cheating: surely some algorithms have a complexity that is very hard to compute precisely, so how could this language easily determine the complexity of its programs? The trick is that there are many ways to express a given algorithm, some which the type-system will reject (it rejects some fine programs), and some, maybe, that it accept. So the user doesn't get the world for free: he or she doesn't have to compute cost estimations anymore, but need to figure how to express code in a way that is accepted by the system.
(It is always the same trick, as with programming languages with only terminating computations, or provable security properties, etc.)
|
I actually thought about the same question a while ago. Here is the train of thought I had:
As you said the halting problem is an issue. To avoid this we need a language which only allows programs that always halt. On the other hand our language needs to be expressive enough to deal with most common problems(e.g. it should at least capture all of the complexity class EXP).
So, let's look at LOOP programs. A LOOP program always halts and its expressiveness is way beyond EXP - to get a better idea: you can simulate any TM for which the runtime function can be expressed as LOOP program.
Now, we can look at the nesting depth and the magnitude of the number of repetitions for every loop from a syntactic point of view and we have a starting point(dont know how far this takes us though). However, consider the following problem:
We want to implement the function $f(n)$:
$f(n) = y$ such that $y$ is the first prime number after $n$ with $y > n$
Let's assume we have a function $p(n)$ which tells us whether a number $n$ is prime or not. Then to implement $f(n)$ most of us would probably write something like:
```
y := n + 1
while not prime(y)
y++
return y
```
Now, how are we going to do this with only bounded loops? The problem now becomes to think about an upper bound for the range of numbers we have to search.
But that was what we wanted our compiler to tell us in some sense! So, we just shifted the problem of pondering about time complexiy to the programmer. By the way, the following sentence gives us the upper bound for our problem:
$$ \forall \text{ prime } p \phantom{a} \exists \text{ prime } p' : p < p' \leq p! + 1 $$
My intuition here is that the only information a compiler can give you is from carefully analyzing the syntax which in the end is provided by the programmer. So, enabling the compiler to make any meaningful statement about the time complexity of a program means to force the programmer to incorporate this information into the program.
However, the last paragraph is subjective and there certainly might be other possible approaches which yield interesting results. I just wanted to give an idea of what not to expect when going down this road.
|
20,331 |
Has anyone thought about the possibility of a programming language, and a compiler, such that the compiler can automatically do worst-case asymptotic analysis? The use case I have in mind is a programming language where I write code, and compile. The compiler tells me that my code runs in O(n^2) (for example). It does this by doing what the smart people who do algorithmic analysis do, possibly counting loops and so on.
* Because of halting problem issues, and since one can have programs that work by dovetailing, for example Levin's algorithm for SAT that runs in polynomial time iff P=NP, I suspect that one may have to design the programming language to be sufficiently restrictive to allow something like this. Are there negative results, which rule out certain kinds of programming languages from having such compilers.
* I would also be interested in systems that give not an exact asymptotic analysis, but an "interesting" upper bound.
* I am specifically *NOT* interested in black box and statistical methods that sample from inputs of particular length, and find out how long the program takes. These methods are very interesting, but they are not what I'm looking for. I am interested in *exact* methods that may give *approximate* bounds.
I would be very grateful if someone could point me to some references on work in this direction.
|
2013/12/26
|
['https://cstheory.stackexchange.com/questions/20331', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/492/']
|
The [COSTA tool](http://costa.ls.fi.upm.es/~costa/costa/costa.php) developed by the [COSTA research group](http://costa.ls.fi.upm.es/web/) does exactly what you want. Given a program (in Java bytecode format), the tool produces a cost equation based on a cost model provided by the programmer. The cost model can involve entities such as runtime, memory usage, or billable events (such as sending text messages). The runtime equation is then solved using a dedicated tool to produce a closed form, worst-case upper bound of the cost model.
Naturally, the tool does not work in all cases, either by failing to produce a runtime equation or by failing to find a closed form. This is not surprising.
|
I actually thought about the same question a while ago. Here is the train of thought I had:
As you said the halting problem is an issue. To avoid this we need a language which only allows programs that always halt. On the other hand our language needs to be expressive enough to deal with most common problems(e.g. it should at least capture all of the complexity class EXP).
So, let's look at LOOP programs. A LOOP program always halts and its expressiveness is way beyond EXP - to get a better idea: you can simulate any TM for which the runtime function can be expressed as LOOP program.
Now, we can look at the nesting depth and the magnitude of the number of repetitions for every loop from a syntactic point of view and we have a starting point(dont know how far this takes us though). However, consider the following problem:
We want to implement the function $f(n)$:
$f(n) = y$ such that $y$ is the first prime number after $n$ with $y > n$
Let's assume we have a function $p(n)$ which tells us whether a number $n$ is prime or not. Then to implement $f(n)$ most of us would probably write something like:
```
y := n + 1
while not prime(y)
y++
return y
```
Now, how are we going to do this with only bounded loops? The problem now becomes to think about an upper bound for the range of numbers we have to search.
But that was what we wanted our compiler to tell us in some sense! So, we just shifted the problem of pondering about time complexiy to the programmer. By the way, the following sentence gives us the upper bound for our problem:
$$ \forall \text{ prime } p \phantom{a} \exists \text{ prime } p' : p < p' \leq p! + 1 $$
My intuition here is that the only information a compiler can give you is from carefully analyzing the syntax which in the end is provided by the programmer. So, enabling the compiler to make any meaningful statement about the time complexity of a program means to force the programmer to incorporate this information into the program.
However, the last paragraph is subjective and there certainly might be other possible approaches which yield interesting results. I just wanted to give an idea of what not to expect when going down this road.
|
20,331 |
Has anyone thought about the possibility of a programming language, and a compiler, such that the compiler can automatically do worst-case asymptotic analysis? The use case I have in mind is a programming language where I write code, and compile. The compiler tells me that my code runs in O(n^2) (for example). It does this by doing what the smart people who do algorithmic analysis do, possibly counting loops and so on.
* Because of halting problem issues, and since one can have programs that work by dovetailing, for example Levin's algorithm for SAT that runs in polynomial time iff P=NP, I suspect that one may have to design the programming language to be sufficiently restrictive to allow something like this. Are there negative results, which rule out certain kinds of programming languages from having such compilers.
* I would also be interested in systems that give not an exact asymptotic analysis, but an "interesting" upper bound.
* I am specifically *NOT* interested in black box and statistical methods that sample from inputs of particular length, and find out how long the program takes. These methods are very interesting, but they are not what I'm looking for. I am interested in *exact* methods that may give *approximate* bounds.
I would be very grateful if someone could point me to some references on work in this direction.
|
2013/12/26
|
['https://cstheory.stackexchange.com/questions/20331', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/492/']
|
Implicit Complexity has taught us that (some) complexity classes can be classified by type systems, in the sense that there are type systems that only accept polynomial programs, for example. One more practical-minded offshoot of this research is [RAML](http://raml.tcs.ifi.lmu.de/documentation/papers) (Resource Aware ML), a functional programming language with a type system that will give you precise information of the running times of its programs. It is more precise, in fact, than big-O complexity, are constant factors are also included, parametrized by a cost model for the base operations.
You may think that this is cheating: surely some algorithms have a complexity that is very hard to compute precisely, so how could this language easily determine the complexity of its programs? The trick is that there are many ways to express a given algorithm, some which the type-system will reject (it rejects some fine programs), and some, maybe, that it accept. So the user doesn't get the world for free: he or she doesn't have to compute cost estimations anymore, but need to figure how to express code in a way that is accepted by the system.
(It is always the same trick, as with programming languages with only terminating computations, or provable security properties, etc.)
|
The [COSTA tool](http://costa.ls.fi.upm.es/~costa/costa/costa.php) developed by the [COSTA research group](http://costa.ls.fi.upm.es/web/) does exactly what you want. Given a program (in Java bytecode format), the tool produces a cost equation based on a cost model provided by the programmer. The cost model can involve entities such as runtime, memory usage, or billable events (such as sending text messages). The runtime equation is then solved using a dedicated tool to produce a closed form, worst-case upper bound of the cost model.
Naturally, the tool does not work in all cases, either by failing to produce a runtime equation or by failing to find a closed form. This is not surprising.
|
3,778,961 |
I need to show $(0,1)$, $[0,1)$ and $[0,1]$ are not homeomorphic using intermediate value theorem (without using connectedness).
I have already did proved that $(0,1)$, $[0,1]$ are not homeomorphic but I struggle with the 2 other couples.
My proof: assume there is an homeomorphism $f:(0,1)\rightarrow[0,1]$ and take $a,b$ such that $f(a)=0, f(b)=1$. So using intermediate value theorem we can say that $f([a,b]) = [0,1]$. so $f$ isn't injective.
Will appreciate any help
|
2020/08/03
|
['https://math.stackexchange.com/questions/3778961', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/813552/']
|
$[0,1]$ is compact but the other two are not. Hence none of them are homeomorphic to $[0,1]$.
Now to show that $(0,1)$ and $[0,1)$ are not homeomorphic.
Suppose $f:[0,1)\to(0,1)$ is a homomorphism.
Then $f(0)\in (0,1)$ so $(0,1)\setminus \{f(0)\}$ is a disconnected set.
But $f((0,1))=(0,1)\setminus \{f(0)\}$, which is not possible as the continuous image of a connected set is connected .
|
Observe that if $\;f:X\to Y\;$ is a homeomorphism between two toplogical spaces and $\;x\in X\;$ then
$$\;g:X\setminus\{x\}\to Y\setminus\{f(x)\}\;,\;\;g(a)=f(a)\;\;\forall\;a\in X\setminus\{x\}\;$$
is also a homeomorphism on the respective top. spaces with the induced topology, and thus: if
$$f:[0,1)\to(0,1)\;\;\text{is a homeomorphism, then}\;\;g:(0,1)\to[(0,1)\setminus\{f(0)\}$$
is also a homeomorhpism. but this can't be since $\;(0,1)\;$ is (path) connected whereas $\;[(0,1)\setminus\{f(0)\}\;$ isn't.
Complete the other pair now (there you have path connectedness if you don't want connectedness...I don't understand why, but whatever)
|
3,778,961 |
I need to show $(0,1)$, $[0,1)$ and $[0,1]$ are not homeomorphic using intermediate value theorem (without using connectedness).
I have already did proved that $(0,1)$, $[0,1]$ are not homeomorphic but I struggle with the 2 other couples.
My proof: assume there is an homeomorphism $f:(0,1)\rightarrow[0,1]$ and take $a,b$ such that $f(a)=0, f(b)=1$. So using intermediate value theorem we can say that $f([a,b]) = [0,1]$. so $f$ isn't injective.
Will appreciate any help
|
2020/08/03
|
['https://math.stackexchange.com/questions/3778961', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/813552/']
|
You have to be a little more careful: you’ve written your argument on the assumption that $a<b$, but it could be that $b<a$, in which case it’s the interval $[b,a]$ that maps to $[0,1]$. You get the same contradiction, of course.
HINT: The same argument works if the domain of $f$ is $[0,1)$. For $(0,1)$ and $[0,1)$ you have to work a little harder, but you can still use the same idea. Suppose that $f:(0,1)\to[0,1)$ is a homeomorphism. There is an $a\in(0,1)$ such that $f(a)=0$, and for each $n\ge 2$ there is a $b\_n\in(0,1)$ such that $f(b\_n)=1-\frac1n$. Let $$I\_n=\begin{cases}[a,b\_n],&\text{if }a<b\_n\\ [b\_n,a],&\text{if }b\_n<a\,;\end{cases}$$ clearly $f[I\_n]\supseteq\left[0,1-\frac1n\right]$. The sequence $\langle b\_n:n\ge 2\rangle$ has a convergent subsequence; let $c$ be the limit of this subsequence, and let
$$I=\begin{cases}
[a,c),&\text{if }a<c\\
(c,a],&\text{if }c<a\,.
\end{cases}$$
What can you say about $f[I]$?
|
$[0,1]$ is compact but the other two are not. Hence none of them are homeomorphic to $[0,1]$.
Now to show that $(0,1)$ and $[0,1)$ are not homeomorphic.
Suppose $f:[0,1)\to(0,1)$ is a homomorphism.
Then $f(0)\in (0,1)$ so $(0,1)\setminus \{f(0)\}$ is a disconnected set.
But $f((0,1))=(0,1)\setminus \{f(0)\}$, which is not possible as the continuous image of a connected set is connected .
|
3,778,961 |
I need to show $(0,1)$, $[0,1)$ and $[0,1]$ are not homeomorphic using intermediate value theorem (without using connectedness).
I have already did proved that $(0,1)$, $[0,1]$ are not homeomorphic but I struggle with the 2 other couples.
My proof: assume there is an homeomorphism $f:(0,1)\rightarrow[0,1]$ and take $a,b$ such that $f(a)=0, f(b)=1$. So using intermediate value theorem we can say that $f([a,b]) = [0,1]$. so $f$ isn't injective.
Will appreciate any help
|
2020/08/03
|
['https://math.stackexchange.com/questions/3778961', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/813552/']
|
Suppose $f:(0,1)\to [0,1)$ is a homeomorphism.
Then $\exists x\in(0,1)$ such that $f(x)=0$. By continuity for every $\epsilon >0$, $ \exists y<x<z$ such that $\{f(y),f(z)\}\subset[0,\epsilon)$.
Without loss of generality assume that $f(y)<f(z)$.
Now by intermediate value property of $f$, we have $f$ on $(x,z)$ attains all the values in $(f(x),f(z))$. So there exists $z\_0\in (x,z)$ such that $f(z\_0)=f(y)$.
Contradicts the fact that $f$ is one-one.
|
$[0,1]$ is compact but the other two are not. Hence none of them are homeomorphic to $[0,1]$.
Now to show that $(0,1)$ and $[0,1)$ are not homeomorphic.
Suppose $f:[0,1)\to(0,1)$ is a homomorphism.
Then $f(0)\in (0,1)$ so $(0,1)\setminus \{f(0)\}$ is a disconnected set.
But $f((0,1))=(0,1)\setminus \{f(0)\}$, which is not possible as the continuous image of a connected set is connected .
|
3,778,961 |
I need to show $(0,1)$, $[0,1)$ and $[0,1]$ are not homeomorphic using intermediate value theorem (without using connectedness).
I have already did proved that $(0,1)$, $[0,1]$ are not homeomorphic but I struggle with the 2 other couples.
My proof: assume there is an homeomorphism $f:(0,1)\rightarrow[0,1]$ and take $a,b$ such that $f(a)=0, f(b)=1$. So using intermediate value theorem we can say that $f([a,b]) = [0,1]$. so $f$ isn't injective.
Will appreciate any help
|
2020/08/03
|
['https://math.stackexchange.com/questions/3778961', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/813552/']
|
You have to be a little more careful: you’ve written your argument on the assumption that $a<b$, but it could be that $b<a$, in which case it’s the interval $[b,a]$ that maps to $[0,1]$. You get the same contradiction, of course.
HINT: The same argument works if the domain of $f$ is $[0,1)$. For $(0,1)$ and $[0,1)$ you have to work a little harder, but you can still use the same idea. Suppose that $f:(0,1)\to[0,1)$ is a homeomorphism. There is an $a\in(0,1)$ such that $f(a)=0$, and for each $n\ge 2$ there is a $b\_n\in(0,1)$ such that $f(b\_n)=1-\frac1n$. Let $$I\_n=\begin{cases}[a,b\_n],&\text{if }a<b\_n\\ [b\_n,a],&\text{if }b\_n<a\,;\end{cases}$$ clearly $f[I\_n]\supseteq\left[0,1-\frac1n\right]$. The sequence $\langle b\_n:n\ge 2\rangle$ has a convergent subsequence; let $c$ be the limit of this subsequence, and let
$$I=\begin{cases}
[a,c),&\text{if }a<c\\
(c,a],&\text{if }c<a\,.
\end{cases}$$
What can you say about $f[I]$?
|
Observe that if $\;f:X\to Y\;$ is a homeomorphism between two toplogical spaces and $\;x\in X\;$ then
$$\;g:X\setminus\{x\}\to Y\setminus\{f(x)\}\;,\;\;g(a)=f(a)\;\;\forall\;a\in X\setminus\{x\}\;$$
is also a homeomorphism on the respective top. spaces with the induced topology, and thus: if
$$f:[0,1)\to(0,1)\;\;\text{is a homeomorphism, then}\;\;g:(0,1)\to[(0,1)\setminus\{f(0)\}$$
is also a homeomorhpism. but this can't be since $\;(0,1)\;$ is (path) connected whereas $\;[(0,1)\setminus\{f(0)\}\;$ isn't.
Complete the other pair now (there you have path connectedness if you don't want connectedness...I don't understand why, but whatever)
|
3,778,961 |
I need to show $(0,1)$, $[0,1)$ and $[0,1]$ are not homeomorphic using intermediate value theorem (without using connectedness).
I have already did proved that $(0,1)$, $[0,1]$ are not homeomorphic but I struggle with the 2 other couples.
My proof: assume there is an homeomorphism $f:(0,1)\rightarrow[0,1]$ and take $a,b$ such that $f(a)=0, f(b)=1$. So using intermediate value theorem we can say that $f([a,b]) = [0,1]$. so $f$ isn't injective.
Will appreciate any help
|
2020/08/03
|
['https://math.stackexchange.com/questions/3778961', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/813552/']
|
Suppose $f:(0,1)\to [0,1)$ is a homeomorphism.
Then $\exists x\in(0,1)$ such that $f(x)=0$. By continuity for every $\epsilon >0$, $ \exists y<x<z$ such that $\{f(y),f(z)\}\subset[0,\epsilon)$.
Without loss of generality assume that $f(y)<f(z)$.
Now by intermediate value property of $f$, we have $f$ on $(x,z)$ attains all the values in $(f(x),f(z))$. So there exists $z\_0\in (x,z)$ such that $f(z\_0)=f(y)$.
Contradicts the fact that $f$ is one-one.
|
Observe that if $\;f:X\to Y\;$ is a homeomorphism between two toplogical spaces and $\;x\in X\;$ then
$$\;g:X\setminus\{x\}\to Y\setminus\{f(x)\}\;,\;\;g(a)=f(a)\;\;\forall\;a\in X\setminus\{x\}\;$$
is also a homeomorphism on the respective top. spaces with the induced topology, and thus: if
$$f:[0,1)\to(0,1)\;\;\text{is a homeomorphism, then}\;\;g:(0,1)\to[(0,1)\setminus\{f(0)\}$$
is also a homeomorhpism. but this can't be since $\;(0,1)\;$ is (path) connected whereas $\;[(0,1)\setminus\{f(0)\}\;$ isn't.
Complete the other pair now (there you have path connectedness if you don't want connectedness...I don't understand why, but whatever)
|
3,778,961 |
I need to show $(0,1)$, $[0,1)$ and $[0,1]$ are not homeomorphic using intermediate value theorem (without using connectedness).
I have already did proved that $(0,1)$, $[0,1]$ are not homeomorphic but I struggle with the 2 other couples.
My proof: assume there is an homeomorphism $f:(0,1)\rightarrow[0,1]$ and take $a,b$ such that $f(a)=0, f(b)=1$. So using intermediate value theorem we can say that $f([a,b]) = [0,1]$. so $f$ isn't injective.
Will appreciate any help
|
2020/08/03
|
['https://math.stackexchange.com/questions/3778961', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/813552/']
|
You have to be a little more careful: you’ve written your argument on the assumption that $a<b$, but it could be that $b<a$, in which case it’s the interval $[b,a]$ that maps to $[0,1]$. You get the same contradiction, of course.
HINT: The same argument works if the domain of $f$ is $[0,1)$. For $(0,1)$ and $[0,1)$ you have to work a little harder, but you can still use the same idea. Suppose that $f:(0,1)\to[0,1)$ is a homeomorphism. There is an $a\in(0,1)$ such that $f(a)=0$, and for each $n\ge 2$ there is a $b\_n\in(0,1)$ such that $f(b\_n)=1-\frac1n$. Let $$I\_n=\begin{cases}[a,b\_n],&\text{if }a<b\_n\\ [b\_n,a],&\text{if }b\_n<a\,;\end{cases}$$ clearly $f[I\_n]\supseteq\left[0,1-\frac1n\right]$. The sequence $\langle b\_n:n\ge 2\rangle$ has a convergent subsequence; let $c$ be the limit of this subsequence, and let
$$I=\begin{cases}
[a,c),&\text{if }a<c\\
(c,a],&\text{if }c<a\,.
\end{cases}$$
What can you say about $f[I]$?
|
Suppose $f:(0,1)\to [0,1)$ is a homeomorphism.
Then $\exists x\in(0,1)$ such that $f(x)=0$. By continuity for every $\epsilon >0$, $ \exists y<x<z$ such that $\{f(y),f(z)\}\subset[0,\epsilon)$.
Without loss of generality assume that $f(y)<f(z)$.
Now by intermediate value property of $f$, we have $f$ on $(x,z)$ attains all the values in $(f(x),f(z))$. So there exists $z\_0\in (x,z)$ such that $f(z\_0)=f(y)$.
Contradicts the fact that $f$ is one-one.
|
62,405,675 |
I have a problem with generics in swift. Let's expose my code.
```
protocol FooProtocol {
associatedtype T
}
protocol Fooable { }
extension Int : Fooable { }
extension String: Fooable { }
class AnyFoo<T>: FooProtocol {
init<P: FooProtocol>(p: P) where P.T == T { }
}
class FooIntImpClass: FooProtocol {
typealias T = Int
}
class FooStringImpClass: FooProtocol {
typealias T = String
}
func createOne(isInt: Bool) -> AnyFoo<Fooable> {
if isInt {
let anyFoo = AnyFoo(p: FooIntImpClass())
return anyFoo
} else {
let anyFoo = AnyFoo(p: FooStringImpClass())
return anyFoo
}
}
func createTwo<F: Fooable>(isInt: Bool) -> AnyFoo<F> {
if isInt {
let anyFoo = AnyFoo(p: FooIntImpClass())
return anyFoo
} else {
let anyFoo = AnyFoo(p: FooStringImpClass())
return anyFoo
}
}
```
`createOne` got an error
>
> Cannot convert return expression of type 'AnyFoo' (aka 'AnyFoo') to return type 'AnyFoo'
>
>
>
`createTwo` got an error
>
> Cannot convert return expression of type 'AnyFoo' (aka 'AnyFoo') to return type 'AnyFoo'
>
>
>
Why is this happening. I'm returning the correct value.
And What is the difference with the `createOne` and `createTwo`
|
2020/06/16
|
['https://Stackoverflow.com/questions/62405675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6239013/']
|
EDIT to respond to the edit to the question:
`createTwo` doesn't work because you have the same misconception as I said in my original answer. `createTwo` decided on its own that `F` should be either `String` or `Int`, rather than "any type that conforms to `Fooable`".
For `createOne`, you have another common misconception. **Generic classes are invariant**. `AnyFoo<String>` is not a kind of `AnyFoo<Fooable>`. In fact, they are totally unrelated types! See [here](https://stackoverflow.com/questions/41976844/swift-generic-coercion-misunderstanding) for more details.
Basically, what you are trying to do violates type safety, and you redesign your APIs and pick another different approach.
---
Original answer (for initial revision of question)
You seem to be having a common misconception of generics. **Generic parameters are decided by the caller, not the callee.**
In `createOne`, you are returning `anyFoo`, which is of type `AnyFoo<Int>`, not `AnyFoo<P>`. The method (callee) have decided, on its own, that `P` should be `Int`. This shouldn't happen, because the *caller* decides what generic parameters should be. If the callee is generic, it must be able to work with *any* type (within constraints). Anyway, `P` can't be `Int` here anyway, since `P: FooProtocol`.
Your `createOne` method should not be generic at all, as it only works with `Int`:
```
func createOne() -> AnyFoo<Int> {
let anyFoo = AnyFoo(p: FooImpClass())
return anyFoo
}
```
|
Is the following what you tried to achieve? (compiled & tested with Xcode 11.4)
```
func createOne() -> some FooProtocol {
let anyFoo = AnyFoo(p: FooImpClass())
return anyFoo
}
```
|
62,405,675 |
I have a problem with generics in swift. Let's expose my code.
```
protocol FooProtocol {
associatedtype T
}
protocol Fooable { }
extension Int : Fooable { }
extension String: Fooable { }
class AnyFoo<T>: FooProtocol {
init<P: FooProtocol>(p: P) where P.T == T { }
}
class FooIntImpClass: FooProtocol {
typealias T = Int
}
class FooStringImpClass: FooProtocol {
typealias T = String
}
func createOne(isInt: Bool) -> AnyFoo<Fooable> {
if isInt {
let anyFoo = AnyFoo(p: FooIntImpClass())
return anyFoo
} else {
let anyFoo = AnyFoo(p: FooStringImpClass())
return anyFoo
}
}
func createTwo<F: Fooable>(isInt: Bool) -> AnyFoo<F> {
if isInt {
let anyFoo = AnyFoo(p: FooIntImpClass())
return anyFoo
} else {
let anyFoo = AnyFoo(p: FooStringImpClass())
return anyFoo
}
}
```
`createOne` got an error
>
> Cannot convert return expression of type 'AnyFoo' (aka 'AnyFoo') to return type 'AnyFoo'
>
>
>
`createTwo` got an error
>
> Cannot convert return expression of type 'AnyFoo' (aka 'AnyFoo') to return type 'AnyFoo'
>
>
>
Why is this happening. I'm returning the correct value.
And What is the difference with the `createOne` and `createTwo`
|
2020/06/16
|
['https://Stackoverflow.com/questions/62405675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6239013/']
|
EDIT to respond to the edit to the question:
`createTwo` doesn't work because you have the same misconception as I said in my original answer. `createTwo` decided on its own that `F` should be either `String` or `Int`, rather than "any type that conforms to `Fooable`".
For `createOne`, you have another common misconception. **Generic classes are invariant**. `AnyFoo<String>` is not a kind of `AnyFoo<Fooable>`. In fact, they are totally unrelated types! See [here](https://stackoverflow.com/questions/41976844/swift-generic-coercion-misunderstanding) for more details.
Basically, what you are trying to do violates type safety, and you redesign your APIs and pick another different approach.
---
Original answer (for initial revision of question)
You seem to be having a common misconception of generics. **Generic parameters are decided by the caller, not the callee.**
In `createOne`, you are returning `anyFoo`, which is of type `AnyFoo<Int>`, not `AnyFoo<P>`. The method (callee) have decided, on its own, that `P` should be `Int`. This shouldn't happen, because the *caller* decides what generic parameters should be. If the callee is generic, it must be able to work with *any* type (within constraints). Anyway, `P` can't be `Int` here anyway, since `P: FooProtocol`.
Your `createOne` method should not be generic at all, as it only works with `Int`:
```
func createOne() -> AnyFoo<Int> {
let anyFoo = AnyFoo(p: FooImpClass())
return anyFoo
}
```
|
**EDIT**
I finally managed to keep your `where clause` :)
**EDIT**
Still not sure what you want to do, and I still agree with @Sweeper but I love to badly abuse generics :) :
```
protocol FooProtocol {
associatedtype T
init()
}
protocol Fooable { }
extension Int : Fooable { }
extension String: Fooable { }
class AnyFoo<T>: FooProtocol {
init<P: FooProtocol>(p: P) where P.T == T { }
init<T>(p: T.Type) { }
required init() { }
}
class FooIntImpClass: FooProtocol {
typealias T = Int
required init() { }
}
class FooStringImpClass: FooProtocol {
typealias T = String
required init() { }
}
func createOne<F: FooProtocol>(foo: F.Type) -> AnyFoo<F.T> {
let anyFoo = AnyFoo<F.T>(p: F.init())
return anyFoo
}
func createTwo<F: FooProtocol>(foo: F.Type) -> some FooProtocol {
let anyFoo = AnyFoo<F.T>(pk: F.T.self)
return anyFoo
}
```
that compiles but I don't know what to do with it.
**Edit**
yeah I really don't know:
```
let one = createOne(foo: FooStringImpClass.self) // AnyFoo<String>
print(type(of: one).T) // "String\n"
let two = createTwo(foo: FooIntImpClass.self) // AnyFoo<Int>
print(type(of: two).T) // "Int\n"
```
**Is that what you wanted ?**
---
I'm not sure what you want to do with that, but I suggest you try putting a `where` clause on the `AnyFoo` class instead of it's initializer.
And I should add, that your where clause on the initializer was wrong, Like [Sweeper](https://stackoverflow.com/a/62406002/1425697) said :
>
> Anyway, P can't be Int here anyway, since P: FooProtocol.
>
>
>
The following code compiles :
```
protocol FooProtocol {
associatedtype T
}
class AnyFoo<T>: FooProtocol where T: FooProtocol {
init<P: FooProtocol>(p: P) { }
}
class FooImpClass: FooProtocol {
typealias T = Int
}
func createOne<P: FooProtocol>() -> AnyFoo<P> {
let anyFoo: AnyFoo<P> = AnyFoo(p: FooImpClass())
return anyFoo
}
```
|
62,405,675 |
I have a problem with generics in swift. Let's expose my code.
```
protocol FooProtocol {
associatedtype T
}
protocol Fooable { }
extension Int : Fooable { }
extension String: Fooable { }
class AnyFoo<T>: FooProtocol {
init<P: FooProtocol>(p: P) where P.T == T { }
}
class FooIntImpClass: FooProtocol {
typealias T = Int
}
class FooStringImpClass: FooProtocol {
typealias T = String
}
func createOne(isInt: Bool) -> AnyFoo<Fooable> {
if isInt {
let anyFoo = AnyFoo(p: FooIntImpClass())
return anyFoo
} else {
let anyFoo = AnyFoo(p: FooStringImpClass())
return anyFoo
}
}
func createTwo<F: Fooable>(isInt: Bool) -> AnyFoo<F> {
if isInt {
let anyFoo = AnyFoo(p: FooIntImpClass())
return anyFoo
} else {
let anyFoo = AnyFoo(p: FooStringImpClass())
return anyFoo
}
}
```
`createOne` got an error
>
> Cannot convert return expression of type 'AnyFoo' (aka 'AnyFoo') to return type 'AnyFoo'
>
>
>
`createTwo` got an error
>
> Cannot convert return expression of type 'AnyFoo' (aka 'AnyFoo') to return type 'AnyFoo'
>
>
>
Why is this happening. I'm returning the correct value.
And What is the difference with the `createOne` and `createTwo`
|
2020/06/16
|
['https://Stackoverflow.com/questions/62405675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6239013/']
|
Is the following what you tried to achieve? (compiled & tested with Xcode 11.4)
```
func createOne() -> some FooProtocol {
let anyFoo = AnyFoo(p: FooImpClass())
return anyFoo
}
```
|
**EDIT**
I finally managed to keep your `where clause` :)
**EDIT**
Still not sure what you want to do, and I still agree with @Sweeper but I love to badly abuse generics :) :
```
protocol FooProtocol {
associatedtype T
init()
}
protocol Fooable { }
extension Int : Fooable { }
extension String: Fooable { }
class AnyFoo<T>: FooProtocol {
init<P: FooProtocol>(p: P) where P.T == T { }
init<T>(p: T.Type) { }
required init() { }
}
class FooIntImpClass: FooProtocol {
typealias T = Int
required init() { }
}
class FooStringImpClass: FooProtocol {
typealias T = String
required init() { }
}
func createOne<F: FooProtocol>(foo: F.Type) -> AnyFoo<F.T> {
let anyFoo = AnyFoo<F.T>(p: F.init())
return anyFoo
}
func createTwo<F: FooProtocol>(foo: F.Type) -> some FooProtocol {
let anyFoo = AnyFoo<F.T>(pk: F.T.self)
return anyFoo
}
```
that compiles but I don't know what to do with it.
**Edit**
yeah I really don't know:
```
let one = createOne(foo: FooStringImpClass.self) // AnyFoo<String>
print(type(of: one).T) // "String\n"
let two = createTwo(foo: FooIntImpClass.self) // AnyFoo<Int>
print(type(of: two).T) // "Int\n"
```
**Is that what you wanted ?**
---
I'm not sure what you want to do with that, but I suggest you try putting a `where` clause on the `AnyFoo` class instead of it's initializer.
And I should add, that your where clause on the initializer was wrong, Like [Sweeper](https://stackoverflow.com/a/62406002/1425697) said :
>
> Anyway, P can't be Int here anyway, since P: FooProtocol.
>
>
>
The following code compiles :
```
protocol FooProtocol {
associatedtype T
}
class AnyFoo<T>: FooProtocol where T: FooProtocol {
init<P: FooProtocol>(p: P) { }
}
class FooImpClass: FooProtocol {
typealias T = Int
}
func createOne<P: FooProtocol>() -> AnyFoo<P> {
let anyFoo: AnyFoo<P> = AnyFoo(p: FooImpClass())
return anyFoo
}
```
|
52,306,898 |
I’m learning Common Lisp, using CCL.
I get a warning when I use a global variable locally. Why does CCL provide this functionality? What is the purpose of this?
```
(setf n 75)
;;;This function works, but gets a warning about
;;;n being an undeclared free variable.
(defun use-global ()
(write n)
)
;;;This function works without warnings.
(defun global-to-local (x)
(write x)
)
(use-global)
(global-to-local n)
```
|
2018/09/13
|
['https://Stackoverflow.com/questions/52306898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10305445/']
|
`Setf` and `setq` do not introduce new variables, they modify existing ones.
In order to define something like global variables, use `defvar` or `defparameter`. These are conventionally written with a leading and ending `*`, and they are automatically declared *globally special*. This means that whenever you re-bind them, this binding is in effect for the entire call stack above it, whatever functions you call from there etc..
In your example, the toplevel `setf` did not do that, so when compiling the function `use-global`, the compiler does not see that `n` is meant as such and issues the warning. In correct and idiomatic Common Lisp code, this warning should generally be treated as an error, since it then indicates a misspelling or typo.
|
Quick googling suggests in Common Lisp is it done as something like:
```
(defvar *n* 75)
(defun use-global () (write *n*))
(use-global)
```
Note the asterisk that decorate global names by convention.
|
52,306,898 |
I’m learning Common Lisp, using CCL.
I get a warning when I use a global variable locally. Why does CCL provide this functionality? What is the purpose of this?
```
(setf n 75)
;;;This function works, but gets a warning about
;;;n being an undeclared free variable.
(defun use-global ()
(write n)
)
;;;This function works without warnings.
(defun global-to-local (x)
(write x)
)
(use-global)
(global-to-local n)
```
|
2018/09/13
|
['https://Stackoverflow.com/questions/52306898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10305445/']
|
The warning provides little value. The variable is bound by a prior top-level assignment, which creates a binding in the [global environment](http://clhs.lisp.se/Body/26_glo_g.htm#global_environment) making that variable a global variable. It simply being accessed, which is likely what is intended by the programmer.
An unbound variable warning is very valuable when no definition of a variable is seen because it catches misspellings of variable references. But a top-level `setf` or `setq` should be noticed by the implementation and treated as a definition.
It is useful to have a warning for cases when a variable is defined by a top-level `setf` and then later subject to a `let`:
```
(setf n 42)
(let ((n 43)) (func))
```
Here, it looks like the programmer might be expecting `n` to be a special variable, but it wasn't defined that way. `func` will see the top level binding of `n` which holds 42, and not the lexical `n` which holds 43. So there is a good reason to have a diagnostic here. The intent of the code requires `n` to have been declared via `defvar` or `defparameter`, or proclaimed special.
(Of course, we cannot warn about `(let ((n 43)) ...)` when no top-level `n` has been seen, because this is the usual situation for the vast majority of lexical variables.)
There is a bit of a defect in ANSI Common Lisp in that the section *[3.1.2.1.1 Symbols as Forms](http://clhs.lisp.se/Body/03_abaa.htm)* says that there are only three kinds of variables: dynamic, lexical and constant. A dynamic variable is one that is declared special, and so according to this reasoning, `setf` is not enough to create a dynamic variable. However, section [3.1.1.1](http://clhs.lisp.se/Body/03_aaa.htm) clearly spells out that there exists a global environment. Confusingly, it says that it contains bindings that have indefinite extent and scope, and that it contains dynamic variables. But then "dynamic variable" is defined in the glossary as being a variable with a binding in the dynamic environment, and a dynamic environment is defined as containing bindings with "dynamic extent". So that can't be the global environment. You know, that one which 3.1.1.1 says contains dynamic variables!
Anyway, all this ANSI confusion has created the misconception that `setf` or `setq` cannot create a variable, which lends support to bogus compiler diagnostics.
|
Quick googling suggests in Common Lisp is it done as something like:
```
(defvar *n* 75)
(defun use-global () (write *n*))
(use-global)
```
Note the asterisk that decorate global names by convention.
|
52,306,898 |
I’m learning Common Lisp, using CCL.
I get a warning when I use a global variable locally. Why does CCL provide this functionality? What is the purpose of this?
```
(setf n 75)
;;;This function works, but gets a warning about
;;;n being an undeclared free variable.
(defun use-global ()
(write n)
)
;;;This function works without warnings.
(defun global-to-local (x)
(write x)
)
(use-global)
(global-to-local n)
```
|
2018/09/13
|
['https://Stackoverflow.com/questions/52306898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10305445/']
|
`Setf` and `setq` do not introduce new variables, they modify existing ones.
In order to define something like global variables, use `defvar` or `defparameter`. These are conventionally written with a leading and ending `*`, and they are automatically declared *globally special*. This means that whenever you re-bind them, this binding is in effect for the entire call stack above it, whatever functions you call from there etc..
In your example, the toplevel `setf` did not do that, so when compiling the function `use-global`, the compiler does not see that `n` is meant as such and issues the warning. In correct and idiomatic Common Lisp code, this warning should generally be treated as an error, since it then indicates a misspelling or typo.
|
The warning provides little value. The variable is bound by a prior top-level assignment, which creates a binding in the [global environment](http://clhs.lisp.se/Body/26_glo_g.htm#global_environment) making that variable a global variable. It simply being accessed, which is likely what is intended by the programmer.
An unbound variable warning is very valuable when no definition of a variable is seen because it catches misspellings of variable references. But a top-level `setf` or `setq` should be noticed by the implementation and treated as a definition.
It is useful to have a warning for cases when a variable is defined by a top-level `setf` and then later subject to a `let`:
```
(setf n 42)
(let ((n 43)) (func))
```
Here, it looks like the programmer might be expecting `n` to be a special variable, but it wasn't defined that way. `func` will see the top level binding of `n` which holds 42, and not the lexical `n` which holds 43. So there is a good reason to have a diagnostic here. The intent of the code requires `n` to have been declared via `defvar` or `defparameter`, or proclaimed special.
(Of course, we cannot warn about `(let ((n 43)) ...)` when no top-level `n` has been seen, because this is the usual situation for the vast majority of lexical variables.)
There is a bit of a defect in ANSI Common Lisp in that the section *[3.1.2.1.1 Symbols as Forms](http://clhs.lisp.se/Body/03_abaa.htm)* says that there are only three kinds of variables: dynamic, lexical and constant. A dynamic variable is one that is declared special, and so according to this reasoning, `setf` is not enough to create a dynamic variable. However, section [3.1.1.1](http://clhs.lisp.se/Body/03_aaa.htm) clearly spells out that there exists a global environment. Confusingly, it says that it contains bindings that have indefinite extent and scope, and that it contains dynamic variables. But then "dynamic variable" is defined in the glossary as being a variable with a binding in the dynamic environment, and a dynamic environment is defined as containing bindings with "dynamic extent". So that can't be the global environment. You know, that one which 3.1.1.1 says contains dynamic variables!
Anyway, all this ANSI confusion has created the misconception that `setf` or `setq` cannot create a variable, which lends support to bogus compiler diagnostics.
|
1,401,673 |
I was using Bash as my default shell on macOS but I decided to switch to Fish.
I am trying to switch between different versions of Java. In bash it was done using the `~/.bash_profile`
```
export JAVA_HOME=`/usr/libexec/java_home -v 1.7`
```
I have set the equivalent on Fish `~/.config/fish/fish_variables`
```
set -x JAVA_HOME `/usr/libexec/java_home -v 1.7`
```
Unfortunately, Java version is not being changed. How can I set environment variables (specific version of Java, in particular) using `~/.config/fish/fish_variables`?
### UPDATE:
According to the [FAQ](https://fishshell.com/docs/2.2/faq.html), instead of `~/.config/fish/fish_variables`, `~/.config/fish/config.fish` should be used. Also I created `~/.config/fish/fish.config` instead of `~/.config/fish/config.fish`.
|
2019/02/03
|
['https://superuser.com/questions/1401673', 'https://superuser.com', 'https://superuser.com/users/806634/']
|
While I am not deeply familiar with [Fish](https://fishshell.com), based on what I am reading it seems like the issue is with the backticks in your command:
```
/usr/libexec/java_home -v 1.7
```
You see that is just like this in Bash:
```
$(/usr/libexec/java_home -v 1.7)
```
Keep that in mind and look at [this Fish FAQ entry](https://fishshell.com/docs/current/faq.html#faq-subcommand):
>
> ### How do I run a subcommand? The backtick doesn't work!
>
>
> fish uses parentheses for subcommands. For example:
>
>
>
> ```
> for i in (ls)
> echo $i
> end
>
> ```
>
>
Knowing that the config line should most likely be:
```
set -x JAVA_HOME (/usr/libexec/java_home -v 1.7)
```
|
```
function javaenv
if test (count $argv) -eq 0
/usr/libexec/java_home -V
else
switch $argv[1]
case 'ls'
/usr/libexec/java_home -V
case 'set'
set -xU JAVA_HOME (/usr/libexec/java_home -v $argv[2])
end
end
end
```
Can put the function above in ~/.config/fish/functions and use it to get the java\_home contents with
```
javaenv
```
and set the contents of java\_home with
```
javaenv set 1.8
```
Idea and contents taken from [here](https://medium.com/@axross/simple-javaenv-with-fish-shell-287ba4a84ba9)
|
41,505,915 |
In C#, I made a textbox that accept only numbers, but I want to make a code to accept a time in the following format: "\_\_\_\_:\_\_\_\_:\_\_\_\_" so that when the user writes part of it, it completes the missing with zeros;
Example:
The user writes: "\_2:12:\_3" it should complete it as "02:12:03".
Does anybody have this code?
|
2017/01/06
|
['https://Stackoverflow.com/questions/41505915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7383939/']
|
I think the best would be to use the Replace() function in C# as follow:
```
string x = "this is an example of a string with a _ character";
string z = x.Replace('_', '0');
```
|
```
private void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
{
int value = int.Parse(YourTextBox.Text);
if (value<10)
{
YourTextBox.Text = "0" + value;
}
}
```
and Ofcourse you can add other logic like if the user enters more than 60 for the minutes textbox the text should be replaced with an empty string
|
37,952,883 |
So right now I'm making an interactive graph in excel, where the user can select a variety of options via drop down menus. For example, if the user wants to change the color of one of the charts to red, they select the drop down menu for that chart, select red, and then the chart turns red. I've written macros to do this, but it composes of multiple if statements for each color. Is there a good way to cut down on all of these if statements? Current code works and is below. F16 is the where the drop down menu is in excel that indicates what color will change. also am using excel 2010
```
If Target = Range("F16") Then
'Checks to see if the color is being changed for the Elevation Graph
If Worksheets("Reference_Sheet").Range("H9").Value = "Black" Then
Call Black_Line_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Tan" Then
Call Tan_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Dark Blue" Then
Call Dark_Blue_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Yellow" Then
Call Yellow_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Olive Green" Then
Call Olive_Green_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Light Green" Then
Call Light_Green_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Green" Then
Call Green_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Light Blue" Then
Call Light_Blue_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Aqua" Then
Call Aqua_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Orange" Then
Call Theme_Orange_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Orange" Then
Call Standard_Orange_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Purple" Then
Call Standard_Purple_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Purple" Then
Call Theme_Purple_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Blue" Then
Call Theme_Blue_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Blue" Then
Call Standard_Blue_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Red" Then
Call Standard_Red_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Red" Then
Call Theme_Red_ELE
End if
End if
```
|
2016/06/21
|
['https://Stackoverflow.com/questions/37952883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6495811/']
|
Time for some mapping! Reference the VBScript runtime and create a new `Scripting.Dictionary` object.
```
Dim colorActions As Dictionary
Set colorActions = New Dictionary
```
Or, don't reference the VBScript runtime and use late-binding to create the dictionary instead:
```
Dim colorActions As Object
Set colorActions = CreateObject("Scripting.Dictionary")
```
---
Next, map each value to a string representing the name of the procedure you want to run:
```
With colorActions
.Add "Black", "Black_Line_ELE"
.Add "Tan", "Tan_ELE"
.Add "Dark Blue", "Dark_Blue_ELE"
'...
.Add "Theme Red", "Theme_Red_ELE"
End With
```
I would make the `colorActions` dictionary live at module-level, and then put the code to populate it at startup - doing that in the `SheetChanged` handler would be doing much more work than needed, for no reason: you don't need to recreate it everytime `F16` changes!
Now assuming these methods are all public subs, you can use `Application.Run` to execute the named procedure mapped to the value of `H9`:
```
Dim key As String
key = Worksheets("Reference_Sheet").Range("H9").Value
If colorActions.Exists(key) Then
Application.Run colorActions(key)
Else
MsgBox "Not supported."
End If
```
This will scale much better than a `Select Case` block, and makes only 1 single place that actually executes something. And when you need to add a supported color/method, you just add a dictionary entry and you're done.
That said `Call` is useless clutter, you can safely omit it.
---
I also suspect that all these separate methods are really all doing the same thing and could all be removed and replaced with a single parameterized version - but there's no way of telling for sure without seeing your actual code... if you **really** want to clean up your code, bring it to [**Code Review**](http://codereview.stackexchange.com) and give as much context code as possible!
|
As @findwindow has stated in the comments, you may benefit from a `Select` statement. Consider the example below: -
```
If Target = Range("F16") Then
'Checks to see if the color is being changed for the Elevation Graph
Select Case Worksheets("Reference_Sheet").Range("H9").Value
Case "Black"
Call Black_Line_ELE
Case "Tan"
Call Tan_ELE
'... [Your other options] ...
End Select
End if
```
|
37,952,883 |
So right now I'm making an interactive graph in excel, where the user can select a variety of options via drop down menus. For example, if the user wants to change the color of one of the charts to red, they select the drop down menu for that chart, select red, and then the chart turns red. I've written macros to do this, but it composes of multiple if statements for each color. Is there a good way to cut down on all of these if statements? Current code works and is below. F16 is the where the drop down menu is in excel that indicates what color will change. also am using excel 2010
```
If Target = Range("F16") Then
'Checks to see if the color is being changed for the Elevation Graph
If Worksheets("Reference_Sheet").Range("H9").Value = "Black" Then
Call Black_Line_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Tan" Then
Call Tan_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Dark Blue" Then
Call Dark_Blue_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Yellow" Then
Call Yellow_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Olive Green" Then
Call Olive_Green_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Light Green" Then
Call Light_Green_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Green" Then
Call Green_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Light Blue" Then
Call Light_Blue_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Aqua" Then
Call Aqua_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Orange" Then
Call Theme_Orange_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Orange" Then
Call Standard_Orange_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Purple" Then
Call Standard_Purple_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Purple" Then
Call Theme_Purple_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Blue" Then
Call Theme_Blue_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Blue" Then
Call Standard_Blue_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Red" Then
Call Standard_Red_ELE
ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Red" Then
Call Theme_Red_ELE
End if
End if
```
|
2016/06/21
|
['https://Stackoverflow.com/questions/37952883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6495811/']
|
Time for some mapping! Reference the VBScript runtime and create a new `Scripting.Dictionary` object.
```
Dim colorActions As Dictionary
Set colorActions = New Dictionary
```
Or, don't reference the VBScript runtime and use late-binding to create the dictionary instead:
```
Dim colorActions As Object
Set colorActions = CreateObject("Scripting.Dictionary")
```
---
Next, map each value to a string representing the name of the procedure you want to run:
```
With colorActions
.Add "Black", "Black_Line_ELE"
.Add "Tan", "Tan_ELE"
.Add "Dark Blue", "Dark_Blue_ELE"
'...
.Add "Theme Red", "Theme_Red_ELE"
End With
```
I would make the `colorActions` dictionary live at module-level, and then put the code to populate it at startup - doing that in the `SheetChanged` handler would be doing much more work than needed, for no reason: you don't need to recreate it everytime `F16` changes!
Now assuming these methods are all public subs, you can use `Application.Run` to execute the named procedure mapped to the value of `H9`:
```
Dim key As String
key = Worksheets("Reference_Sheet").Range("H9").Value
If colorActions.Exists(key) Then
Application.Run colorActions(key)
Else
MsgBox "Not supported."
End If
```
This will scale much better than a `Select Case` block, and makes only 1 single place that actually executes something. And when you need to add a supported color/method, you just add a dictionary entry and you're done.
That said `Call` is useless clutter, you can safely omit it.
---
I also suspect that all these separate methods are really all doing the same thing and could all be removed and replaced with a single parameterized version - but there's no way of telling for sure without seeing your actual code... if you **really** want to clean up your code, bring it to [**Code Review**](http://codereview.stackexchange.com) and give as much context code as possible!
|
```
If Target = Range("F16") Then
Select Case Worksheets("Reference_Sheet").Range("H9").Value
Case "Black"
Call Black_Line_ELE
Case "Tan"
Call Tan_ELE
Case 'Do this for all cases
End Select
End If
```
[Look here for more details](https://msdn.microsoft.com/en-gb/library/cy37t14y.aspx)
Should make the structure of your code clearer.
|
25,931,781 |
I have to implement a search in following method,
Let :
```
Dim checkin As String = "This is the base string, i have to find a word here"
Dim valueSearch As String="to find a word"
```
Now the algorithm to be implemented is:
* Dim str() As String = Split(checkin , " ")
* Dim Position As Integer
* `Position`=Find Position of `str(0)` in the string
* Check `str(1)` with the next word after `position`th word in `checkin`
* if not equal continue the second step with `str(1)`
* `if Dim valueSearch As String="to find a game" then`
i have to display a message that `"to find a"` is present
My question is that is it possible to find the position of a word in a string using
[string.Contains()](http://vb.net-informations.com/string/vb.net_String_Contains.htm) operation. or any other possibility to implement this algorithm?
|
2014/09/19
|
['https://Stackoverflow.com/questions/25931781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
I made a Ribbon.xml for every addin, that has the same structure.
I've set a "namespace" in every ribbon.xml, that will help the controls to be added to the same tab, everytime.
```
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load" xmlns:x="NAMESPACE FOR EVERY TAB"> //the namespaces abreviation is "x"
<ribbon>
<tabs>
<tab idQ="x:tab1" label="CommonTab" >
....
```
Then I set the tabs idQ with the "x:" prefix so it will know the namespace. From every add-in that uses the same xml structure, the controls from the tab will be added to a single tab.
|
We use [Add In Express](http://www.add-in-express.com/) at our work place. It's really easy to use and does everything. It's paid though.
Also please look at [this](https://stackoverflow.com/questions/7135480/office-add-in-ribbons-same-tab-with-2-addins) answer.
|
64,066,995 |
Essentially when the browser window goes larger thh div stays centered and creates white space on the outside. I want the same thing to happen when the browser window goes smaller. I want to see less of the div but keep it centered. At the moment I see less of the div but the left side locks so I end up only seeing a slither of the left part of the image (instead of the center). Sorry if this is a convoluted way of asking I am new to programming. Any help would be massively appreciated! Thanks in advance! :)
p.s I am also struggling to have the video playing if anyone can help with that too
Here is my code currently
```css
body {
font-family: 'Noto Sans', sans-serif;
margin: 0;
padding: 0;
}
#page-container {
width: 1920px;
margin: auto;
}
```
```html
<div id="page-container">
<video id="backgroundvid" width="auto" autoplay>
<source src="assets/video/portalAnimLowRes.mp4" type="video/mp4">
</video>
</div>
```
|
2020/09/25
|
['https://Stackoverflow.com/questions/64066995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14341030/']
|
You can try
```
#page-container {
width:1920px;
margin-left: -960px;
position: relative;
left: 50%;
}
```
|
You can put the pageContainer on `absolute` position as follows.
```
#page-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 1920px;
}
```
|
64,066,995 |
Essentially when the browser window goes larger thh div stays centered and creates white space on the outside. I want the same thing to happen when the browser window goes smaller. I want to see less of the div but keep it centered. At the moment I see less of the div but the left side locks so I end up only seeing a slither of the left part of the image (instead of the center). Sorry if this is a convoluted way of asking I am new to programming. Any help would be massively appreciated! Thanks in advance! :)
p.s I am also struggling to have the video playing if anyone can help with that too
Here is my code currently
```css
body {
font-family: 'Noto Sans', sans-serif;
margin: 0;
padding: 0;
}
#page-container {
width: 1920px;
margin: auto;
}
```
```html
<div id="page-container">
<video id="backgroundvid" width="auto" autoplay>
<source src="assets/video/portalAnimLowRes.mp4" type="video/mp4">
</video>
</div>
```
|
2020/09/25
|
['https://Stackoverflow.com/questions/64066995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14341030/']
|
You can try
```
#page-container {
width:1920px;
margin-left: -960px;
position: relative;
left: 50%;
}
```
|
What about use flexbox?
```css
body {
font-family: 'Noto Sans', sans-serif;
margin: 0;
padding: 0;
}
#page-container {
width: 1920px;
display: flex;
align-items: center;
justify-content: center;
}
```
```html
<div id="page-container">
<img src="https://placeimg.com/640/480/any">
</div>
```
|
64,066,995 |
Essentially when the browser window goes larger thh div stays centered and creates white space on the outside. I want the same thing to happen when the browser window goes smaller. I want to see less of the div but keep it centered. At the moment I see less of the div but the left side locks so I end up only seeing a slither of the left part of the image (instead of the center). Sorry if this is a convoluted way of asking I am new to programming. Any help would be massively appreciated! Thanks in advance! :)
p.s I am also struggling to have the video playing if anyone can help with that too
Here is my code currently
```css
body {
font-family: 'Noto Sans', sans-serif;
margin: 0;
padding: 0;
}
#page-container {
width: 1920px;
margin: auto;
}
```
```html
<div id="page-container">
<video id="backgroundvid" width="auto" autoplay>
<source src="assets/video/portalAnimLowRes.mp4" type="video/mp4">
</video>
</div>
```
|
2020/09/25
|
['https://Stackoverflow.com/questions/64066995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14341030/']
|
You can try
```
#page-container {
width:1920px;
margin-left: -960px;
position: relative;
left: 50%;
}
```
|
Do you really want the horizontal scroll bar?
If you don't, I prefer not to define the width(especially in pixel), as the width of every device varies.
Instead, you can define width as `width:100%` or `width:100vw`, this helps to fit the div according to the screen size.
You can try this code:
```
body {
font-family: 'Noto Sans', sans-serif;
margin: 0 auto;
padding: 0;
}
#page-container {
width: 100%;
margin: auto;
}
```
|
64,066,995 |
Essentially when the browser window goes larger thh div stays centered and creates white space on the outside. I want the same thing to happen when the browser window goes smaller. I want to see less of the div but keep it centered. At the moment I see less of the div but the left side locks so I end up only seeing a slither of the left part of the image (instead of the center). Sorry if this is a convoluted way of asking I am new to programming. Any help would be massively appreciated! Thanks in advance! :)
p.s I am also struggling to have the video playing if anyone can help with that too
Here is my code currently
```css
body {
font-family: 'Noto Sans', sans-serif;
margin: 0;
padding: 0;
}
#page-container {
width: 1920px;
margin: auto;
}
```
```html
<div id="page-container">
<video id="backgroundvid" width="auto" autoplay>
<source src="assets/video/portalAnimLowRes.mp4" type="video/mp4">
</video>
</div>
```
|
2020/09/25
|
['https://Stackoverflow.com/questions/64066995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14341030/']
|
You can put the pageContainer on `absolute` position as follows.
```
#page-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 1920px;
}
```
|
What about use flexbox?
```css
body {
font-family: 'Noto Sans', sans-serif;
margin: 0;
padding: 0;
}
#page-container {
width: 1920px;
display: flex;
align-items: center;
justify-content: center;
}
```
```html
<div id="page-container">
<img src="https://placeimg.com/640/480/any">
</div>
```
|
64,066,995 |
Essentially when the browser window goes larger thh div stays centered and creates white space on the outside. I want the same thing to happen when the browser window goes smaller. I want to see less of the div but keep it centered. At the moment I see less of the div but the left side locks so I end up only seeing a slither of the left part of the image (instead of the center). Sorry if this is a convoluted way of asking I am new to programming. Any help would be massively appreciated! Thanks in advance! :)
p.s I am also struggling to have the video playing if anyone can help with that too
Here is my code currently
```css
body {
font-family: 'Noto Sans', sans-serif;
margin: 0;
padding: 0;
}
#page-container {
width: 1920px;
margin: auto;
}
```
```html
<div id="page-container">
<video id="backgroundvid" width="auto" autoplay>
<source src="assets/video/portalAnimLowRes.mp4" type="video/mp4">
</video>
</div>
```
|
2020/09/25
|
['https://Stackoverflow.com/questions/64066995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14341030/']
|
Do you really want the horizontal scroll bar?
If you don't, I prefer not to define the width(especially in pixel), as the width of every device varies.
Instead, you can define width as `width:100%` or `width:100vw`, this helps to fit the div according to the screen size.
You can try this code:
```
body {
font-family: 'Noto Sans', sans-serif;
margin: 0 auto;
padding: 0;
}
#page-container {
width: 100%;
margin: auto;
}
```
|
What about use flexbox?
```css
body {
font-family: 'Noto Sans', sans-serif;
margin: 0;
padding: 0;
}
#page-container {
width: 1920px;
display: flex;
align-items: center;
justify-content: center;
}
```
```html
<div id="page-container">
<img src="https://placeimg.com/640/480/any">
</div>
```
|
7,195,248 |
What is the difference between NULL and character(0) | integer(0) etc?
```
> identical(NULL, character(0))
[1] FALSE
> is.null(integer(0))
[1] FALSE
> str(character(0))
chr(0)
> str(NULL)
NULL
```
In general it seems you can pass `NULL` as parameters into functions, and that an empty vector is generally returned as `character(0)`, `integer(0)`, etc.
Why is this the case? Come to think of it, is there a test for zero-ness, *a la* `is.integer0`?
|
2011/08/25
|
['https://Stackoverflow.com/questions/7195248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/602276/']
|
The [R Language Definitio](http://cran.r-project.org/doc/manuals/R-lang.html)n has this on `NULL`:
>
> There is a special object called NULL. It is used whenever there is a need to indicate or
> specify that an object is absent. It should not be confused with a vector or list of zero
> length. The NULL object has no type and no modifiable properties. There is only one NULL
> object in R, to which all instances refer. To test for NULL use is.null. You cannot set
> attributes on NULL.
>
>
>
So by definition `NULL` is very different to zero length vectors. A zero length vector very much **isn't** absent. `NULL` is really a catch-all for something that is absent or not set, but not missing-ness, which is the job of `NA`. There is an exception, the zero-length pairlist, as mentioned by @Owen. The Language Definition states:
>
> A zero-length pairlist is NULL, as would be expected in Lisp but in contrast to a zero-length list.
>
>
>
which highlights the exception in this case.
To test for a zero-length vector use something like `if(length(foo) == 0L)` for example. And combine that with a class check (`is.character(foo)`) if you want a specific type of zero length vector.
|
Here's a partial answer, beginning by simply quoting the R Language Definition Guide:
>
> There is a special object called NULL. It is used whenever there is a
> need to indicate or specify that an object is absent. It should not be
> confused with a vector or list of zero length. The NULL object has no
> type and no modifiable properties. There is only one NULL object in R,
> to which all instances refer. To test for NULL use is.null. You cannot
> set attributes on NULL.
>
>
>
I take that to mean that zero length vectors can have attributes, whereas `NULL` cannot:
```
> x <- character(0)
> y <- NULL
> attr(x,"name") <- "nm"
> attr(y,"name") <- "nm"
Error in attr(y, "name") <- "nm" : attempt to set an attribute on NULL
```
|
7,195,248 |
What is the difference between NULL and character(0) | integer(0) etc?
```
> identical(NULL, character(0))
[1] FALSE
> is.null(integer(0))
[1] FALSE
> str(character(0))
chr(0)
> str(NULL)
NULL
```
In general it seems you can pass `NULL` as parameters into functions, and that an empty vector is generally returned as `character(0)`, `integer(0)`, etc.
Why is this the case? Come to think of it, is there a test for zero-ness, *a la* `is.integer0`?
|
2011/08/25
|
['https://Stackoverflow.com/questions/7195248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/602276/']
|
The other guys have the right answers, but I want to add a few curiosities.
First, it's not *quite* true that NULL "is used whenever there is a need to indicate or specify that an object is absent" as it says in the doc. There are actually 2 other "no data" values in R (not counting NA, which is not a complete value).
There's "missing", which is used for missing arguments:
>
> alist(x=)$x
>
>
>
```
> identical(NULL, alist(x=)$x)
[1] FALSE
> y = alist(x=)$x
> y
Error: argument "y" is missing, with no default
```
Then there's "unbound", which you can't (AFAIK) access directly, but using C:
```
SEXP getUnbound(void) {
return R_UnboundValue;
}
> x = .Call("getUnbound")
> x
Error: object 'x' not found
```
|
Here's a partial answer, beginning by simply quoting the R Language Definition Guide:
>
> There is a special object called NULL. It is used whenever there is a
> need to indicate or specify that an object is absent. It should not be
> confused with a vector or list of zero length. The NULL object has no
> type and no modifiable properties. There is only one NULL object in R,
> to which all instances refer. To test for NULL use is.null. You cannot
> set attributes on NULL.
>
>
>
I take that to mean that zero length vectors can have attributes, whereas `NULL` cannot:
```
> x <- character(0)
> y <- NULL
> attr(x,"name") <- "nm"
> attr(y,"name") <- "nm"
Error in attr(y, "name") <- "nm" : attempt to set an attribute on NULL
```
|
7,195,248 |
What is the difference between NULL and character(0) | integer(0) etc?
```
> identical(NULL, character(0))
[1] FALSE
> is.null(integer(0))
[1] FALSE
> str(character(0))
chr(0)
> str(NULL)
NULL
```
In general it seems you can pass `NULL` as parameters into functions, and that an empty vector is generally returned as `character(0)`, `integer(0)`, etc.
Why is this the case? Come to think of it, is there a test for zero-ness, *a la* `is.integer0`?
|
2011/08/25
|
['https://Stackoverflow.com/questions/7195248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/602276/']
|
The [R Language Definitio](http://cran.r-project.org/doc/manuals/R-lang.html)n has this on `NULL`:
>
> There is a special object called NULL. It is used whenever there is a need to indicate or
> specify that an object is absent. It should not be confused with a vector or list of zero
> length. The NULL object has no type and no modifiable properties. There is only one NULL
> object in R, to which all instances refer. To test for NULL use is.null. You cannot set
> attributes on NULL.
>
>
>
So by definition `NULL` is very different to zero length vectors. A zero length vector very much **isn't** absent. `NULL` is really a catch-all for something that is absent or not set, but not missing-ness, which is the job of `NA`. There is an exception, the zero-length pairlist, as mentioned by @Owen. The Language Definition states:
>
> A zero-length pairlist is NULL, as would be expected in Lisp but in contrast to a zero-length list.
>
>
>
which highlights the exception in this case.
To test for a zero-length vector use something like `if(length(foo) == 0L)` for example. And combine that with a class check (`is.character(foo)`) if you want a specific type of zero length vector.
|
The other guys have the right answers, but I want to add a few curiosities.
First, it's not *quite* true that NULL "is used whenever there is a need to indicate or specify that an object is absent" as it says in the doc. There are actually 2 other "no data" values in R (not counting NA, which is not a complete value).
There's "missing", which is used for missing arguments:
>
> alist(x=)$x
>
>
>
```
> identical(NULL, alist(x=)$x)
[1] FALSE
> y = alist(x=)$x
> y
Error: argument "y" is missing, with no default
```
Then there's "unbound", which you can't (AFAIK) access directly, but using C:
```
SEXP getUnbound(void) {
return R_UnboundValue;
}
> x = .Call("getUnbound")
> x
Error: object 'x' not found
```
|
29,628 |
Is there anyway to sync Outlook's calendar with Google's calendar? I've tried [following this](http://support.google.com/calendar/bin/answer.py?hl=en&answer=89955) before but it doesn't work properly. I'm using Windows 7 and Outlook 2010.
The thing is, it's really easy to check my Google Calendar on my phone since I have an Android terminal, but on my computer I prefer just opening Outlook instead of opening a web browser and logging into Gmail.
|
2012/08/02
|
['https://webapps.stackexchange.com/questions/29628', 'https://webapps.stackexchange.com', 'https://webapps.stackexchange.com/users/22630/']
|
You can use
```
in:(anywhere -inbox) label:unread
```
or
```
in:anywhere label:(unread -inbox)
```
`in:anywhere` is the same as "All Mail": mails in inbox, archived, and sent mails. When used in conjection with labels, like `label:any`, it further expands to trash, spam, draft as well.
The `()` after the `:` makes it an AND operator: all conditions inside `()` must be fulfilled. So `in:(anywhere -inbox)` selects all mails, except those in inbox. Since all inbox mails are also labelled as `inbox`, putting it in `label:` also works.
|
You can create a filter if you use the condensed short syntax like so:
```
-label:{inbox trash sent spam}
```
This won't overly help your situation though, since filters only operate on incoming mail.
Your best alternative at this stage may be to bookmark the search so you can quickly mark all as read. For something a little more persistent, you could enable the Quick Links feature in Labs and add the search to that.
|
1,660,424 |
In the linear fractional transformation $T(z)=\frac{az+b}{cz+d}$, if we define $T(-\frac{d}{c})=\infty$, then what is $T(\infty)$?
|
2016/02/17
|
['https://math.stackexchange.com/questions/1660424', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296257/']
|
It is $a/c$. You can always think of it as $\lim\_{z\to\infty}T(z)$.
|
There is no need to "define" these things... since, in fact, $G=GL\_2(\mathbb C)$ acts on complex projective one-space, a.k.a. the Riemann sphere, in homogeneous coordinates: coordinates are $\pmatrix{\omega\_1\cr \omega\_2}$ mod scalars $\mathbb C^\times$. $\mathbb C$ imbeds by $z\to \pmatrix{z \cr 1}$. Then the action of $G$ is just by matrix multiplication of vectors. Thus, the point of the projective space missing from $\mathbb C$ is $\pmatrix{1\cr 0}$. It is mapped to $\pmatrix{a \cr c}$ by $\pmatrix{a & b \cr c & d}$, etc.
|
1,660,424 |
In the linear fractional transformation $T(z)=\frac{az+b}{cz+d}$, if we define $T(-\frac{d}{c})=\infty$, then what is $T(\infty)$?
|
2016/02/17
|
['https://math.stackexchange.com/questions/1660424', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296257/']
|
It is $a/c$. You can always think of it as $\lim\_{z\to\infty}T(z)$.
|
$$\lim\_{z\to\infty}T(z)=\lim\_{z\to 0}T(1/z)=\lim\_{z\to 0}\frac{a/z+b}{c/z+d}=\lim\_{z\to 0}\frac{a+bz}{c+dz}=a/c.$$
|
1,660,424 |
In the linear fractional transformation $T(z)=\frac{az+b}{cz+d}$, if we define $T(-\frac{d}{c})=\infty$, then what is $T(\infty)$?
|
2016/02/17
|
['https://math.stackexchange.com/questions/1660424', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296257/']
|
There is no need to "define" these things... since, in fact, $G=GL\_2(\mathbb C)$ acts on complex projective one-space, a.k.a. the Riemann sphere, in homogeneous coordinates: coordinates are $\pmatrix{\omega\_1\cr \omega\_2}$ mod scalars $\mathbb C^\times$. $\mathbb C$ imbeds by $z\to \pmatrix{z \cr 1}$. Then the action of $G$ is just by matrix multiplication of vectors. Thus, the point of the projective space missing from $\mathbb C$ is $\pmatrix{1\cr 0}$. It is mapped to $\pmatrix{a \cr c}$ by $\pmatrix{a & b \cr c & d}$, etc.
|
$$\lim\_{z\to\infty}T(z)=\lim\_{z\to 0}T(1/z)=\lim\_{z\to 0}\frac{a/z+b}{c/z+d}=\lim\_{z\to 0}\frac{a+bz}{c+dz}=a/c.$$
|
42,660,684 |
I have a very simple problem I am trying to solve but cannot wrap my head around it.
I have three tables of identical structure
```
t1.id, t1.cust_id, t1.name, t1.value
t2.id, t2.cust_id, t2.name, t2.value
t3.id, t3.cust_id, t3.name, t3.value
```
Customers appear in some tables but not in others; the 'value' record in each is a dollar amount.
I would like to run a query in mySQL that produces a summation table that adds up all the purchases made by each customer in the three tables.
My desired output would look something like:
```
Name Customer ID T1 T2 T3
Joe 88888 12.45 45.90 2.34
Ted 99999 8.90 3.45 null
Sue 12123 9.45 2.45 null
```
I've tried a few queries with JOINs but with no satisfactory results.
Thanks your help!
|
2017/03/08
|
['https://Stackoverflow.com/questions/42660684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1234414/']
|
Use `union all` to combine the rows from 3 tables and then use aggregation.
```
select cust_id,name,sum(t1val),sum(t2val),sum(t3val)
from (
select id, cust_id, name, value as t1val, null as t2val, null as t3val from t1
union all
select id, cust_id, name, null, value, null from t2
union all
select id, cust_id, name, null, null ,value from t3
) t
group by cust_id,name
```
|
You can do it with `SELECT`, e.g.:
```
SELECT (
(SELECT COALESCE(SUM(value),0) FROM t1 WHERE cust_id = 100)
+
(SELECT COALESCE(SUM(value),0) FROM t2 WHERE cust_id = 100)
+
(SELECT COALESCE(SUM(value),0) FROM t3 WHERE cust_id = 100)
) as total;
```
Here's the **[SQL Fiddle](http://sqlfiddle.com/#!9/6f286/8/0)**.
|
16,865,303 |
I am changing an existing data storage php code from `mysql_*` functions to PDO as well changing it from Procedural to OOB programming. I was updating the SQL statements when I noticed something, fairly far into the rewriting process.
I am setting up an array for multiple tables `INSERT` and `UPDATE` queries, as I was defining an array to work as the binding values I noticed that the *order* in which the bound values are called would be different from the `UPDATE` to the `INSERT`, here is a brief example:
```
$bound_values = array(
':column_aa' => 'aa',
':column_ab' => 'ab',
':column_ac' => 'ac'
)
);
```
Example sql for `INSERT`:
```
INSERT INTO `table_a`
(`id`, `column_aa`, `column_ab`, `column_ac`)
VALUES
('', :column_aa, :column_ab, :column_ac);
```
and the `UPDATE`:
```
UPDATE `table_a` SET
`column_ab` = :column_ab, `column_ac` = :column_ac, `column_aa` = :column_aa;
```
Example PHP PDO:
```
$pdo = new PDO('mysql:host=localhost;dbname=example', 'root', '');
// The second parameter of the PDO cursor is what I saw that raised the flag
$sth = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($boud_values);
```
So my question is, can I keep going forward using this method without an issue as to what order the SQL statements are in vs the `$bound_values` array, or am I right in being concerned and need to make some changes?
Please note that the existing code I am working with isn't anywhere **near** as simple as the SQL statements I have shown above.
|
2013/05/31
|
['https://Stackoverflow.com/questions/16865303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2200704/']
|
Using named placeholders (:col\_name), you can put them in any order as you please. However, using positional placeholders (?) - you need to put them in order.
|
It doesn't matter as long as you use named parameters ( `:somename` ). The binding simply tells your database engine "where I wrote the placeholder `:abc`, fill with this value. Where I wrote placeholder `:xyz`, put this other value".
Think about how the code would look like if you were binding each value separately instead of all at once in the execute
```
$sth->bindParam(':abc', 'value1', PDO::PARAM_STR);
$sth->bindParam(':xyz', 'value2', PDO::PARAM_STR);
$sth->execute();
```
Switching the bindParam() order would not have any impact.
Also, note that the order in which the column are set in INSERT and UPDATE sql queries doesn't matter, so if this really bugs you (or if you like things to be standardized a little) you can just order the column the same way in both queries.
```
UPDATE table SET col2 = 'xyz', col1 = 'abc'
// is the same as
UPDATE table SET col1 = 'abc', col2 = 'xyz'
```
|
32,143,770 |
Preface - I'm pretty new to Python, having had more experience in another language.
I have a text file with single column list of strings in the generic (but slightly varying) format "./abc123a1/type/1ab2\_x\_data\_type.file.type"
I need to extract the abc123a1 and the 1ab2 portions from all several hundred of the rows and put them under two columns (column a and b) in a csv. Sometimes there may be a "1ab2\_a" and a "1ab2\_b", but I *only* want one 1ab2. So I'd want to grab "1ab2\_a" and ignore all others.
I have the regex which I THINK will work:
```
tmp = list()
if re.findall(re.compile(r'^([a-zA-Z0-9]{4})_'), x):
tmp = re.findall(re.compile(r'^([a-zA-Z0-9]{4})_'), x)
elif re.findall(re.compile(r'_([a-zA-Z0-9]{4})_'), x):
tmp = re.findall(re.compile(r'_([a-zA-Z0-9]{4})_'), x)
if len(tmp) == 0:
return None
elif len(tmp) > 1:
print "ERROR found multiple matches"
return "ERROR"
else:
return tmp[0].upper()
```
I am trying to make this script step by step and testing things to make sure it works, but it's just not.
```
import sys
import csv
listOfData = []
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
for line in f:
listOfData.append([line])
print listOfData
with open('extracted.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('column a', 'column b'))
writer.writerows(listOfData)
print listOfData
```
Still failing to get anything in the csv other than column headers, much less a parsed version!
Does anyone have any better ideas or formats I could do this in? A friend mentioned looking into glob.glob, but I haven't had luck getting that to work either.
|
2015/08/21
|
['https://Stackoverflow.com/questions/32143770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5252432/']
|
IMHO, you were not far from making it work. The problem is that you read once the whole file just to print the lines, and then (once at end of file) you try to put them into a list... and get an empty list !
You should read the file only once:
```
import sys
import csv
listOfData = []
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
listOfData.append([line])
print listOfData
with open('extracted.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('column a', 'column b'))
writer.writerows(listOfData)
print listOfData
```
once it works, you still have to use the regex to get relevant data to put into the csv file
|
I am not sure about your regex (it will most probably not work) , but the reason why your current (non-regex , simple) code does not work is because -
```
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
for line in f:
listOfData.append([line])
```
As you can see you are first iterating over each line in file and printing it, it should be fine, but after the loop ends, the file pointer is at the end of file, so trying to iterate over it again , would not produce any result. You should only iterate over it once, and do both printing and appending to list in it. Example -
```
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
listOfData.append([line])
```
|
32,143,770 |
Preface - I'm pretty new to Python, having had more experience in another language.
I have a text file with single column list of strings in the generic (but slightly varying) format "./abc123a1/type/1ab2\_x\_data\_type.file.type"
I need to extract the abc123a1 and the 1ab2 portions from all several hundred of the rows and put them under two columns (column a and b) in a csv. Sometimes there may be a "1ab2\_a" and a "1ab2\_b", but I *only* want one 1ab2. So I'd want to grab "1ab2\_a" and ignore all others.
I have the regex which I THINK will work:
```
tmp = list()
if re.findall(re.compile(r'^([a-zA-Z0-9]{4})_'), x):
tmp = re.findall(re.compile(r'^([a-zA-Z0-9]{4})_'), x)
elif re.findall(re.compile(r'_([a-zA-Z0-9]{4})_'), x):
tmp = re.findall(re.compile(r'_([a-zA-Z0-9]{4})_'), x)
if len(tmp) == 0:
return None
elif len(tmp) > 1:
print "ERROR found multiple matches"
return "ERROR"
else:
return tmp[0].upper()
```
I am trying to make this script step by step and testing things to make sure it works, but it's just not.
```
import sys
import csv
listOfData = []
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
for line in f:
listOfData.append([line])
print listOfData
with open('extracted.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('column a', 'column b'))
writer.writerows(listOfData)
print listOfData
```
Still failing to get anything in the csv other than column headers, much less a parsed version!
Does anyone have any better ideas or formats I could do this in? A friend mentioned looking into glob.glob, but I haven't had luck getting that to work either.
|
2015/08/21
|
['https://Stackoverflow.com/questions/32143770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5252432/']
|
IMHO, you were not far from making it work. The problem is that you read once the whole file just to print the lines, and then (once at end of file) you try to put them into a list... and get an empty list !
You should read the file only once:
```
import sys
import csv
listOfData = []
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
listOfData.append([line])
print listOfData
with open('extracted.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('column a', 'column b'))
writer.writerows(listOfData)
print listOfData
```
once it works, you still have to use the regex to get relevant data to put into the csv file
|
I think at least part of the problem is the two `for` loops in the following:
```
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
for line in f:
listOfData.append([line])
```
The first one `print`s all the lines of `f`, so there's nothing left for the second one to iterate over unless you first `f.seek(0)` and rewind the file.
An alternative way would to simply to this:
```
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
listOfData.append([line])
```
It's hard to tell if your regexes are OK without more than one line of sample input data.
|
32,143,770 |
Preface - I'm pretty new to Python, having had more experience in another language.
I have a text file with single column list of strings in the generic (but slightly varying) format "./abc123a1/type/1ab2\_x\_data\_type.file.type"
I need to extract the abc123a1 and the 1ab2 portions from all several hundred of the rows and put them under two columns (column a and b) in a csv. Sometimes there may be a "1ab2\_a" and a "1ab2\_b", but I *only* want one 1ab2. So I'd want to grab "1ab2\_a" and ignore all others.
I have the regex which I THINK will work:
```
tmp = list()
if re.findall(re.compile(r'^([a-zA-Z0-9]{4})_'), x):
tmp = re.findall(re.compile(r'^([a-zA-Z0-9]{4})_'), x)
elif re.findall(re.compile(r'_([a-zA-Z0-9]{4})_'), x):
tmp = re.findall(re.compile(r'_([a-zA-Z0-9]{4})_'), x)
if len(tmp) == 0:
return None
elif len(tmp) > 1:
print "ERROR found multiple matches"
return "ERROR"
else:
return tmp[0].upper()
```
I am trying to make this script step by step and testing things to make sure it works, but it's just not.
```
import sys
import csv
listOfData = []
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
for line in f:
listOfData.append([line])
print listOfData
with open('extracted.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('column a', 'column b'))
writer.writerows(listOfData)
print listOfData
```
Still failing to get anything in the csv other than column headers, much less a parsed version!
Does anyone have any better ideas or formats I could do this in? A friend mentioned looking into glob.glob, but I haven't had luck getting that to work either.
|
2015/08/21
|
['https://Stackoverflow.com/questions/32143770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5252432/']
|
IMHO, you were not far from making it work. The problem is that you read once the whole file just to print the lines, and then (once at end of file) you try to put them into a list... and get an empty list !
You should read the file only once:
```
import sys
import csv
listOfData = []
with open(sys.argv[1]) as f:
print "yes"
for line in f:
print line
listOfData.append([line])
print listOfData
with open('extracted.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('column a', 'column b'))
writer.writerows(listOfData)
print listOfData
```
once it works, you still have to use the regex to get relevant data to put into the csv file
|
Are you sure you need all of the regular expressions? You seem to be parsing a list of paths and filenames. The path could be split up using a `split` command, for example:
```
print "./abc123a1/type/1ab2_a_data_type.file.type".split("/")
```
Would give:
```
['.', 'abc123a1', 'type', '1ab2_a_data_type.file.type']
```
You could then create a `set` consisting of the second entry and up to the '\_' in forth entry, e.g.
```
('abc123a1', '1ab2')
```
This could then be used to print only the first entry from each:
```
pairs = set()
with open(sys.argv[1], 'r') as in_file, open('extracted.csv', 'wb') as out_file:
writer = csv.writer(out_file)
for row in in_file:
folders = row.split("/")
col_a = folders[1]
col_b = folders[3].split("_")[0]
if (col_a, col_b) not in pairs:
pairs.add((col_a, col_b))
writer.writerow([col_a, col_b])
```
So for an input looking like this:
```
./abc123a1/type/1ab2_a_data_type.file.type
./abc123a1/type/1ab2_b_data_type.file.type
./abc123a2/type/1ab2_a_data_type.file.type
./abc123a3/type/1ab2_a_data_type.file.type
```
You would get a CSV file looking like:
```
abc123a1,1ab2
abc123a2,1ab2
abc123a3,1ab2
```
|
206,391 |
I am taking part in a robotics competition, where the challenge is to create a pair of robots which successfully navigate a series of obstacles. However, the rules state that of the two robots, only one must have a driving actuator. The other must somehow be moved by the other robot, WITHOUT PHYSICAL CONTACT.
I could think of either having sails on the non-driving robot, and moving it with fans on the driving one OR electromangnets on the driving one and permanent magnets with the opposite polarity on the non-driving one. However the problem with both is that efficiency falls off drastically with distance. Thus, I am looking for possible ways to overcome this problem.
Also, the driving robot has a cable power supply, while the non-driving one may only have batteries which can steer it.
I believe this question belongs to Physics as I want to know the actual forces possible, not their implementation in robots. Thanks :)
|
2015/09/11
|
['https://physics.stackexchange.com/questions/206391', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/92488/']
|
The average *vector* momentum of an electron bound to an atom is exactly zero. (Otherwise, the electron would leave the atom!)
The average *magnitude* of the momentum can't be zero, because of the uncertainty principle. So Feynman is using the approximation $\vec p = \vec 0 + \Delta p \hat p$, where the magnitude $\Delta p$ comes from the uncertainty principle and the unit vector $\hat p$ points in a completely random direction.
As for your second question, you're almost there. The kinetic energy *does* become larger for an electron nearer the nucleus — and, thanks to the uncertainty principle, so does the momentum! It has to be this way because the kinetic energy is approximately $T=p^2/2m.$
|
In QM that electron would need more and more kinetic energy when it closes to nucleus, so at some point Coulombic force becomes too weak. The result is an equilibrium position with nucleus, i.e. hydrogen atom.
Heisenberg's uncertainty principle is useless when it comes to hydrogenic $1/r$ potential, but for harmonic oscillator $r^2$ potential we can use Heisenberg's uncertainty principle to easily calculate the ground state energy.
What you need is the following "uncertainty principle" that solves $1/r$ potential and the ground state energy for hydrogen atom, when $\psi$ is the wave for electron. You can prove it as an easy homework exercise:
$$\int\frac{|\psi(x,t)|^2}{|x|}dx \le \sqrt{\int |\nabla\psi(x,t)|^2dx}.$$
|
206,391 |
I am taking part in a robotics competition, where the challenge is to create a pair of robots which successfully navigate a series of obstacles. However, the rules state that of the two robots, only one must have a driving actuator. The other must somehow be moved by the other robot, WITHOUT PHYSICAL CONTACT.
I could think of either having sails on the non-driving robot, and moving it with fans on the driving one OR electromangnets on the driving one and permanent magnets with the opposite polarity on the non-driving one. However the problem with both is that efficiency falls off drastically with distance. Thus, I am looking for possible ways to overcome this problem.
Also, the driving robot has a cable power supply, while the non-driving one may only have batteries which can steer it.
I believe this question belongs to Physics as I want to know the actual forces possible, not their implementation in robots. Thanks :)
|
2015/09/11
|
['https://physics.stackexchange.com/questions/206391', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/92488/']
|
This might be a bit helpful.
The uncertainty in the momentum of an electron in an atom is defined as: $(\Delta P )^{2}= \langle P^{2}\rangle-\langle P\rangle^{2}$. An electron bounded by the nucleus, has an average momentum of zero, which means ($\Delta P)^2 = {\langle P^{2}\rangle}$, but again, Feynman's explain, as explained in the comment, was a really hand-wavy approach towards approximating the size of an atom.
|
In QM that electron would need more and more kinetic energy when it closes to nucleus, so at some point Coulombic force becomes too weak. The result is an equilibrium position with nucleus, i.e. hydrogen atom.
Heisenberg's uncertainty principle is useless when it comes to hydrogenic $1/r$ potential, but for harmonic oscillator $r^2$ potential we can use Heisenberg's uncertainty principle to easily calculate the ground state energy.
What you need is the following "uncertainty principle" that solves $1/r$ potential and the ground state energy for hydrogen atom, when $\psi$ is the wave for electron. You can prove it as an easy homework exercise:
$$\int\frac{|\psi(x,t)|^2}{|x|}dx \le \sqrt{\int |\nabla\psi(x,t)|^2dx}.$$
|
206,391 |
I am taking part in a robotics competition, where the challenge is to create a pair of robots which successfully navigate a series of obstacles. However, the rules state that of the two robots, only one must have a driving actuator. The other must somehow be moved by the other robot, WITHOUT PHYSICAL CONTACT.
I could think of either having sails on the non-driving robot, and moving it with fans on the driving one OR electromangnets on the driving one and permanent magnets with the opposite polarity on the non-driving one. However the problem with both is that efficiency falls off drastically with distance. Thus, I am looking for possible ways to overcome this problem.
Also, the driving robot has a cable power supply, while the non-driving one may only have batteries which can steer it.
I believe this question belongs to Physics as I want to know the actual forces possible, not their implementation in robots. Thanks :)
|
2015/09/11
|
['https://physics.stackexchange.com/questions/206391', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/92488/']
|
The average *vector* momentum of an electron bound to an atom is exactly zero. (Otherwise, the electron would leave the atom!)
The average *magnitude* of the momentum can't be zero, because of the uncertainty principle. So Feynman is using the approximation $\vec p = \vec 0 + \Delta p \hat p$, where the magnitude $\Delta p$ comes from the uncertainty principle and the unit vector $\hat p$ points in a completely random direction.
As for your second question, you're almost there. The kinetic energy *does* become larger for an electron nearer the nucleus — and, thanks to the uncertainty principle, so does the momentum! It has to be this way because the kinetic energy is approximately $T=p^2/2m.$
|
This might be a bit helpful.
The uncertainty in the momentum of an electron in an atom is defined as: $(\Delta P )^{2}= \langle P^{2}\rangle-\langle P\rangle^{2}$. An electron bounded by the nucleus, has an average momentum of zero, which means ($\Delta P)^2 = {\langle P^{2}\rangle}$, but again, Feynman's explain, as explained in the comment, was a really hand-wavy approach towards approximating the size of an atom.
|
14,001 |
How must I populate a playa hidden input field (in a safecracker form) with multiple entries? I tried passing the entry IDs separated by comma, semicolon, bar, but nothing seems to work. Only the first entry in the array gets saved. How do I have to format the entry IDs for multiple relationships to be saved?
Update: Thanks to Jeremy I now know how to add data to Playa correctly. Alas, it's still not working, now I get PHP errors.
This is what I have (inside a safecracker form):
{exp:channel:entries channel="channel-name" category="{category\_id}" dynamic="no" disable="member\_data|pagination"}
- {title}{if {embed:parent\_id} == '{exp:playa:parent\_ids}' }
{if:else}
{/if}
{/exp:channel:entries}
I make a list with checkboxes. The conditionals check whether this entry is related to the entry currently being edited. So when it's related
```
<input class="relate" type="hidden" name="playa_field[selections][]" value="{entry_id}"/>
```
gets displayed, when it's not related
```
<input class="relate" type="hidden" name="0" value="{entry_id}"/>{/if}</label>
```
gets displayed. This works fine.
In the footer I load jQuery and this code to look for changes on checkboxes. When a checkbox is changed the "name" attribute gets updated.
```
$(document).ready(function() {
var $checkboxes = jQuery("#tag_list").find(":checkbox");
$checkboxes.on('change', function () {
var $relate = jQuery(this).siblings('.relate').attr("name"),
$name = "playa_field[selections][]";
if ($relate == $name) {
jQuery(this).siblings('.relate').attr( "name", "0" );
}
if ($relate != $name) {
jQuery(this).siblings('.relate').attr( "name", "playa_field[selections][]" );
}
});
});
```
This also seems to work, I can see the "name" attribute get changed in the Safari developer tools.
But now, when I submit the field I get a bunch of the following PHP errors:
```
Severity: Warning
Message: array_filter() expects parameter 1 to be array, string given
Filename: playa/ft.playa.php
Line Number: 2356
Severity: Warning
Message: array_merge() [function.array-merge]: Argument #1 is not an array
Filename: playa/ft.playa.php
Line Number: 2356
```
What am I doing wrong?
|
2013/09/23
|
['https://expressionengine.stackexchange.com/questions/14001', 'https://expressionengine.stackexchange.com', 'https://expressionengine.stackexchange.com/users/779/']
|
You'll want to actually use multiple hidden fields, each adding to an array:
```
<input type="hidden" name="cf_playa_field[selections][]" value="123">
<input type="hidden" name="cf_playa_field[selections][]" value="456">
```
You could also potentially write an extension to rework the POST data if you absolutely must submit the values in one field.
|
OK, I got this squared away. It seems like my name="0" inputs were causing the errors. Now I remove the complete hidden input when a checkbox is unchecked and create a new one on the fly when a checkbox is checked.
|
62,804,224 |
My OpenCL program involves having about 7 billion work-items. In my C++ program, I would set this to my global\_item\_size:
```
size_t global_item_size = 7200000000;
```
If my program is compiled to 64-bit systems (x64), this global size is OK, since SIZE\_MAX (the maximum value of size\_t) is much larger than 7 billion. However, to ensure backwards compatibility I want to make sure that my program is able to compile to 32-bit systems (x86). On 32-bit systems, SIZE\_MAX is about 4 billion, less than my global size, 7 billion. If I would try to set the global size to 7 billion, it would result in an overflow. What can I do in this case?
One of the solutions I was thinking about was to make a multi-dimensional global size and local size. However, this solution requires the kernel to calculate the original global size (because my kernel heavily depends on the global and local size), which would result in a performance loss.
The other solution I considered was to launch multiple kernels. I think this solution would be a little "sloppy" and synchronizing kernels also wouldn't be the best solution.
So my question basically is: **How can I (if possible) make the global size larger than the maximum size of size\_t? If this is not possible, what are some workarounds?**
|
2020/07/08
|
['https://Stackoverflow.com/questions/62804224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6702334/']
|
`proc_res_field` doesn't know anything about `i` or `a`
```
Function proc_res_field(Tstruct As TestMDate)
Debug.Print Tstruct.MonthS
Debug.Print Tstruct.MonthD
Debug.Print Tstruct.StartD
Debug.Print Tstruct.EndD
proc_res_field = 1 '?
End Function
```
|
It is a common error, I forgot it too, but functions return something.
```
Function proc_res_field(Tstruct As TestMDate) as integer
proc_res_field=7
End Function
```
And at the call:
```
a=proc_res_field(your_tstruct)
```
Just as example, setup the correct params and return types that you want to use.
|
32,537,116 |
Im trying days to understand how I can convert a SQL query to a query builder style in laravel.
My SQL query is:
```
$tagid = Db::select("SELECT `id` FROM `wouter_blog_tags` WHERE `slug` = '".$this->param('slug')."'");
$blog = Db::select("SELECT *
FROM `wouter_blog_posts`
WHERE `published` IS NOT NULL
AND `published` = '1'
AND `published_at` IS NOT NULL
AND `published_at` < NOW()
AND (
SELECT count( * )
FROM `wouter_blog_tags`
INNER JOIN `wouter_blog_posts_tags` ON `wouter_blog_tags`.`id` = `wouter_blog_posts_tags`.`tags_id`
WHERE `wouter_blog_posts_tags`.`post_id` = `wouter_blog_posts`.`id`
AND `id`
IN (
'".$tagid[0]->id."'
)) >=1
ORDER BY `published_at` DESC
LIMIT 10
OFFSET 0");
```
Where I now end up to convert to the query builder is:
```
$test = Db::table('wouter_blog_posts')
->where('published', '=', 1)
->where('published', '=', 'IS NOT NULL')
->where('published_at', '=', 'IS NOT NULL')
->where('published_at', '<', 'NOW()')
->select(Db::raw('count(*) wouter_blog_tags'))
->join('wouter_blog_posts_tags', function($join)
{
$join->on('wouter_blog_tags.id', '=', 'wouter_blog_posts_tags.tags_id')
->on('wouter_blog_posts_tags.post_id', '=', 'wouter_blog_posts.id')
->whereIn('id', $tagid[0]->id);
})
->get();
```
I have read that I can't use whereIn in a join. The error i now get:
>
> Call to undefined method Illuminate\Database\Query\JoinClause::whereIn()
>
>
>
I realy dont know how I can convert my SQL to query builder. I hope when I see a good working conversion of my query I can understand how I have to do it next time.
|
2015/09/12
|
['https://Stackoverflow.com/questions/32537116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3618513/']
|
This work for me:
>
> DB::table('wouter\_blog\_posts')
> ->whereNotNull('published')
> ->where('published', 1)
> ->whereNotNull('published\_at')
> ->whereRaw('`published_at` < NOW()')
> ->whereRaw("(SELECT count(\*)
> FROM `wouter_blog_tags`
> INNER JOIN `wouter_blog_posts_tags` ON `wouter_blog_tags`.`id` = `wouter_blog_posts_tags`.`tags_id`
> WHERE `wouter_blog_posts_tags`.`post_id` = `wouter_blog_posts`.`id`
> AND `id`
> IN (
> '".$tagid."'
> )) >=1")
> ->orderBy('published\_at', 'desc')
> ->skip(0)
> ->take(10)
> ->paginate($this->property('postsPerPage'));
>
>
>
|
The following Query Builder code will give you the exact SQL query you have within your `DB::select`:
```
DB::table('wouter_blog_posts')
->whereNotNull('published')
->where('published', 1)
->whereNotNull('published_at')
->whereRaw('`published_at` < NOW()')
->where(DB::raw('1'), '<=', function ($query) use ($tagid) {
$query->from('wouter_blog_tags')
->select('count(*)')
->join('wouter_blog_posts_tags', 'wouter_blog_tags.id', '=', 'wouter_blog_posts_tags.tags_id')
->whereRaw('`wouter_blog_posts_tags`.`post_id` = `wouter_blog_posts`.`id`')
->whereIn('id', [$tagid[0]->id]);
})
->orderBy('published_at', 'desc')
->skip(0)
->take(10)
->get();
```
The subquery condition had to be reversed because you can't have a subquery as the first parameter of the `where` method and still be able to bind the condition value. So it's `1 <= (subquery)` which is equivalent to `(subquery) >= 1`. The query generated by the above code will look like this:
```sql
SELECT *
FROM `wouter_blog_posts`
WHERE `published` IS NOT NULL
AND `published` = 1
AND `published_at` IS NOT NULL
AND `published_at` < Now()
AND 1 <= (SELECT `count(*)`
FROM `wouter_blog_tags`
INNER JOIN `wouter_blog_posts_tags`
ON `wouter_blog_tags`.`id` =
`wouter_blog_posts_tags`.`tags_id`
WHERE `wouter_blog_posts_tags`.`post_id` =
`wouter_blog_posts`.`id`
AND `id` IN ( ? ))
ORDER BY `published_at` DESC
LIMIT 10 offset 0
```
---
My process when creating more complex queries is to first create them and try them out in a SQL environment to make sure they work as indended. Then I implement them step by step with the Query Builder, but instead of using `get()` at the end of the query, I use `toSql()` which will give me a string representation of the query that will be generated by the Query Builder, allowing me to compare that to my original query to make sure it's the same.
|
3,996,048 |
I've got a sortable list which is using `connectWith` to ensure it can only be sorted within its own types of list.
Now I'm trying to make a droppable trash can element that appears at the bottom on the viewport when an item is being sorted. This element is outside the context of the lists and simply deletes any element that is dropped on it. The desired functionality is identical to deleting a shortcut from the desktop of an Android phone, if you are familiar with that.
The problem is, although my trash can is a droppable which accepts '\*', my sortable is told only to `connectWith` other '.dropZone' items only, which means I cannot get any of my sortable elements to cause a hover state on the trash element.
I've tried making each sortable into a draggable on the `start` event, but of course I'm not dragging that draggable at the exact moment and so it's not activated. Is it possible to satisfy both requirements or am I going to have to detect the trash can hover manually?
|
2010/10/22
|
['https://Stackoverflow.com/questions/3996048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192/']
|
Since `connectWith` accepts a selector, you can provide it a selector that selects both the other connected lists and your trash can.
```
$("#sortable1, #sortable2").sortable({
connectWith: '.connectedSortable, #trash'
}).disableSelection();
$("#trash").droppable({
accept: ".connectedSortable li",
hoverClass: "ui-state-hover",
drop: function(ev, ui) {
ui.draggable.remove();
}
});
```
Example: <http://jsfiddle.net/petersendidit/YDZJs/1/>
|
How about making the trash can a `.dropZone` as well? Then you would get a proper `drop` event, and you could handle the deleting properly.
There may be side effects of making the trash can a sortable, but I figure they should be easy to work around.
If this doesn't meet your requirements, could you throw up a demo [somewhere](http://jsfiddle.net), so we know what exactly we'd have to work around to keep your structure intact, while still adding the functionality you need?
|
45,003,631 |
I have a column where a date store in ddmmyy format (e.g. 151216). How can I convert it to yyyy-mm-dd format (e.g 2016-12-15) for calculating a date difference from the current date? I try using DATE\_FORMAT function but its not appropriate for this.
|
2017/07/10
|
['https://Stackoverflow.com/questions/45003631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2231075/']
|
If you want to get the date difference, you can use `to_days()` after converting the string to a date using `str_to_date()`:
```
select to_days(curdate()) - to_days(str_to_date(col, '%d%m%y'))
```
or `datediff()`:
```
select datediff(curdate(), str_to_date(col, '%d%m%y'))
```
or `timestampdiff()`:
```
select timestampdiff(day, str_to_date(col, '%d%m%y'), curdate())
```
|
You can use the function, `STR_TO_DATE()` for this.
```
STR_TO_DATE('151216', '%d%m%y')
```
A query would look something like:
```
select
foo.bar
from
foo
where
STR_TO_DATE(foo.baz, '%d%m%y') < CURDATE()
```
Note: Since both `STR_TO_DATE()` and `CURDATE()` return date objects, there's no reason to change the actual display format of the date. For this function, we just need to format it. If you wanted to display it in your query, you could use something like
```
DATE_FORMAT(STR_TO_DATE(foo.baz, '%d%m%y'), '%Y-%m-%d')
```
To get the difference, we can simply subtract time
```
select
to_days(CURDATE() - STR_TO_DATE(foo.baz, '%d%m%y')) as diff
from
foo
```
If you wanted to only select rows that have a difference of a specified amount, you can put the whole `to_days(...)` bit in your where clause.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.