qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
11,828,045 | let's say I have a interface IPerson that expose a collection of another interface ICar. ICar is implemented by the Car class, and the IPerson is implemented by the Person class. I would like that Person could expose a collection of Car, and not of ICar, but this does not seem possible without changing the IPerson interface.
Is there any other solution ? I would like to have the IPerson expose a collection of ICar, but I would also need a class implementing IPerson and exposind a collection of Car.
Thanks | 2012/08/06 | [
"https://Stackoverflow.com/questions/11828045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1472131/"
] | I don't know if this solution will fit your needs, however depending on what language you are using, you could use a generic solution to achieve this kind of behavior.
For example in java
```
interface IPerson<T extends ICar> {
public T[] getCars();
// ...
}
```
This will insure that the generic type `T` must implement `ICar`, then in your implementation of `Person` you can have
```
Class Person implements IPerson<Car> {
Car[] cars;
public Car[] getCars() {
return cars;
}
// ...
}
```
This will unfortunately not allow you to look at a collection of different `IPersons` together, since this is no longer an `IPerson` but an `IPerson<Car>`. | In my opinion this is not possible.
If IPerson has a collection of ICars, then your Person class also needs to accept any ICar, not just your concrete *Car* class.
This is of course assuming that the user of IPerson is allowed to add ICar instances. If the collection is readonly, then in theory this might be possible but most languages won't allow it (C# for instance will not). |
3,473,797 | we have to calculate the arc length of the following function
$y=\sqrt{(\cos2x)} dx$ in the interval $[0 ,\pi/4]$. I know the arc length formula but following it becomes an integral thats really complex...need help.... | 2019/12/12 | [
"https://math.stackexchange.com/questions/3473797",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/734313/"
] | I got the following integral $$\int\_0^{\frac{\pi }{4}} \sqrt{\sin (2 x) \tan (2 x)+1} \, dx$$ no hope that this has an algebraic solution. | $\int\_{0}^{\frac{\pi}{4}} \sqrt{\cos2x} dx = \frac{1}{2}\int\_{0}^{\frac{\pi}{4}} \sqrt{\cos{u}} du = \frac{1}{2}\cdot \:2\text{E}\left(\frac{u}{2}|\:2\right) = \frac{1}{2}\cdot \:2\text{E}\left(\frac{2x}{2}|\:2\right) = \text{E}\left(x|2\right)+C$, where $\text{E}\left(x|m\right)$ is the elliptic integral of the second kind.
See: <https://math.stackexchange.com/a/19786/733593> |
19,778,790 | I'm trying to have a default instance of a class. I want to have
```
class Foo():
def __init__(self):
....
_default = Foo()
@staticmethod
def get_default():
return _default
```
However `_default = Foo()` leads to `NameError: name 'Foo' is not defined` | 2013/11/04 | [
"https://Stackoverflow.com/questions/19778790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1445618/"
] | `Foo` does not exist until the class definition is finalized. You can easily refer to it *after* the class definition, though:
```
class Foo(object):
def __init__(self):
# ....
Foo.default_instance = Foo()
```
Note also that I have removed the superfluous getter method in favor of a plain old attribute.
You can also solve the problem with a decorator:
```
def defaultinstance(Class):
Class.default_instance = Class()
return Class
@defaultinstance
class Foo(object):
# ...
```
Or, gratuitously, with a metaclass:
```
def defaultmeta(name, bases, attrs):
Class = type(name, bases, attrs)
Class.default_instance = Class()
return Class
# Python 2.x usage
class Foo(object):
__metaclass__ = defaultmeta
# ...
# Python 3.x usage
class Foo(metaclass=defaultmeta):
# ...
```
When might you might want to use each method?
* Use the post-definition class attribute assignment for one-offs
* Use the decorator if you want the same behavior in a lot of unrelated classes and to "hide" the implementation of it (it's not really hidden, or even that complicated, here, though)
* Use the metaclass if you want the behavior to be *inheritable* in which case it's not really gratuitous. :-) | You cannot refer to a class that doesn't yet exist. Within the class definition body, the `Foo` class is *not yet created*.
Add the attribute after the class has been created:
```
class Foo():
def __init__(self):
....
@staticmethod
def get_default():
return Foo._default
Foo._default = Foo()
```
Note that you also need to alter the `get_default()` static method; the class body doesn't form a scope, so you cannot reach `_default` as a non-local from `get_default()`.
You are now, however, repeating yourself a lot. Reduce repetition a little by making `get_default()` a classmethod instead:
```
class Foo():
def __init__(self):
....
@classmethod
def get_default(cls):
return cls._default
Foo._default = Foo()
```
or create the default on first call:
```
class Foo():
def __init__(self):
....
@classmethod
def get_default(cls):
if not hasattr(cls, '_default'):
cls._default = cls()
return cls._default
``` |
19,778,790 | I'm trying to have a default instance of a class. I want to have
```
class Foo():
def __init__(self):
....
_default = Foo()
@staticmethod
def get_default():
return _default
```
However `_default = Foo()` leads to `NameError: name 'Foo' is not defined` | 2013/11/04 | [
"https://Stackoverflow.com/questions/19778790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1445618/"
] | `Foo` does not exist until the class definition is finalized. You can easily refer to it *after* the class definition, though:
```
class Foo(object):
def __init__(self):
# ....
Foo.default_instance = Foo()
```
Note also that I have removed the superfluous getter method in favor of a plain old attribute.
You can also solve the problem with a decorator:
```
def defaultinstance(Class):
Class.default_instance = Class()
return Class
@defaultinstance
class Foo(object):
# ...
```
Or, gratuitously, with a metaclass:
```
def defaultmeta(name, bases, attrs):
Class = type(name, bases, attrs)
Class.default_instance = Class()
return Class
# Python 2.x usage
class Foo(object):
__metaclass__ = defaultmeta
# ...
# Python 3.x usage
class Foo(metaclass=defaultmeta):
# ...
```
When might you might want to use each method?
* Use the post-definition class attribute assignment for one-offs
* Use the decorator if you want the same behavior in a lot of unrelated classes and to "hide" the implementation of it (it's not really hidden, or even that complicated, here, though)
* Use the metaclass if you want the behavior to be *inheritable* in which case it's not really gratuitous. :-) | You may lazily initialize your default instance.
```
class Foo(object):
_default = None
@staticmethod
def get_default():
if not Foo._default:
Foo._default = Foo()
return Foo._default
``` |
19,778,790 | I'm trying to have a default instance of a class. I want to have
```
class Foo():
def __init__(self):
....
_default = Foo()
@staticmethod
def get_default():
return _default
```
However `_default = Foo()` leads to `NameError: name 'Foo' is not defined` | 2013/11/04 | [
"https://Stackoverflow.com/questions/19778790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1445618/"
] | You cannot refer to a class that doesn't yet exist. Within the class definition body, the `Foo` class is *not yet created*.
Add the attribute after the class has been created:
```
class Foo():
def __init__(self):
....
@staticmethod
def get_default():
return Foo._default
Foo._default = Foo()
```
Note that you also need to alter the `get_default()` static method; the class body doesn't form a scope, so you cannot reach `_default` as a non-local from `get_default()`.
You are now, however, repeating yourself a lot. Reduce repetition a little by making `get_default()` a classmethod instead:
```
class Foo():
def __init__(self):
....
@classmethod
def get_default(cls):
return cls._default
Foo._default = Foo()
```
or create the default on first call:
```
class Foo():
def __init__(self):
....
@classmethod
def get_default(cls):
if not hasattr(cls, '_default'):
cls._default = cls()
return cls._default
``` | You may lazily initialize your default instance.
```
class Foo(object):
_default = None
@staticmethod
def get_default():
if not Foo._default:
Foo._default = Foo()
return Foo._default
``` |
247,639 | I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:
* *Pool*. This is a class which allocates memory efficiently, for some definition of 'efficient'. *Pool* is guaranteed to return a chunk of memory that is aligned for the requested size.
* *Obj\_list*. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of *Obj\_list* is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.
* *Aggregate*. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. *Aggregate*s can be empty, or manage an arbitrary number of objects.
In this example, *Aggregate* items are always allocated from *Pool*s, so they are always aligned. The only occurrences of *Obj\_list* in this example are the 'hidden' members in *Aggregate* objects, and therefore they are always allocated using *placement new*. Here are the support classes:
```
class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
```
And here is Aggregate. Note that member declaration *member\_list\_store\_d*:
```
// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
```
It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:
```
Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
```
You may be tempted to suggest that we replace the char array with a pointer to the *Obj\_list* type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an *Obj\_list* would cost one more pointer in the case when *Aggregate* objects *do* have members.
Besides that, I don't really want to get distracted from the main question here, which is alignment. I *think* the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' *new*.
So, does the above construct do anything more than cause an occasional pipe stall?
**Edit**: I realize that there are ways to *replace* the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.
However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks! | 2008/10/29 | [
"https://Stackoverflow.com/questions/247639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3778/"
] | The alignment will be picked by the compiler according to its defaults, this will probably end up as four-bytes under GCC / MSVC.
This should only be a problem if there is code (SIMD/DMA) that requires a specific alignment. In this case you should be able to use compiler directives to ensure that member\_list\_store\_d is aligned, or increase the size by (alignment-1) and use an appropriate offset. | Allocate the char array `member_list_store_d` with malloc or global operator new[], either of which will give storage aligned for any type.
Edit: Just read the OP again - you don't want to pay for another pointer. Will read again in the morning. |
247,639 | I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:
* *Pool*. This is a class which allocates memory efficiently, for some definition of 'efficient'. *Pool* is guaranteed to return a chunk of memory that is aligned for the requested size.
* *Obj\_list*. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of *Obj\_list* is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.
* *Aggregate*. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. *Aggregate*s can be empty, or manage an arbitrary number of objects.
In this example, *Aggregate* items are always allocated from *Pool*s, so they are always aligned. The only occurrences of *Obj\_list* in this example are the 'hidden' members in *Aggregate* objects, and therefore they are always allocated using *placement new*. Here are the support classes:
```
class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
```
And here is Aggregate. Note that member declaration *member\_list\_store\_d*:
```
// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
```
It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:
```
Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
```
You may be tempted to suggest that we replace the char array with a pointer to the *Obj\_list* type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an *Obj\_list* would cost one more pointer in the case when *Aggregate* objects *do* have members.
Besides that, I don't really want to get distracted from the main question here, which is alignment. I *think* the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' *new*.
So, does the above construct do anything more than cause an occasional pipe stall?
**Edit**: I realize that there are ways to *replace* the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.
However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks! | 2008/10/29 | [
"https://Stackoverflow.com/questions/247639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3778/"
] | Ok - had a chance to read it properly. You have an alignment problem, and invoke undefined behaviour when you access the char array as an Obj\_list. Most likely your platform will do one of three things: let you get away with it, let you get away with it at a runtime penalty or occasionally crash with a bus error.
Your portable options to fix this are:
* allocate the storage with malloc or
a global allocation function, but
you think this is too
expensive.
* as Arkadiy says, make your buffer an Obj\_list member:
```
Obj_list list;
```
but you now don't want to pay the cost of construction. You could mitigate this by providing an inline do-nothing constructor to be used only to create this instance - as posted the default constructor would do. If you follow this route, strongly consider invoking the dtor
```
list.~Obj_list();
```
before doing a placement new into this storage.
Otherwise, I think you are left with non portable options: either rely on your platform's tolerance of misaligned accesses, or else use any nonportable options your compiler gives you.
Disclaimer: It's entirely possible I'm missing a trick with unions or some such. It's an unusual problem. | The alignment will be picked by the compiler according to its defaults, this will probably end up as four-bytes under GCC / MSVC.
This should only be a problem if there is code (SIMD/DMA) that requires a specific alignment. In this case you should be able to use compiler directives to ensure that member\_list\_store\_d is aligned, or increase the size by (alignment-1) and use an appropriate offset. |
247,639 | I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:
* *Pool*. This is a class which allocates memory efficiently, for some definition of 'efficient'. *Pool* is guaranteed to return a chunk of memory that is aligned for the requested size.
* *Obj\_list*. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of *Obj\_list* is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.
* *Aggregate*. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. *Aggregate*s can be empty, or manage an arbitrary number of objects.
In this example, *Aggregate* items are always allocated from *Pool*s, so they are always aligned. The only occurrences of *Obj\_list* in this example are the 'hidden' members in *Aggregate* objects, and therefore they are always allocated using *placement new*. Here are the support classes:
```
class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
```
And here is Aggregate. Note that member declaration *member\_list\_store\_d*:
```
// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
```
It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:
```
Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
```
You may be tempted to suggest that we replace the char array with a pointer to the *Obj\_list* type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an *Obj\_list* would cost one more pointer in the case when *Aggregate* objects *do* have members.
Besides that, I don't really want to get distracted from the main question here, which is alignment. I *think* the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' *new*.
So, does the above construct do anything more than cause an occasional pipe stall?
**Edit**: I realize that there are ways to *replace* the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.
However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks! | 2008/10/29 | [
"https://Stackoverflow.com/questions/247639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3778/"
] | If you want to ensure alignment of your structures, just do a
```
// MSVC
#pragma pack(push,1)
// structure definitions
#pragma pack(pop)
// *nix
struct YourStruct
{
....
} __attribute__((packed));
```
To ensure 1 byte alignment of your char array in Aggregate | Allocate the char array `member_list_store_d` with malloc or global operator new[], either of which will give storage aligned for any type.
Edit: Just read the OP again - you don't want to pay for another pointer. Will read again in the morning. |
247,639 | I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:
* *Pool*. This is a class which allocates memory efficiently, for some definition of 'efficient'. *Pool* is guaranteed to return a chunk of memory that is aligned for the requested size.
* *Obj\_list*. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of *Obj\_list* is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.
* *Aggregate*. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. *Aggregate*s can be empty, or manage an arbitrary number of objects.
In this example, *Aggregate* items are always allocated from *Pool*s, so they are always aligned. The only occurrences of *Obj\_list* in this example are the 'hidden' members in *Aggregate* objects, and therefore they are always allocated using *placement new*. Here are the support classes:
```
class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
```
And here is Aggregate. Note that member declaration *member\_list\_store\_d*:
```
// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
```
It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:
```
Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
```
You may be tempted to suggest that we replace the char array with a pointer to the *Obj\_list* type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an *Obj\_list* would cost one more pointer in the case when *Aggregate* objects *do* have members.
Besides that, I don't really want to get distracted from the main question here, which is alignment. I *think* the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' *new*.
So, does the above construct do anything more than cause an occasional pipe stall?
**Edit**: I realize that there are ways to *replace* the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.
However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks! | 2008/10/29 | [
"https://Stackoverflow.com/questions/247639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3778/"
] | Can you simply have an instance of Obj\_list inside Aggregate? IOW, something along the lines of
class Aggregate : public Lesser
{
...
protected:
Obj\_list list;
};
I must be missing something, but I can't figure why this is bad.
As to your question - it's perfectly compiler-dependent. Most compilers, though, will align every member at word boundary by default, even if the member's type does not need to be aligned that way for correct access. | Allocate the char array `member_list_store_d` with malloc or global operator new[], either of which will give storage aligned for any type.
Edit: Just read the OP again - you don't want to pay for another pointer. Will read again in the morning. |
247,639 | I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:
* *Pool*. This is a class which allocates memory efficiently, for some definition of 'efficient'. *Pool* is guaranteed to return a chunk of memory that is aligned for the requested size.
* *Obj\_list*. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of *Obj\_list* is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.
* *Aggregate*. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. *Aggregate*s can be empty, or manage an arbitrary number of objects.
In this example, *Aggregate* items are always allocated from *Pool*s, so they are always aligned. The only occurrences of *Obj\_list* in this example are the 'hidden' members in *Aggregate* objects, and therefore they are always allocated using *placement new*. Here are the support classes:
```
class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
```
And here is Aggregate. Note that member declaration *member\_list\_store\_d*:
```
// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
```
It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:
```
Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
```
You may be tempted to suggest that we replace the char array with a pointer to the *Obj\_list* type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an *Obj\_list* would cost one more pointer in the case when *Aggregate* objects *do* have members.
Besides that, I don't really want to get distracted from the main question here, which is alignment. I *think* the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' *new*.
So, does the above construct do anything more than cause an occasional pipe stall?
**Edit**: I realize that there are ways to *replace* the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.
However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks! | 2008/10/29 | [
"https://Stackoverflow.com/questions/247639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3778/"
] | Ok - had a chance to read it properly. You have an alignment problem, and invoke undefined behaviour when you access the char array as an Obj\_list. Most likely your platform will do one of three things: let you get away with it, let you get away with it at a runtime penalty or occasionally crash with a bus error.
Your portable options to fix this are:
* allocate the storage with malloc or
a global allocation function, but
you think this is too
expensive.
* as Arkadiy says, make your buffer an Obj\_list member:
```
Obj_list list;
```
but you now don't want to pay the cost of construction. You could mitigate this by providing an inline do-nothing constructor to be used only to create this instance - as posted the default constructor would do. If you follow this route, strongly consider invoking the dtor
```
list.~Obj_list();
```
before doing a placement new into this storage.
Otherwise, I think you are left with non portable options: either rely on your platform's tolerance of misaligned accesses, or else use any nonportable options your compiler gives you.
Disclaimer: It's entirely possible I'm missing a trick with unions or some such. It's an unusual problem. | Allocate the char array `member_list_store_d` with malloc or global operator new[], either of which will give storage aligned for any type.
Edit: Just read the OP again - you don't want to pay for another pointer. Will read again in the morning. |
247,639 | I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:
* *Pool*. This is a class which allocates memory efficiently, for some definition of 'efficient'. *Pool* is guaranteed to return a chunk of memory that is aligned for the requested size.
* *Obj\_list*. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of *Obj\_list* is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.
* *Aggregate*. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. *Aggregate*s can be empty, or manage an arbitrary number of objects.
In this example, *Aggregate* items are always allocated from *Pool*s, so they are always aligned. The only occurrences of *Obj\_list* in this example are the 'hidden' members in *Aggregate* objects, and therefore they are always allocated using *placement new*. Here are the support classes:
```
class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
```
And here is Aggregate. Note that member declaration *member\_list\_store\_d*:
```
// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
```
It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:
```
Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
```
You may be tempted to suggest that we replace the char array with a pointer to the *Obj\_list* type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an *Obj\_list* would cost one more pointer in the case when *Aggregate* objects *do* have members.
Besides that, I don't really want to get distracted from the main question here, which is alignment. I *think* the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' *new*.
So, does the above construct do anything more than cause an occasional pipe stall?
**Edit**: I realize that there are ways to *replace* the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.
However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks! | 2008/10/29 | [
"https://Stackoverflow.com/questions/247639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3778/"
] | Ok - had a chance to read it properly. You have an alignment problem, and invoke undefined behaviour when you access the char array as an Obj\_list. Most likely your platform will do one of three things: let you get away with it, let you get away with it at a runtime penalty or occasionally crash with a bus error.
Your portable options to fix this are:
* allocate the storage with malloc or
a global allocation function, but
you think this is too
expensive.
* as Arkadiy says, make your buffer an Obj\_list member:
```
Obj_list list;
```
but you now don't want to pay the cost of construction. You could mitigate this by providing an inline do-nothing constructor to be used only to create this instance - as posted the default constructor would do. If you follow this route, strongly consider invoking the dtor
```
list.~Obj_list();
```
before doing a placement new into this storage.
Otherwise, I think you are left with non portable options: either rely on your platform's tolerance of misaligned accesses, or else use any nonportable options your compiler gives you.
Disclaimer: It's entirely possible I'm missing a trick with unions or some such. It's an unusual problem. | If you want to ensure alignment of your structures, just do a
```
// MSVC
#pragma pack(push,1)
// structure definitions
#pragma pack(pop)
// *nix
struct YourStruct
{
....
} __attribute__((packed));
```
To ensure 1 byte alignment of your char array in Aggregate |
247,639 | I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:
* *Pool*. This is a class which allocates memory efficiently, for some definition of 'efficient'. *Pool* is guaranteed to return a chunk of memory that is aligned for the requested size.
* *Obj\_list*. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of *Obj\_list* is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.
* *Aggregate*. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. *Aggregate*s can be empty, or manage an arbitrary number of objects.
In this example, *Aggregate* items are always allocated from *Pool*s, so they are always aligned. The only occurrences of *Obj\_list* in this example are the 'hidden' members in *Aggregate* objects, and therefore they are always allocated using *placement new*. Here are the support classes:
```
class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
```
And here is Aggregate. Note that member declaration *member\_list\_store\_d*:
```
// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
```
It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:
```
Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
```
You may be tempted to suggest that we replace the char array with a pointer to the *Obj\_list* type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an *Obj\_list* would cost one more pointer in the case when *Aggregate* objects *do* have members.
Besides that, I don't really want to get distracted from the main question here, which is alignment. I *think* the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' *new*.
So, does the above construct do anything more than cause an occasional pipe stall?
**Edit**: I realize that there are ways to *replace* the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.
However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks! | 2008/10/29 | [
"https://Stackoverflow.com/questions/247639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3778/"
] | Ok - had a chance to read it properly. You have an alignment problem, and invoke undefined behaviour when you access the char array as an Obj\_list. Most likely your platform will do one of three things: let you get away with it, let you get away with it at a runtime penalty or occasionally crash with a bus error.
Your portable options to fix this are:
* allocate the storage with malloc or
a global allocation function, but
you think this is too
expensive.
* as Arkadiy says, make your buffer an Obj\_list member:
```
Obj_list list;
```
but you now don't want to pay the cost of construction. You could mitigate this by providing an inline do-nothing constructor to be used only to create this instance - as posted the default constructor would do. If you follow this route, strongly consider invoking the dtor
```
list.~Obj_list();
```
before doing a placement new into this storage.
Otherwise, I think you are left with non portable options: either rely on your platform's tolerance of misaligned accesses, or else use any nonportable options your compiler gives you.
Disclaimer: It's entirely possible I'm missing a trick with unions or some such. It's an unusual problem. | Can you simply have an instance of Obj\_list inside Aggregate? IOW, something along the lines of
class Aggregate : public Lesser
{
...
protected:
Obj\_list list;
};
I must be missing something, but I can't figure why this is bad.
As to your question - it's perfectly compiler-dependent. Most compilers, though, will align every member at word boundary by default, even if the member's type does not need to be aligned that way for correct access. |
22,962 | Not all nations provide education in the national tongue.
In India, being educated in English is generally preferred.
I am looking for any study with details about the situations in different countries about this - with details about to what level (primary, secondary school, bachelors or masters) education in the national tongue is provided.
Is there any recent trend among the parents to switch to English?
Please provide any study which would be of help. Thanks. | 2017/05/18 | [
"https://linguistics.stackexchange.com/questions/22962",
"https://linguistics.stackexchange.com",
"https://linguistics.stackexchange.com/users/16920/"
] | I suspect that there are not any *good* studies that will give you a comprehensive answer. You might be able to find a compilation of official national educational policies that covers a sufficient number of countries, but official policy and reality are different things. For example, policy used to be in Tanzania and AFAIK still in Kenya that for one or two years there would be "mother tongue education", but policy was doesn't reflect reality when there exist no mother tongue resources (for which reason Kenya and Tanzania differed in the extent to which they *could* provide mother tongue education, and this also accounts substantially for the actual high degree of mother tongue instruction in South Africa, whose law is [here](http://www.education.gov.za/Portals/0/Documents/Policies/GET/LanguageEducationPolicy1997.pdf?ver=2007-08-22-083918-000)). This [study](http://www.mdpi.com/2071-1050/5/5/1994/pdf) speaks of the benefits of "local language" instruction, but the case study involves primary schools in Zanzibar where the national language, Swahili, is actually the local language.
Indeed, actual "mother tongue" education is rarely even a policy reality, instead you find "local language" education (which differ when people move around). National-level surveys of language policy and attitudes at least in Africa are few, far-between, and not particularly reliable. I would hesitate to extrapolate from European language practices to the rest of the world. | A Google search will bring up a huge number of articles. Also look at UNESCO and UNICEF and the Global Reading Network websites. There is a big international push for mother tongue-based education (also referred to as multilingual education) and a number of countries have introduced MLE, but on a large scale across all languages, it is not feasible for a range of reasons including lack of materials, lack of orthographies, cost, etc. |
32,859,367 | I am getting these errors using `sbt assembly`.
I am using Spark which seems to be at the root of this problem.
```
val Spark = Seq(
"org.apache.spark" %% "spark-core" % sparkVersion,
"org.apache.spark" %% "spark-sql" % sparkVersion,
"org.apache.spark" %% "spark-streaming" % sparkVersion
)
```
Error:
```
[error] 12 errors were encountered during merge
[trace] Stack trace suppressed: run last coreBackend/*:assembly for the full output.
[trace] Stack trace suppressed: run last core/*:assembly for the full output.
[trace] Stack trace suppressed: run last commons/*:assembly for the full output.
[error] (coreBackend/*:assembly) deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.osgi/org.osgi.core/org.osgi.core-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.osgi/org.osgi.compendium/org.osgi.compendium-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Absent.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Absent.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Function.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Function.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Optional$1$1.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1$1.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Optional$1.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Optional.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Present.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Present.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Supplier.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Supplier.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-common/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-api/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-common/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-api/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-common/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-api/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-core_2.11/spark-core_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-launcher_2.11/spark-launcher_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.spark-project.spark/unused/unused-1.0.0.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-shuffle_2.11/spark-network-shuffle_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-unsafe_2.11/spark-unsafe_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-sql_2.11/spark-sql_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-catalyst_2.11/spark-catalyst_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-streaming_2.11/spark-streaming_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] (core/*:assembly) deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.core/jars/org.osgi.core-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.compendium/jars/org.osgi.compendium-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Absent.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Absent.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Function.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Function.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Optional$1$1.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1$1.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Optional$1.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Optional.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Present.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Present.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Supplier.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Supplier.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-core_2.11/jars/spark-core_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-launcher_2.11/jars/spark-launcher_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.spark-project.spark/unused/jars/unused-1.0.0.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-shuffle_2.11/jars/spark-network-shuffle_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-unsafe_2.11/jars/spark-unsafe_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-sql_2.11/jars/spark-sql_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-catalyst_2.11/jars/spark-catalyst_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-streaming_2.11/jars/spark-streaming_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] (commons/*:assembly) deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.core/jars/org.osgi.core-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.compendium/jars/org.osgi.compendium-4.3.1.jar:OSGI-OPT/bnd.bnd
```
I tried all the recommend solutions here with no luck.
[sbt-assembly: deduplication found error](https://stackoverflow.com/questions/25144484/sbt-assembly-deduplication-found-error?rq=1)
[deduplicating commons-validator - sbt assembly](https://stackoverflow.com/questions/30574262/deduplicating-commons-validator-sbt-assembly)
[spark + sbt-assembly: "deduplicate: different file contents found in the following"](https://stackoverflow.com/questions/30446984/spark-sbt-assembly-deduplicate-different-file-contents-found-in-the-followi) | 2015/09/30 | [
"https://Stackoverflow.com/questions/32859367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417896/"
] | This is not exactly an answer to the problem, but it is a workaround.
*I hope this saves a few hundred man-hours.*
Use [`sbt-native-packager`](http://www.scala-sbt.org/sbt-native-packager/) instead of `sbt-assembly`.
Add to `plugins.sbt`:
```
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.0.0")
```
And in your `build.sbt`
```
enablePlugins(JavaAppPackaging)
enablePlugins(UniversalPlugin)
```
To build the files for multiple Scala versions use the +
```
+ universal:packageBin
```
The output will tell you where the file was created.
Unfortunately the generated jars are zipped. It is not a fat jar. (to generate a fat jar would require `sbt-assembly` which has the same issues)
To overcome this, I made a simple script (in SBT) that unzips the generated files and writes the jar paths to a file so I can easily build a Spark submit script.
```
packageBin in TxtFormat := {
val zippedJar = "core-backend-1.0.zip"
val basePath = target.value / "universal"
// Unzip to folder of JARs
IO.unzip(basePath / zippedJar, basePath)
val fileMappings = (mappings in Universal).value
val sparkScriptOut = basePath / s"${packageName.value}.txt"
// append all mappings to the list
fileMappings foreach {
case (file, name) => IO.append(sparkScriptOut, s"core-backend-1.0/$name${IO.Newline}")
}
sparkScriptOut
}
```
After building the zip, use this to execute the task:
```
+ txtFormat:packageBin
``` | ```
assemblyMergeStrategy in assembly := {
case PathList("org", "apache", xs @ _*) => MergeStrategy.last
case PathList("com", "google", xs @ _*) => MergeStrategy.last
case x =>
val oldStrategy = (assemblyMergeStrategy in assembly).value
oldStrategy(x)
}
```
This works for me. |
32,859,367 | I am getting these errors using `sbt assembly`.
I am using Spark which seems to be at the root of this problem.
```
val Spark = Seq(
"org.apache.spark" %% "spark-core" % sparkVersion,
"org.apache.spark" %% "spark-sql" % sparkVersion,
"org.apache.spark" %% "spark-streaming" % sparkVersion
)
```
Error:
```
[error] 12 errors were encountered during merge
[trace] Stack trace suppressed: run last coreBackend/*:assembly for the full output.
[trace] Stack trace suppressed: run last core/*:assembly for the full output.
[trace] Stack trace suppressed: run last commons/*:assembly for the full output.
[error] (coreBackend/*:assembly) deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.osgi/org.osgi.core/org.osgi.core-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.osgi/org.osgi.compendium/org.osgi.compendium-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Absent.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Absent.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Function.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Function.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Optional$1$1.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1$1.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Optional$1.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Optional.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Present.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Present.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Supplier.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Supplier.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-common/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-api/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-common/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-api/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-common/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-api/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-core_2.11/spark-core_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-launcher_2.11/spark-launcher_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.spark-project.spark/unused/unused-1.0.0.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-shuffle_2.11/spark-network-shuffle_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-unsafe_2.11/spark-unsafe_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-sql_2.11/spark-sql_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-catalyst_2.11/spark-catalyst_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-streaming_2.11/spark-streaming_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] (core/*:assembly) deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.core/jars/org.osgi.core-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.compendium/jars/org.osgi.compendium-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Absent.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Absent.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Function.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Function.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Optional$1$1.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1$1.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Optional$1.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Optional.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Present.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Present.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Supplier.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Supplier.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-core_2.11/jars/spark-core_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-launcher_2.11/jars/spark-launcher_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.spark-project.spark/unused/jars/unused-1.0.0.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-shuffle_2.11/jars/spark-network-shuffle_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-unsafe_2.11/jars/spark-unsafe_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-sql_2.11/jars/spark-sql_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-catalyst_2.11/jars/spark-catalyst_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-streaming_2.11/jars/spark-streaming_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] (commons/*:assembly) deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.core/jars/org.osgi.core-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.compendium/jars/org.osgi.compendium-4.3.1.jar:OSGI-OPT/bnd.bnd
```
I tried all the recommend solutions here with no luck.
[sbt-assembly: deduplication found error](https://stackoverflow.com/questions/25144484/sbt-assembly-deduplication-found-error?rq=1)
[deduplicating commons-validator - sbt assembly](https://stackoverflow.com/questions/30574262/deduplicating-commons-validator-sbt-assembly)
[spark + sbt-assembly: "deduplicate: different file contents found in the following"](https://stackoverflow.com/questions/30446984/spark-sbt-assembly-deduplicate-different-file-contents-found-in-the-followi) | 2015/09/30 | [
"https://Stackoverflow.com/questions/32859367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417896/"
] | This is not exactly an answer to the problem, but it is a workaround.
*I hope this saves a few hundred man-hours.*
Use [`sbt-native-packager`](http://www.scala-sbt.org/sbt-native-packager/) instead of `sbt-assembly`.
Add to `plugins.sbt`:
```
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.0.0")
```
And in your `build.sbt`
```
enablePlugins(JavaAppPackaging)
enablePlugins(UniversalPlugin)
```
To build the files for multiple Scala versions use the +
```
+ universal:packageBin
```
The output will tell you where the file was created.
Unfortunately the generated jars are zipped. It is not a fat jar. (to generate a fat jar would require `sbt-assembly` which has the same issues)
To overcome this, I made a simple script (in SBT) that unzips the generated files and writes the jar paths to a file so I can easily build a Spark submit script.
```
packageBin in TxtFormat := {
val zippedJar = "core-backend-1.0.zip"
val basePath = target.value / "universal"
// Unzip to folder of JARs
IO.unzip(basePath / zippedJar, basePath)
val fileMappings = (mappings in Universal).value
val sparkScriptOut = basePath / s"${packageName.value}.txt"
// append all mappings to the list
fileMappings foreach {
case (file, name) => IO.append(sparkScriptOut, s"core-backend-1.0/$name${IO.Newline}")
}
sparkScriptOut
}
```
After building the zip, use this to execute the task:
```
+ txtFormat:packageBin
``` | Spark dependencies should be provided by the cluster, add the "Provided":
```
val Spark = Seq(
"org.apache.spark" %% "spark-core" % sparkVersion % Provided,
"org.apache.spark" %% "spark-sql" % sparkVersion % Provided,
"org.apache.spark" %% "spark-streaming" % sparkVersion % Provided
)
``` |
32,859,367 | I am getting these errors using `sbt assembly`.
I am using Spark which seems to be at the root of this problem.
```
val Spark = Seq(
"org.apache.spark" %% "spark-core" % sparkVersion,
"org.apache.spark" %% "spark-sql" % sparkVersion,
"org.apache.spark" %% "spark-streaming" % sparkVersion
)
```
Error:
```
[error] 12 errors were encountered during merge
[trace] Stack trace suppressed: run last coreBackend/*:assembly for the full output.
[trace] Stack trace suppressed: run last core/*:assembly for the full output.
[trace] Stack trace suppressed: run last commons/*:assembly for the full output.
[error] (coreBackend/*:assembly) deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.osgi/org.osgi.core/org.osgi.core-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.osgi/org.osgi.compendium/org.osgi.compendium-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Absent.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Absent.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Function.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Function.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Optional$1$1.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1$1.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Optional$1.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Optional.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Present.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Present.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/bundles/com.google.guava/guava/guava-18.0.jar:com/google/common/base/Supplier.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Supplier.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-common/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-api/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-common/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-api/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-common/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.hadoop/hadoop-yarn-api/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-core_2.11/spark-core_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-launcher_2.11/spark-launcher_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.spark-project.spark/unused/unused-1.0.0.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-common_2.11/spark-network-common_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-network-shuffle_2.11/spark-network-shuffle_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-unsafe_2.11/spark-unsafe_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-sql_2.11/spark-sql_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-catalyst_2.11/spark-catalyst_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Volumes/COYOTE/Developer/tibra/lib_managed/jars/org.apache.spark/spark-streaming_2.11/spark-streaming_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] (core/*:assembly) deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.core/jars/org.osgi.core-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.compendium/jars/org.osgi.compendium-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Absent.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Absent.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Function.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Function.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Optional$1$1.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1$1.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Optional$1.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional$1.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Optional.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Optional.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Present.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Present.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/com.google.guava/guava/bundles/guava-18.0.jar:com/google/common/base/Supplier.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:com/google/common/base/Supplier.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factories/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/factory/providers/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-common/jars/hadoop-yarn-common-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] /Users/bryan/.ivy2/cache/org.apache.hadoop/hadoop-yarn-api/jars/hadoop-yarn-api-2.2.0.jar:org/apache/hadoop/yarn/util/package-info.class
[error] deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-core_2.11/jars/spark-core_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-launcher_2.11/jars/spark-launcher_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.spark-project.spark/unused/jars/unused-1.0.0.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-common_2.11/jars/spark-network-common_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-network-shuffle_2.11/jars/spark-network-shuffle_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-unsafe_2.11/jars/spark-unsafe_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-sql_2.11/jars/spark-sql_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-catalyst_2.11/jars/spark-catalyst_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] /Users/bryan/.ivy2/cache/org.apache.spark/spark-streaming_2.11/jars/spark-streaming_2.11-1.5.1.jar:org/apache/spark/unused/UnusedStubClass.class
[error] (commons/*:assembly) deduplicate: different file contents found in the following:
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.core/jars/org.osgi.core-4.3.1.jar:OSGI-OPT/bnd.bnd
[error] /Users/bryan/.ivy2/cache/org.osgi/org.osgi.compendium/jars/org.osgi.compendium-4.3.1.jar:OSGI-OPT/bnd.bnd
```
I tried all the recommend solutions here with no luck.
[sbt-assembly: deduplication found error](https://stackoverflow.com/questions/25144484/sbt-assembly-deduplication-found-error?rq=1)
[deduplicating commons-validator - sbt assembly](https://stackoverflow.com/questions/30574262/deduplicating-commons-validator-sbt-assembly)
[spark + sbt-assembly: "deduplicate: different file contents found in the following"](https://stackoverflow.com/questions/30446984/spark-sbt-assembly-deduplicate-different-file-contents-found-in-the-followi) | 2015/09/30 | [
"https://Stackoverflow.com/questions/32859367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417896/"
] | This is not exactly an answer to the problem, but it is a workaround.
*I hope this saves a few hundred man-hours.*
Use [`sbt-native-packager`](http://www.scala-sbt.org/sbt-native-packager/) instead of `sbt-assembly`.
Add to `plugins.sbt`:
```
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.0.0")
```
And in your `build.sbt`
```
enablePlugins(JavaAppPackaging)
enablePlugins(UniversalPlugin)
```
To build the files for multiple Scala versions use the +
```
+ universal:packageBin
```
The output will tell you where the file was created.
Unfortunately the generated jars are zipped. It is not a fat jar. (to generate a fat jar would require `sbt-assembly` which has the same issues)
To overcome this, I made a simple script (in SBT) that unzips the generated files and writes the jar paths to a file so I can easily build a Spark submit script.
```
packageBin in TxtFormat := {
val zippedJar = "core-backend-1.0.zip"
val basePath = target.value / "universal"
// Unzip to folder of JARs
IO.unzip(basePath / zippedJar, basePath)
val fileMappings = (mappings in Universal).value
val sparkScriptOut = basePath / s"${packageName.value}.txt"
// append all mappings to the list
fileMappings foreach {
case (file, name) => IO.append(sparkScriptOut, s"core-backend-1.0/$name${IO.Newline}")
}
sparkScriptOut
}
```
After building the zip, use this to execute the task:
```
+ txtFormat:packageBin
``` | I know this is an old question but none of the solutions given so far handle the case I encountered.
It appears there are cases where a jar that is not "provided" has dependencies on jars that are. If the transitive dependencies pull in jars with conflicting content, you can see this same error. In certain cases, adding those jars as dependencies marked "provided" has not resolved the conflicts between them when the assembly is being built. The only solution I have found is to explicitly exclude them from the assembly as follows.
```
assemblyExcludedJars in assembly := {
val cp = (fullClasspath in assembly).value
cp filter { el =>
(el.data.getName == "unused-1.0.0.jar") ||
(el.data.getName == "spark-tags_2.11-2.1.0.jar")
}
}
``` |
47,459,747 | I am trying to install pygame with pip install . but every time i tried i faced to this error.
>
> Retrying (Retry(total=4, connect=None, read=None, redirect=None))
> after connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying
> (Retry(total=3, connect=None, read=None, redirect=None)) after
> connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying
> (Retry(total=2, connect=None, read=None, redirect=None)) after
> connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Operation
> cancelled by user\*
>
>
>
I have done it with other libraries but I faced the same problem | 2017/11/23 | [
"https://Stackoverflow.com/questions/47459747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8385256/"
] | Go to this [Website](https://www.lfd.uci.edu/~gohlke/pythonlibs/), download the pygame‑1.9.3‑cp36‑cp36m‑win\_amd64.whl file, open cmd, change directory to the folder you have the .whl file end type:
`pip install pygame‑1.9.3‑cp36‑cp36m‑win_amd64.whl` .
This works when you are trying to install packages and firewalls are blocking the connection. | It looks like `pip` is not connecting to the internet. I have a few options --
I don't know if they will work, but you can try them.
1. Try to reinstall `pip` (`pip3` if using python3) I had to do this on my
systeme, as `pip3` didn't work initally either.
2. Check and see if you can ping a website from your terminal to check connectivity. You could have an error with your terminal (if using linux) and not with python itself.
Good luck, and hope this helps! |
47,459,747 | I am trying to install pygame with pip install . but every time i tried i faced to this error.
>
> Retrying (Retry(total=4, connect=None, read=None, redirect=None))
> after connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying
> (Retry(total=3, connect=None, read=None, redirect=None)) after
> connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying
> (Retry(total=2, connect=None, read=None, redirect=None)) after
> connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Operation
> cancelled by user\*
>
>
>
I have done it with other libraries but I faced the same problem | 2017/11/23 | [
"https://Stackoverflow.com/questions/47459747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8385256/"
] | I had the same issue in windows. My antivirus was blocking PIP requests. Try disabling your antivirus(in my case manually killed it from task manager). | It looks like `pip` is not connecting to the internet. I have a few options --
I don't know if they will work, but you can try them.
1. Try to reinstall `pip` (`pip3` if using python3) I had to do this on my
systeme, as `pip3` didn't work initally either.
2. Check and see if you can ping a website from your terminal to check connectivity. You could have an error with your terminal (if using linux) and not with python itself.
Good luck, and hope this helps! |
47,459,747 | I am trying to install pygame with pip install . but every time i tried i faced to this error.
>
> Retrying (Retry(total=4, connect=None, read=None, redirect=None))
> after connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying
> (Retry(total=3, connect=None, read=None, redirect=None)) after
> connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying
> (Retry(total=2, connect=None, read=None, redirect=None)) after
> connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Operation
> cancelled by user\*
>
>
>
I have done it with other libraries but I faced the same problem | 2017/11/23 | [
"https://Stackoverflow.com/questions/47459747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8385256/"
] | I had same error message when I tried to install Python packages on my laptop with Windows 10 OS.
I tried all methods recommended online and it still didn't work. I have been noticing for a while that Windows 10 automatically set proxy off causing Internet access problem sometime.
Then I googled with keywords: 'windows 10 automatic proxy setting off'. Someone mentioned to modify regedit key value of [ProxyEnabled=1] under Computer\HKEY\_CURRENT\_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
I opened the regedit and found it's [ProxyEnabled=1]. I compared HKEY\_CURRENT\_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
with another workstation with relatively clean image. It's [ProxyEnabled=0] and no other extra entry for Proxy.
Solution: set ProxyEnabled=0 and delete any other Proxy entries.
It worked successfully! pip install package\_name | It looks like `pip` is not connecting to the internet. I have a few options --
I don't know if they will work, but you can try them.
1. Try to reinstall `pip` (`pip3` if using python3) I had to do this on my
systeme, as `pip3` didn't work initally either.
2. Check and see if you can ping a website from your terminal to check connectivity. You could have an error with your terminal (if using linux) and not with python itself.
Good luck, and hope this helps! |
47,459,747 | I am trying to install pygame with pip install . but every time i tried i faced to this error.
>
> Retrying (Retry(total=4, connect=None, read=None, redirect=None))
> after connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying
> (Retry(total=3, connect=None, read=None, redirect=None)) after
> connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying
> (Retry(total=2, connect=None, read=None, redirect=None)) after
> connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Operation
> cancelled by user\*
>
>
>
I have done it with other libraries but I faced the same problem | 2017/11/23 | [
"https://Stackoverflow.com/questions/47459747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8385256/"
] | Go to this [Website](https://www.lfd.uci.edu/~gohlke/pythonlibs/), download the pygame‑1.9.3‑cp36‑cp36m‑win\_amd64.whl file, open cmd, change directory to the folder you have the .whl file end type:
`pip install pygame‑1.9.3‑cp36‑cp36m‑win_amd64.whl` .
This works when you are trying to install packages and firewalls are blocking the connection. | I had same error message when I tried to install Python packages on my laptop with Windows 10 OS.
I tried all methods recommended online and it still didn't work. I have been noticing for a while that Windows 10 automatically set proxy off causing Internet access problem sometime.
Then I googled with keywords: 'windows 10 automatic proxy setting off'. Someone mentioned to modify regedit key value of [ProxyEnabled=1] under Computer\HKEY\_CURRENT\_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
I opened the regedit and found it's [ProxyEnabled=1]. I compared HKEY\_CURRENT\_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
with another workstation with relatively clean image. It's [ProxyEnabled=0] and no other extra entry for Proxy.
Solution: set ProxyEnabled=0 and delete any other Proxy entries.
It worked successfully! pip install package\_name |
47,459,747 | I am trying to install pygame with pip install . but every time i tried i faced to this error.
>
> Retrying (Retry(total=4, connect=None, read=None, redirect=None))
> after connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying
> (Retry(total=3, connect=None, read=None, redirect=None)) after
> connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Retrying
> (Retry(total=2, connect=None, read=None, redirect=None)) after
> connection broken by 'ProxyError('Cannot connect to proxy.',
> NewConnectionError(': Failed to establish a new connection: [WinError
> 10061] No connection could be made because the target machine actively
> refused it',))': /simple/pygame-1-9-3-cp36-cp36m-win-amd64/ Operation
> cancelled by user\*
>
>
>
I have done it with other libraries but I faced the same problem | 2017/11/23 | [
"https://Stackoverflow.com/questions/47459747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8385256/"
] | I had the same issue in windows. My antivirus was blocking PIP requests. Try disabling your antivirus(in my case manually killed it from task manager). | I had same error message when I tried to install Python packages on my laptop with Windows 10 OS.
I tried all methods recommended online and it still didn't work. I have been noticing for a while that Windows 10 automatically set proxy off causing Internet access problem sometime.
Then I googled with keywords: 'windows 10 automatic proxy setting off'. Someone mentioned to modify regedit key value of [ProxyEnabled=1] under Computer\HKEY\_CURRENT\_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
I opened the regedit and found it's [ProxyEnabled=1]. I compared HKEY\_CURRENT\_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
with another workstation with relatively clean image. It's [ProxyEnabled=0] and no other extra entry for Proxy.
Solution: set ProxyEnabled=0 and delete any other Proxy entries.
It worked successfully! pip install package\_name |
36,066,548 | I would like to nest a protocol in my class to implement the delegate pattern like so :
```
class MyViewController : UIViewController {
protocol Delegate {
func eventHappened()
}
var delegate:MyViewController.Delegate?
private func myFunc() {
delegate?.eventHappened()
}
}
```
But the compiler will not allow it :
>
> Protocol 'Delegate' cannot be nested inside another declaration
>
>
>
I can easily make it work by declaring `MyViewControllerDelegate` outside of the class scope.
My question is *why* such a limitation ? | 2016/03/17 | [
"https://Stackoverflow.com/questions/36066548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327557/"
] | according to the [swift documenation](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/NestedTypes.html)
>
> Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support.
>
>
>
Given protocols are not on that list, it doesn't appear that it's currently supported.
It's possible they will add the feature at some point, (Swift was announced less than 2 years go after all). Any idea on why they won't or haven't would be speculation on my part. | A separate problem with your class is that `delegate` does not have a concrete type. You can get away with declaring it a `MyViewController.Delegate?` because it is an optional type and can be `.None`. But that just makes your private `myFunc` dead code. Only enumerations, classes, and structures can **conform** to a protocol. Which of those three types is `delegate`?
That said, this is not the cause of your problem. When I make a real type for `delegate` and make it conform to the `Delegate` protocol, I still get the same error.
```
class MyViewController: UIViewController {
protocol Delegate {
func eventHappened()
}
class Classy: Delegate {
func eventHappened() {
print("eventHappened")
}
}
var delegate: Classy? = Classy()
func myFunc() {
delegate?.eventHappened()
}
}
```
[](https://i.stack.imgur.com/o0dFY.png)
As an esoteric exercise this might be interesting in pushing the bounds of what a class might do but no one should every try to declare a protocol inside of a class. Protocols are all about type composition and collections. There is no code reuse scenario when you are limited to being in the same outer class. |
36,066,548 | I would like to nest a protocol in my class to implement the delegate pattern like so :
```
class MyViewController : UIViewController {
protocol Delegate {
func eventHappened()
}
var delegate:MyViewController.Delegate?
private func myFunc() {
delegate?.eventHappened()
}
}
```
But the compiler will not allow it :
>
> Protocol 'Delegate' cannot be nested inside another declaration
>
>
>
I can easily make it work by declaring `MyViewControllerDelegate` outside of the class scope.
My question is *why* such a limitation ? | 2016/03/17 | [
"https://Stackoverflow.com/questions/36066548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327557/"
] | according to the [swift documenation](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/NestedTypes.html)
>
> Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support.
>
>
>
Given protocols are not on that list, it doesn't appear that it's currently supported.
It's possible they will add the feature at some point, (Swift was announced less than 2 years go after all). Any idea on why they won't or haven't would be speculation on my part. | this is my work around:
```
protocol MyViewControllerDelegate : class {
func eventHappened()
}
class MyViewController : UIViewController {
typealias Delegate = MyViewControllerDelegate
weak var delegate: Delegate?
private func myFunc() {
delegate?.eventHappened()
}
}
``` |
36,066,548 | I would like to nest a protocol in my class to implement the delegate pattern like so :
```
class MyViewController : UIViewController {
protocol Delegate {
func eventHappened()
}
var delegate:MyViewController.Delegate?
private func myFunc() {
delegate?.eventHappened()
}
}
```
But the compiler will not allow it :
>
> Protocol 'Delegate' cannot be nested inside another declaration
>
>
>
I can easily make it work by declaring `MyViewControllerDelegate` outside of the class scope.
My question is *why* such a limitation ? | 2016/03/17 | [
"https://Stackoverflow.com/questions/36066548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327557/"
] | this is my work around:
```
protocol MyViewControllerDelegate : class {
func eventHappened()
}
class MyViewController : UIViewController {
typealias Delegate = MyViewControllerDelegate
weak var delegate: Delegate?
private func myFunc() {
delegate?.eventHappened()
}
}
``` | A separate problem with your class is that `delegate` does not have a concrete type. You can get away with declaring it a `MyViewController.Delegate?` because it is an optional type and can be `.None`. But that just makes your private `myFunc` dead code. Only enumerations, classes, and structures can **conform** to a protocol. Which of those three types is `delegate`?
That said, this is not the cause of your problem. When I make a real type for `delegate` and make it conform to the `Delegate` protocol, I still get the same error.
```
class MyViewController: UIViewController {
protocol Delegate {
func eventHappened()
}
class Classy: Delegate {
func eventHappened() {
print("eventHappened")
}
}
var delegate: Classy? = Classy()
func myFunc() {
delegate?.eventHappened()
}
}
```
[](https://i.stack.imgur.com/o0dFY.png)
As an esoteric exercise this might be interesting in pushing the bounds of what a class might do but no one should every try to declare a protocol inside of a class. Protocols are all about type composition and collections. There is no code reuse scenario when you are limited to being in the same outer class. |
36,097,446 | I have a data.frame that is a single column with 235,886 rows. Each row corresponds to a single word of the English language.
E.g.
```
> words[10000:10005,1]
```
[1] anticontagionist anticontagious anticonventional anticonventionalism anticonvulsive
[6] anticor
What I'd like to do is convert each row to a number based on the letters in it. So, if "a" = 1, "b" = 2, "c" = 3, and "d" = 4, then "abcd" = 10. Does anyone know of a way to do that?
My ultimate goal is to have a function that scans the data.frame for a given numeric value and returns all the strings, i.e. words, with that value. So, continuing from the example above, if I asked for the value 9, this function would return "dad" and any other rows having a numeric value of 9. | 2016/03/19 | [
"https://Stackoverflow.com/questions/36097446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6085225/"
] | ```
let count = reminderListsStructure.structure.reduce(0) { $0 + $1.1.list.count }
```
Something like this. Not enough info though, so I'm not 100% sure it works. | When you `reduce` a dictionary, the element type is a tuple of the Key and Value types, so you can use:
```
dictionary.reduce(0) { $0 + $1.1.list.count }
```
Or, you can get just the values from the dictionary and reduce that:
```
dictionary.values.reduce(0) { $0 + $1.list.count }
```
Note that since Dictionary.values returns a lazy iterator, there's not really a huge cost to using it. |
36,097,446 | I have a data.frame that is a single column with 235,886 rows. Each row corresponds to a single word of the English language.
E.g.
```
> words[10000:10005,1]
```
[1] anticontagionist anticontagious anticonventional anticonventionalism anticonvulsive
[6] anticor
What I'd like to do is convert each row to a number based on the letters in it. So, if "a" = 1, "b" = 2, "c" = 3, and "d" = 4, then "abcd" = 10. Does anyone know of a way to do that?
My ultimate goal is to have a function that scans the data.frame for a given numeric value and returns all the strings, i.e. words, with that value. So, continuing from the example above, if I asked for the value 9, this function would return "dad" and any other rows having a numeric value of 9. | 2016/03/19 | [
"https://Stackoverflow.com/questions/36097446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6085225/"
] | ```
let count = reminderListsStructure.structure.reduce(0) { $0 + $1.1.list.count }
```
Something like this. Not enough info though, so I'm not 100% sure it works. | I think [`flatMap`](http://swiftdoc.org/v2.2/protocol/SequenceType/#comment-func--flatmap-s_-sequencetype_-self-generator-element-throws-s) is a more appropriate choice here:
```
let input = [
1: [1],
2: [1, 2],
3: [1, 2, 3],
4: [1, 2, 3, 4],
5: [1, 2, 3, 4, 5]
]
let output = input.values.flatMap{$0}.count //15
``` |
36,097,446 | I have a data.frame that is a single column with 235,886 rows. Each row corresponds to a single word of the English language.
E.g.
```
> words[10000:10005,1]
```
[1] anticontagionist anticontagious anticonventional anticonventionalism anticonvulsive
[6] anticor
What I'd like to do is convert each row to a number based on the letters in it. So, if "a" = 1, "b" = 2, "c" = 3, and "d" = 4, then "abcd" = 10. Does anyone know of a way to do that?
My ultimate goal is to have a function that scans the data.frame for a given numeric value and returns all the strings, i.e. words, with that value. So, continuing from the example above, if I asked for the value 9, this function would return "dad" and any other rows having a numeric value of 9. | 2016/03/19 | [
"https://Stackoverflow.com/questions/36097446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6085225/"
] | ```
let count = reminderListsStructure.structure.reduce(0) { $0 + $1.1.list.count }
```
Something like this. Not enough info though, so I'm not 100% sure it works. | More simple and clear way goes like this,
```
var dict = ["x" : 1 , "y" : 2, "z" : 3]
let count = dict.reduce(0, { x, element in
//maybe here some condition
//if(element.value > 1){return x}
return x + 1
})
``` |
36,097,446 | I have a data.frame that is a single column with 235,886 rows. Each row corresponds to a single word of the English language.
E.g.
```
> words[10000:10005,1]
```
[1] anticontagionist anticontagious anticonventional anticonventionalism anticonvulsive
[6] anticor
What I'd like to do is convert each row to a number based on the letters in it. So, if "a" = 1, "b" = 2, "c" = 3, and "d" = 4, then "abcd" = 10. Does anyone know of a way to do that?
My ultimate goal is to have a function that scans the data.frame for a given numeric value and returns all the strings, i.e. words, with that value. So, continuing from the example above, if I asked for the value 9, this function would return "dad" and any other rows having a numeric value of 9. | 2016/03/19 | [
"https://Stackoverflow.com/questions/36097446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6085225/"
] | I think [`flatMap`](http://swiftdoc.org/v2.2/protocol/SequenceType/#comment-func--flatmap-s_-sequencetype_-self-generator-element-throws-s) is a more appropriate choice here:
```
let input = [
1: [1],
2: [1, 2],
3: [1, 2, 3],
4: [1, 2, 3, 4],
5: [1, 2, 3, 4, 5]
]
let output = input.values.flatMap{$0}.count //15
``` | When you `reduce` a dictionary, the element type is a tuple of the Key and Value types, so you can use:
```
dictionary.reduce(0) { $0 + $1.1.list.count }
```
Or, you can get just the values from the dictionary and reduce that:
```
dictionary.values.reduce(0) { $0 + $1.list.count }
```
Note that since Dictionary.values returns a lazy iterator, there's not really a huge cost to using it. |
36,097,446 | I have a data.frame that is a single column with 235,886 rows. Each row corresponds to a single word of the English language.
E.g.
```
> words[10000:10005,1]
```
[1] anticontagionist anticontagious anticonventional anticonventionalism anticonvulsive
[6] anticor
What I'd like to do is convert each row to a number based on the letters in it. So, if "a" = 1, "b" = 2, "c" = 3, and "d" = 4, then "abcd" = 10. Does anyone know of a way to do that?
My ultimate goal is to have a function that scans the data.frame for a given numeric value and returns all the strings, i.e. words, with that value. So, continuing from the example above, if I asked for the value 9, this function would return "dad" and any other rows having a numeric value of 9. | 2016/03/19 | [
"https://Stackoverflow.com/questions/36097446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6085225/"
] | When you `reduce` a dictionary, the element type is a tuple of the Key and Value types, so you can use:
```
dictionary.reduce(0) { $0 + $1.1.list.count }
```
Or, you can get just the values from the dictionary and reduce that:
```
dictionary.values.reduce(0) { $0 + $1.list.count }
```
Note that since Dictionary.values returns a lazy iterator, there's not really a huge cost to using it. | More simple and clear way goes like this,
```
var dict = ["x" : 1 , "y" : 2, "z" : 3]
let count = dict.reduce(0, { x, element in
//maybe here some condition
//if(element.value > 1){return x}
return x + 1
})
``` |
36,097,446 | I have a data.frame that is a single column with 235,886 rows. Each row corresponds to a single word of the English language.
E.g.
```
> words[10000:10005,1]
```
[1] anticontagionist anticontagious anticonventional anticonventionalism anticonvulsive
[6] anticor
What I'd like to do is convert each row to a number based on the letters in it. So, if "a" = 1, "b" = 2, "c" = 3, and "d" = 4, then "abcd" = 10. Does anyone know of a way to do that?
My ultimate goal is to have a function that scans the data.frame for a given numeric value and returns all the strings, i.e. words, with that value. So, continuing from the example above, if I asked for the value 9, this function would return "dad" and any other rows having a numeric value of 9. | 2016/03/19 | [
"https://Stackoverflow.com/questions/36097446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6085225/"
] | I think [`flatMap`](http://swiftdoc.org/v2.2/protocol/SequenceType/#comment-func--flatmap-s_-sequencetype_-self-generator-element-throws-s) is a more appropriate choice here:
```
let input = [
1: [1],
2: [1, 2],
3: [1, 2, 3],
4: [1, 2, 3, 4],
5: [1, 2, 3, 4, 5]
]
let output = input.values.flatMap{$0}.count //15
``` | More simple and clear way goes like this,
```
var dict = ["x" : 1 , "y" : 2, "z" : 3]
let count = dict.reduce(0, { x, element in
//maybe here some condition
//if(element.value > 1){return x}
return x + 1
})
``` |
4,876,737 | Hi there im using a ListView in wpf and have a few columns that have auto width, now i want some padding on them but im a bit unsure how to do this? i have a red background on my header and then text in there, but i want to have some space between the border of the box and the text...
 | 2011/02/02 | [
"https://Stackoverflow.com/questions/4876737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58553/"
] | You could modify the `HeaderTemplate` of the `GridViewColumn`
```
<GridViewColumn ...>
<GridViewColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Margin="5,0,5,0"/>
</DataTemplate>
</GridViewColumn.HeaderTemplate>
<GridViewColumnHeader Content="Some Header" Background="Red" />
</GridViewColumn>
``` | For anyone else coming across this, here is an option that's a little cleaner. Not specifying a key on the style has this apply to all columns. This also uses padding, like the OP wanted.
```
<ListView.Resources>
<Style TargetType="GridViewColumnHeader">
<Setter Property="Padding" Value="10,0" />
</Style>
</ListView.Resources>
``` |
33,010,751 | I followed a tutorial of new component NavigationView in Support Design Library and can't get through this error message
>
> java.lang.RuntimeException: Unable to start activity ComponentInfo{com.encore/com.encore.NavViewActivity}: android.view.InflateException: Binary XML file line #27: Error inflating class android.support.design.widget.NavigationView
>
>
>
```
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
<item name="android:colorPrimary">@color/PrimaryColor</item>
<item name="android:colorPrimaryDark">@color/PrimaryDarkColor</item>
<item name="windowActionModeOverlay">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
```
**layout file**
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/lib/com.encore.NavViewActivity"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<include
android:id="@+id/toolbar"
layout="@layout/tool_bar"
/>
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:menu="@menu/drawer"
/>
```
**java file**
```
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;
public class NavViewActivity extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.inbox:
Toast.makeText(getApplicationContext(),"Inbox Selected",Toast.LENGTH_SHORT).show();
ContentFragment fragment = new ContentFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.starred:
Toast.makeText(getApplicationContext(),"Stared Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.sent_mail:
Toast.makeText(getApplicationContext(),"Send Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.drafts:
Toast.makeText(getApplicationContext(),"Drafts Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.allmail:
Toast.makeText(getApplicationContext(),"All Mail Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.trash:
Toast.makeText(getApplicationContext(),"Trash Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.spam:
Toast.makeText(getApplicationContext(),"Spam Selected",Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
@Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
}
``` | 2015/10/08 | [
"https://Stackoverflow.com/questions/33010751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324789/"
] | I also encountered the same problem,Error exactly,Later I found out wrong here:menu->item->`android:icon="@drawable/ic_menu_camera"`,this`ic_menu_camera` header has `vector` only used in v21 or higher,so in system 5.0 or less useing can get the problems,than you can copy the following code in values folder and Named "drawables".code:`<resources xmlns:android="http://schemas.android.com/apk/res/android">
<item name="ic_menu_camera" type="drawable">@android:drawable/ic_menu_camera</item>
<item name="ic_menu_gallery" type="drawable">@android:drawable/ic_menu_gallery</item>
<item name="ic_menu_slideshow" type="drawable">@android:drawable/ic_menu_slideshow</item>
<item name="ic_menu_manage" type="drawable">@android:drawable/ic_menu_manage</item>
<item name="ic_menu_share" type="drawable">@android:drawable/ic_menu_share</item>
<item name="ic_menu_send" type="drawable">@android:drawable/ic_menu_send</item>
</resources>` | Try replacing `android:layout_gravity="start"`with `android:layout_gravity="right"` inside `NavigationView` layout. |
33,010,751 | I followed a tutorial of new component NavigationView in Support Design Library and can't get through this error message
>
> java.lang.RuntimeException: Unable to start activity ComponentInfo{com.encore/com.encore.NavViewActivity}: android.view.InflateException: Binary XML file line #27: Error inflating class android.support.design.widget.NavigationView
>
>
>
```
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
<item name="android:colorPrimary">@color/PrimaryColor</item>
<item name="android:colorPrimaryDark">@color/PrimaryDarkColor</item>
<item name="windowActionModeOverlay">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
```
**layout file**
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/lib/com.encore.NavViewActivity"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<include
android:id="@+id/toolbar"
layout="@layout/tool_bar"
/>
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:menu="@menu/drawer"
/>
```
**java file**
```
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;
public class NavViewActivity extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.inbox:
Toast.makeText(getApplicationContext(),"Inbox Selected",Toast.LENGTH_SHORT).show();
ContentFragment fragment = new ContentFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.starred:
Toast.makeText(getApplicationContext(),"Stared Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.sent_mail:
Toast.makeText(getApplicationContext(),"Send Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.drafts:
Toast.makeText(getApplicationContext(),"Drafts Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.allmail:
Toast.makeText(getApplicationContext(),"All Mail Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.trash:
Toast.makeText(getApplicationContext(),"Trash Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.spam:
Toast.makeText(getApplicationContext(),"Spam Selected",Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
@Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
}
``` | 2015/10/08 | [
"https://Stackoverflow.com/questions/33010751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324789/"
] | I also encountered the same problem,Error exactly,Later I found out wrong here:menu->item->`android:icon="@drawable/ic_menu_camera"`,this`ic_menu_camera` header has `vector` only used in v21 or higher,so in system 5.0 or less useing can get the problems,than you can copy the following code in values folder and Named "drawables".code:`<resources xmlns:android="http://schemas.android.com/apk/res/android">
<item name="ic_menu_camera" type="drawable">@android:drawable/ic_menu_camera</item>
<item name="ic_menu_gallery" type="drawable">@android:drawable/ic_menu_gallery</item>
<item name="ic_menu_slideshow" type="drawable">@android:drawable/ic_menu_slideshow</item>
<item name="ic_menu_manage" type="drawable">@android:drawable/ic_menu_manage</item>
<item name="ic_menu_share" type="drawable">@android:drawable/ic_menu_share</item>
<item name="ic_menu_send" type="drawable">@android:drawable/ic_menu_send</item>
</resources>` | check your navigation view by removing one of these and check your code is working or not
* app:headerLayout="@layout/nav\_header"
* app:menu="@menu/drawer"
if your logcat says cause by resourcenotfoundexception with your above error. issue may be with a icon file/resource file in drawers. if it coming from menu/drawer try changing icons and add icons to drawer folder and to drawer-v21. hope this helps |
35,423,581 | How can we copy all the contents of all the files in a given directory into a file **so that there are two empty lines between contents of each files**?
Need not to mention, I am new to bash scripting, and I know this is not an extra complicated code!
Any help will be greatly appreciated.
Related links are following:
\* [How do I compare the contents of all the files in a directory against another directory?](https://stackoverflow.com/questions/28555826/how-do-i-compare-the-contents-of-all-the-files-in-a-directory-against-another-di)
\* [Append contents of one file into another](https://stackoverflow.com/questions/10382330/append-contents-of-one-file-into-another)
\* [BASH: Copy all files and directories into another directory in the same parent directory](https://stackoverflow.com/questions/20832544/bash-copy-all-files-and-directories-into-another-directory-in-the-same-parent-d)
After reading comments, my initial attempt is this:
```
cat * > newfile.txt
```
**But this does not create two empty lines between contents of each new files.** | 2016/02/16 | [
"https://Stackoverflow.com/questions/35423581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5200329/"
] | Try this.
```
awk 'FNR==1 && NR>1 { printf("\n\n") }1' * >newfile.txt
```
The variable `FNR` is the line number within the current file and `NR` is the line number overall. | One way:
```
(
files=(*)
cat "${files[0]}"
for (( i = 1; i < "${#files[@]}" ; ++i )) ; do
echo
echo
cat "${files[i]}"
done
) > newfile.txt
``` |
35,423,581 | How can we copy all the contents of all the files in a given directory into a file **so that there are two empty lines between contents of each files**?
Need not to mention, I am new to bash scripting, and I know this is not an extra complicated code!
Any help will be greatly appreciated.
Related links are following:
\* [How do I compare the contents of all the files in a directory against another directory?](https://stackoverflow.com/questions/28555826/how-do-i-compare-the-contents-of-all-the-files-in-a-directory-against-another-di)
\* [Append contents of one file into another](https://stackoverflow.com/questions/10382330/append-contents-of-one-file-into-another)
\* [BASH: Copy all files and directories into another directory in the same parent directory](https://stackoverflow.com/questions/20832544/bash-copy-all-files-and-directories-into-another-directory-in-the-same-parent-d)
After reading comments, my initial attempt is this:
```
cat * > newfile.txt
```
**But this does not create two empty lines between contents of each new files.** | 2016/02/16 | [
"https://Stackoverflow.com/questions/35423581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5200329/"
] | Try this.
```
awk 'FNR==1 && NR>1 { printf("\n\n") }1' * >newfile.txt
```
The variable `FNR` is the line number within the current file and `NR` is the line number overall. | Example of file organization:
-----------------------------
I have a directory ~/Pictures/Temp
If I wanted to move PNG's from that directory to another directory I would first want to set a variable for my file names:
```
# This could be other file types as well
file=$(find ~/Pictures/Temp/*.png)
```
Of course there are many ways to view this check out:
```
$ man find
$ man ls
```
Then I would want to set a directory variable (especially if this directory is going to be something like a date
```
dir=$(some defining command here perhaps an awk of an ls -lt)
# Then we want to check for that directories existence and make it if
# it doesn't exist
[[ -e $dir ]] || mkdir "$dir"
# [[ -d $dir ]] will work here as well
```
You could write a for loop:
```
# t is time with the sleep this will be in seconds
# super useful with an every minute crontab
for ((t=1; t<59; t++));
do
# see above
file=$(blah blah)
# do nothing if there is no file to move
[[ -z $file ]] || mv "$file" "$dir/$file"
sleep 1
done
```
Please Google this if any of it seems unclear here are some useful links:
<https://www.gnu.org/software/gawk/manual/html_node/For-Statement.html>
<http://www.gnu.org/software/gawk/manual/gawk.html>
Best link on this page is below:
--------------------------------
<http://mywiki.wooledge.org/BashFAQ/031>
Edit:
-----
Anyhow where I was going with that whole answer is that you could easily write a script that will organize certain files on your system for 60 sec and write a crontab to automatically do your organizing for you:
```
crontab -e
```
Here is an example
```
$ crontab -l
* * * * * ~/Applications/Startup/Desktop-Cleanup.sh
# where ~/Applications/Startup/Desktop-Cleanup.sh is a custom application that I wrote
``` |
35,423,581 | How can we copy all the contents of all the files in a given directory into a file **so that there are two empty lines between contents of each files**?
Need not to mention, I am new to bash scripting, and I know this is not an extra complicated code!
Any help will be greatly appreciated.
Related links are following:
\* [How do I compare the contents of all the files in a directory against another directory?](https://stackoverflow.com/questions/28555826/how-do-i-compare-the-contents-of-all-the-files-in-a-directory-against-another-di)
\* [Append contents of one file into another](https://stackoverflow.com/questions/10382330/append-contents-of-one-file-into-another)
\* [BASH: Copy all files and directories into another directory in the same parent directory](https://stackoverflow.com/questions/20832544/bash-copy-all-files-and-directories-into-another-directory-in-the-same-parent-d)
After reading comments, my initial attempt is this:
```
cat * > newfile.txt
```
**But this does not create two empty lines between contents of each new files.** | 2016/02/16 | [
"https://Stackoverflow.com/questions/35423581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5200329/"
] | One way:
```
(
files=(*)
cat "${files[0]}"
for (( i = 1; i < "${#files[@]}" ; ++i )) ; do
echo
echo
cat "${files[i]}"
done
) > newfile.txt
``` | Example of file organization:
-----------------------------
I have a directory ~/Pictures/Temp
If I wanted to move PNG's from that directory to another directory I would first want to set a variable for my file names:
```
# This could be other file types as well
file=$(find ~/Pictures/Temp/*.png)
```
Of course there are many ways to view this check out:
```
$ man find
$ man ls
```
Then I would want to set a directory variable (especially if this directory is going to be something like a date
```
dir=$(some defining command here perhaps an awk of an ls -lt)
# Then we want to check for that directories existence and make it if
# it doesn't exist
[[ -e $dir ]] || mkdir "$dir"
# [[ -d $dir ]] will work here as well
```
You could write a for loop:
```
# t is time with the sleep this will be in seconds
# super useful with an every minute crontab
for ((t=1; t<59; t++));
do
# see above
file=$(blah blah)
# do nothing if there is no file to move
[[ -z $file ]] || mv "$file" "$dir/$file"
sleep 1
done
```
Please Google this if any of it seems unclear here are some useful links:
<https://www.gnu.org/software/gawk/manual/html_node/For-Statement.html>
<http://www.gnu.org/software/gawk/manual/gawk.html>
Best link on this page is below:
--------------------------------
<http://mywiki.wooledge.org/BashFAQ/031>
Edit:
-----
Anyhow where I was going with that whole answer is that you could easily write a script that will organize certain files on your system for 60 sec and write a crontab to automatically do your organizing for you:
```
crontab -e
```
Here is an example
```
$ crontab -l
* * * * * ~/Applications/Startup/Desktop-Cleanup.sh
# where ~/Applications/Startup/Desktop-Cleanup.sh is a custom application that I wrote
``` |
16,088,103 | I'm trying to print a label from an Android app to a Zebra printer (iMZ 320) but it seems not to be understanding my command line.
When I try this sample code, the printer prints all the commands to the paper as I send them to the printer:
```
zebraPrinterConnection.write("^XA^FO50,50^ADN,36,20^FDHELLO^FS^XZ".getBytes());
```
I've read the ZPL programming tutorial from Zebra's official website, but I can't figure out how to make my printer work all right with ZPL commands. | 2013/04/18 | [
"https://Stackoverflow.com/questions/16088103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2295894/"
] | The Zebra iMZ may ship in line print mode. This means that it will not parse and interpret the ZPL commands that you have provided, but rather, it will print them. You'll need to configure the printer to ZPL mode instead of line print mode. The following command should do it:
! U1 setvar "device.languages" "zpl"
**Note:** In some cases you may have to set the language to "hybrid\_xml\_zpl" instead of just "zpl"
Notice that you need to include a newline character (or carriage return) at the end of this command. You can use Zebra Setup Utilities to send commands directly to the printer through its 'communication' perspective, available by hitting the 'communication' button on the main screen.
Zebra Setup Utilities: <http://www.zebra.com/us/en/products-services/software/manage-software/zebra-setup-utility.html>
ZPL Manual page 705 (details command such as the one listed above): <https://support.zebra.com/cpws/docs/zpl/zpl_manual.pdf> | If you want to print simple text you can send normal "raw" data trough BT socket to Zebra printer and it will print it! You don't need to use Zebra print library.
Just run this code in async task to print two lines of plain text:
```
protected Object doInBackground(Object... params) {
//bt address
String bt_printer = "00:22:58:31:85:68";
String print_this = "Hello Zebra!\rThis is second line";
//vars
BluetoothSocket socket = null;
BufferedReader in = null;
BufferedWriter out = null;
//device from address
BluetoothDevice hxm = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(bt_printer);
UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
//create & connect to BT socket
socket = hxm.createRfcommSocketToServiceRecord(applicationUUID);
socket.connect();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write(print_this);
out.flush();
//some waiting
Thread.sleep(3000);
//in - nothing, just wait to close connection
in.ready();
in.skip(0);
//close all
in.close();
socket.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
``` |
58,130,757 | I need to convert this function to work with IE10.
I thought to use Babel to convert the file from ES6 to ES5, but i dont know how to use correctly Babel, because Babel dont convert Promise.
The script ES6 is this:
....
```
function readTextFile(file) {
return new Promise(function (resolve, reject) {
let rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status === 0) {
allText = rawFile.responseText;
resolve(allText);
}
}
};
rawFile.send(null);
});
}
```
.....
Thanks so much for your help and your time. | 2019/09/27 | [
"https://Stackoverflow.com/questions/58130757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4597387/"
] | According to [this article](https://en.cppreference.com/w/cpp/language/static) arr5 is declared but not defined.
Add
```
int MyClass::arr5[5];
```
after declaration of `class MyClass`. Than you can get `obj.arr5[0]`
```
class MyClass {
public:
int arr4[5];
static int arr5[5];
};
int MyClass::arr5[5];
``` | arr1 scope is global and exists until the end of the program.
arr2 scope is local and it will be created and destroyed every time when a function will be called.
arr3 scope is local. Local static variables are created and initialized the first time they are used, not at program startup and will be destroyed when the program exists.
arr1 and arr2 are not the same in terms of scope and initialization time. arr1 scope is global arr3 local(function scope). arr1 will be initialized when the program starts arr3 when the function will be called.
arr4 is a MyClass member it will be created/destroyed every time when you create/destroy MyClass object. It can be accessed only through MyClass object. So arr4 and arr2 are not the same.
arr5 is a static class member. It is not accosted with MyClass object. You can use it without creating MyClass object. You can access it directly with the following way MyClass::arr5. |
20,722,015 | I want to send a request with fiddler and want to send it **every second** same request.Is there any way to make this with fiddler. | 2013/12/21 | [
"https://Stackoverflow.com/questions/20722015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3105966/"
] | I would use [JMeter](http://jmeter.apache.org/index.html) for these kind of tests, but to answer your question, here is sample script which I got from [here](http://www.bayden.com/fiddler/Dev/ScriptSamples.asp)
```
public static ToolsAction("Crawl Sequential URLs")
function doCrawl(){
var sBase: String;
var sInt: String;
sBase = FiddlerObject.prompt("Enter base URL with ## in place of the start integer", "http://www.example.com/img##.jpg");
sInt = FiddlerObject.prompt("Start At", "1");
var iFirst = int.Parse(sInt);
sInt = FiddlerObject.prompt("End At", "12");
var iLast = int.Parse(sInt);
for (var x=iFirst; x<=iLast; x++)
{
//Replace 's' with your HTTP Request. Note: \ is a special character in JScript
// If you want to represent a backslash in a string constant, double it like \\
var s = "GET " + sBase.Replace("##", x.ToString()) + " HTTP/1.0\r\n\r\n";
var b=false;
while(!b){
try{
FiddlerObject.utilIssueRequest(s);
b=true;
}
catch(e){
var iT = Environment.TickCount + 10000;
FiddlerObject.StatusText = "Waiting 10 sec because we have too many requests outstanding...";
while (iT > Environment.TickCount){ Application.DoEvents(); }
}
}
}
}
``` | I believe you can do it, as you can write scripts in fiddler.
Anyway, I recommend you to use BURP for this purpose - you have built-in option to do it easily (repeater, for example).
See <http://portswigger.net/burp/>
and <http://portswigger.net/burp/repeater.html> (for repeater). |
20,722,015 | I want to send a request with fiddler and want to send it **every second** same request.Is there any way to make this with fiddler. | 2013/12/21 | [
"https://Stackoverflow.com/questions/20722015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3105966/"
] | I would use [curl](http://curl.haxx.se/) with a batch file to do just that
From Fiddler, select one or more requests you want to repeat and head over to *File > Export Sessions > Selected Sessions*
[](https://i.stack.imgur.com/NAxfk.png)
Now select Curl Export and save the output as a .bat file
[](https://i.stack.imgur.com/j3zs0.png)
Now edit the batch file to make it run every 60 seconds
```
:loop
<your curl commands exported from Fiddler>
timeout /t 60
goto loop
```
Now save the batch file and run it! | I believe you can do it, as you can write scripts in fiddler.
Anyway, I recommend you to use BURP for this purpose - you have built-in option to do it easily (repeater, for example).
See <http://portswigger.net/burp/>
and <http://portswigger.net/burp/repeater.html> (for repeater). |
36,064,921 | The past few days I’ve been experimenting with time pickers in Xamarin.Android. I've followed these two links:
[How to update text-view with multiple datepickers](https://stackoverflow.com/questions/20738960/how-to-update-text-view-with-multiple-datepickers?lq=1)
<http://blog.falafel.com/31-days-of-xamarin-android-day-15-controls-datetime-controls/>
But I’m now a little stuck.
I’ve two time pickers in the same activity. I want to choose a start time and an end time. But when I set the time of one of the time picker in the activity it automatically updates the other one.
What I want is set one time picker without updating the other one.
Below is what I’ve tried:
**ReservationHoursActivity.cs**
```
public class ReservationHoursActivity : Activity, TimePickerDialog.IOnTimeSetListener
{
private TextView time_display_Start;
private Button pick_button_Start;
private TextView time_display_End;
private Button pick_button_End, submitButtonMyslot;
private int hour;
private int minute;
const int START_TIME_DIALOG_ID = 0;
const int END_TIME_DIALOG_ID = 1;
const int TIME_PICKER_TO = 0;
const int TIME_PICKER_FROM = 1;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.ReservationHoursLayout);
time_display_Start = FindViewById<TextView> (Resource.Id.timeDisplayStart);
pick_button_Start = FindViewById<Button> (Resource.Id.btnPickTimeStart);
time_display_End = FindViewById<TextView> (Resource.Id.timeDisplayEnd);
pick_button_End = FindViewById<Button> (Resource.Id.btnPickTimeEnd);
submitButtonMyslot = FindViewById<Button> (Resource.Id.btnSubmitSlot);
submitButtonMyslot.Click += SubmitButtonMyslot_Click;
pick_button_Start.Click += delegate {
ShowTimePickerDialog (START_TIME_DIALOG_ID);
};
pick_button_End.Click += delegate {
ShowTimePickerDialog (END_TIME_DIALOG_ID);
};
hour = DateTime.Now.Hour;
minute = DateTime.Now.Minute;
UpdateDisplayStart (hour, minute);
UpdateDisplayEnd (hour, minute);
}
void ShowTimePickerDialog (int pickerID)
{
switch (pickerID) {
case TIME_PICKER_FROM:
var dialogStart = new TimePickerFragment (this, hour, minute, this);
dialogStart.Show (FragmentManager, null);
break;
case TIME_PICKER_TO:
var dialogEnd = new TimePickerFragment (this, hour, minute, this);
dialogEnd.Show (FragmentManager, null);
break;
}
}
public void OnTimeSet (TimePicker view, int hourOfDay, int minute)
{
UpdateDisplayEnd (hourOfDay, minute);
UpdateDisplayStart (hourOfDay, minute);
}
void UpdateDisplayStart (int selectedHours, int selectedMinutes)
{
time_display_Start.Text = selectedHours + ":" + selectedMinutes;
}
void UpdateDisplayEnd (int selectedHours, int selectedMinutes)
{
time_display_End.Text = selectedHours + ":" + selectedMinutes;
}
}
```
**TimePickerFragment.cs**
```
public class TimePickerFragment:DialogFragment
{
private readonly Context context;
private int hour;
private int minute;
private readonly TimePickerDialog.IOnTimeSetListener listener;
public TimePickerFragment (Context context, int hour, int minute, TimePickerDialog.IOnTimeSetListener listener)
{
this.context = context;
this.hour = hour;
this.minute = minute;
this.listener = listener;
}
public override Dialog OnCreateDialog (Bundle savedState)
{
var dialog = new TimePickerDialog (context, listener, hour, minute, false);
return dialog;
}
}
```
I don’t know how I can update the two time pickers separately.
I’ve also tried to put the OnTimeSet method inside this:
```
private TimePickerDialog.IOnTimeSetListener From_Time_Listener = new TimePickerDialog.IOnTimeSetListener()
{
public void OnTimeSet (TimePicker view, int hourOfDay, int minute)
{
UpdateDisplayEnd (hourOfDay, minute);
}
};
```
But that doesn’t work. It is not allowing me to put that method inside. Besides, other variables and methods will be unexpected if I do that. | 2016/03/17 | [
"https://Stackoverflow.com/questions/36064921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5655661/"
] | `var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));` takes each element from list - `x` and checks if it fits specific condition.
The condition is `x == s` OR `!string.IsNullOrEmpty(x)`, so element should fit at least one part of the condition.
Particularly, every element of list meets the `!string.IsNullOrEmpty(x)` condition.
Try to add `null` to your list. It doesn't meet the `!string.IsNullOrEmpty(x)` and doesn't meet `x == s`, so it won't be included in result.
```
var list = new List<string>
{
"One",
"Two",
"Three",
null
};
var numbers = list.Where(x => x == "One" || !string.IsNullOrEmpty(x)).ToList();
``` | The operator is correct . In your first example:
```
string s = "One";
var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));
foreach(var number in numbers)
{
Console.WriteLine(number);
// output:
// One <-- First condition is met
// Two <-- First condition is not met so goes into the OR operator and returns true
// Three <--Same as above
}
```
<https://msdn.microsoft.com/en-us/library/6373h346.aspx> |
36,064,921 | The past few days I’ve been experimenting with time pickers in Xamarin.Android. I've followed these two links:
[How to update text-view with multiple datepickers](https://stackoverflow.com/questions/20738960/how-to-update-text-view-with-multiple-datepickers?lq=1)
<http://blog.falafel.com/31-days-of-xamarin-android-day-15-controls-datetime-controls/>
But I’m now a little stuck.
I’ve two time pickers in the same activity. I want to choose a start time and an end time. But when I set the time of one of the time picker in the activity it automatically updates the other one.
What I want is set one time picker without updating the other one.
Below is what I’ve tried:
**ReservationHoursActivity.cs**
```
public class ReservationHoursActivity : Activity, TimePickerDialog.IOnTimeSetListener
{
private TextView time_display_Start;
private Button pick_button_Start;
private TextView time_display_End;
private Button pick_button_End, submitButtonMyslot;
private int hour;
private int minute;
const int START_TIME_DIALOG_ID = 0;
const int END_TIME_DIALOG_ID = 1;
const int TIME_PICKER_TO = 0;
const int TIME_PICKER_FROM = 1;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.ReservationHoursLayout);
time_display_Start = FindViewById<TextView> (Resource.Id.timeDisplayStart);
pick_button_Start = FindViewById<Button> (Resource.Id.btnPickTimeStart);
time_display_End = FindViewById<TextView> (Resource.Id.timeDisplayEnd);
pick_button_End = FindViewById<Button> (Resource.Id.btnPickTimeEnd);
submitButtonMyslot = FindViewById<Button> (Resource.Id.btnSubmitSlot);
submitButtonMyslot.Click += SubmitButtonMyslot_Click;
pick_button_Start.Click += delegate {
ShowTimePickerDialog (START_TIME_DIALOG_ID);
};
pick_button_End.Click += delegate {
ShowTimePickerDialog (END_TIME_DIALOG_ID);
};
hour = DateTime.Now.Hour;
minute = DateTime.Now.Minute;
UpdateDisplayStart (hour, minute);
UpdateDisplayEnd (hour, minute);
}
void ShowTimePickerDialog (int pickerID)
{
switch (pickerID) {
case TIME_PICKER_FROM:
var dialogStart = new TimePickerFragment (this, hour, minute, this);
dialogStart.Show (FragmentManager, null);
break;
case TIME_PICKER_TO:
var dialogEnd = new TimePickerFragment (this, hour, minute, this);
dialogEnd.Show (FragmentManager, null);
break;
}
}
public void OnTimeSet (TimePicker view, int hourOfDay, int minute)
{
UpdateDisplayEnd (hourOfDay, minute);
UpdateDisplayStart (hourOfDay, minute);
}
void UpdateDisplayStart (int selectedHours, int selectedMinutes)
{
time_display_Start.Text = selectedHours + ":" + selectedMinutes;
}
void UpdateDisplayEnd (int selectedHours, int selectedMinutes)
{
time_display_End.Text = selectedHours + ":" + selectedMinutes;
}
}
```
**TimePickerFragment.cs**
```
public class TimePickerFragment:DialogFragment
{
private readonly Context context;
private int hour;
private int minute;
private readonly TimePickerDialog.IOnTimeSetListener listener;
public TimePickerFragment (Context context, int hour, int minute, TimePickerDialog.IOnTimeSetListener listener)
{
this.context = context;
this.hour = hour;
this.minute = minute;
this.listener = listener;
}
public override Dialog OnCreateDialog (Bundle savedState)
{
var dialog = new TimePickerDialog (context, listener, hour, minute, false);
return dialog;
}
}
```
I don’t know how I can update the two time pickers separately.
I’ve also tried to put the OnTimeSet method inside this:
```
private TimePickerDialog.IOnTimeSetListener From_Time_Listener = new TimePickerDialog.IOnTimeSetListener()
{
public void OnTimeSet (TimePicker view, int hourOfDay, int minute)
{
UpdateDisplayEnd (hourOfDay, minute);
}
};
```
But that doesn’t work. It is not allowing me to put that method inside. Besides, other variables and methods will be unexpected if I do that. | 2016/03/17 | [
"https://Stackoverflow.com/questions/36064921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5655661/"
] | You are right in saying that:
```
a || b
```
Will not evaluate `b` if `a` is `true`, but:
`Where` LINQ using Lambda expression checks **every** element in the Enumerable regardless of the previous result. Thus when you do:
```
string s = "One";
var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));
```
It checks every element in the query whenever the `Where` lambda expression is valid:
```
x == s || !string.IsNullOrEmpty(x)); //x = "One", x == s is true
x == s || !string.IsNullOrEmpty(x)); //x = "Two", !string.IsNullOrEmpty(x) is true
x == s || !string.IsNullOrEmpty(x)); //x = "Three", !string.IsNullOrEmpty(x) is true
```
Thus you got all the elements.
Consider using `TakeWhile` if you want to stop taking the query result as soon as a condition is no longer reached. | `var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));` takes each element from list - `x` and checks if it fits specific condition.
The condition is `x == s` OR `!string.IsNullOrEmpty(x)`, so element should fit at least one part of the condition.
Particularly, every element of list meets the `!string.IsNullOrEmpty(x)` condition.
Try to add `null` to your list. It doesn't meet the `!string.IsNullOrEmpty(x)` and doesn't meet `x == s`, so it won't be included in result.
```
var list = new List<string>
{
"One",
"Two",
"Three",
null
};
var numbers = list.Where(x => x == "One" || !string.IsNullOrEmpty(x)).ToList();
``` |
36,064,921 | The past few days I’ve been experimenting with time pickers in Xamarin.Android. I've followed these two links:
[How to update text-view with multiple datepickers](https://stackoverflow.com/questions/20738960/how-to-update-text-view-with-multiple-datepickers?lq=1)
<http://blog.falafel.com/31-days-of-xamarin-android-day-15-controls-datetime-controls/>
But I’m now a little stuck.
I’ve two time pickers in the same activity. I want to choose a start time and an end time. But when I set the time of one of the time picker in the activity it automatically updates the other one.
What I want is set one time picker without updating the other one.
Below is what I’ve tried:
**ReservationHoursActivity.cs**
```
public class ReservationHoursActivity : Activity, TimePickerDialog.IOnTimeSetListener
{
private TextView time_display_Start;
private Button pick_button_Start;
private TextView time_display_End;
private Button pick_button_End, submitButtonMyslot;
private int hour;
private int minute;
const int START_TIME_DIALOG_ID = 0;
const int END_TIME_DIALOG_ID = 1;
const int TIME_PICKER_TO = 0;
const int TIME_PICKER_FROM = 1;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.ReservationHoursLayout);
time_display_Start = FindViewById<TextView> (Resource.Id.timeDisplayStart);
pick_button_Start = FindViewById<Button> (Resource.Id.btnPickTimeStart);
time_display_End = FindViewById<TextView> (Resource.Id.timeDisplayEnd);
pick_button_End = FindViewById<Button> (Resource.Id.btnPickTimeEnd);
submitButtonMyslot = FindViewById<Button> (Resource.Id.btnSubmitSlot);
submitButtonMyslot.Click += SubmitButtonMyslot_Click;
pick_button_Start.Click += delegate {
ShowTimePickerDialog (START_TIME_DIALOG_ID);
};
pick_button_End.Click += delegate {
ShowTimePickerDialog (END_TIME_DIALOG_ID);
};
hour = DateTime.Now.Hour;
minute = DateTime.Now.Minute;
UpdateDisplayStart (hour, minute);
UpdateDisplayEnd (hour, minute);
}
void ShowTimePickerDialog (int pickerID)
{
switch (pickerID) {
case TIME_PICKER_FROM:
var dialogStart = new TimePickerFragment (this, hour, minute, this);
dialogStart.Show (FragmentManager, null);
break;
case TIME_PICKER_TO:
var dialogEnd = new TimePickerFragment (this, hour, minute, this);
dialogEnd.Show (FragmentManager, null);
break;
}
}
public void OnTimeSet (TimePicker view, int hourOfDay, int minute)
{
UpdateDisplayEnd (hourOfDay, minute);
UpdateDisplayStart (hourOfDay, minute);
}
void UpdateDisplayStart (int selectedHours, int selectedMinutes)
{
time_display_Start.Text = selectedHours + ":" + selectedMinutes;
}
void UpdateDisplayEnd (int selectedHours, int selectedMinutes)
{
time_display_End.Text = selectedHours + ":" + selectedMinutes;
}
}
```
**TimePickerFragment.cs**
```
public class TimePickerFragment:DialogFragment
{
private readonly Context context;
private int hour;
private int minute;
private readonly TimePickerDialog.IOnTimeSetListener listener;
public TimePickerFragment (Context context, int hour, int minute, TimePickerDialog.IOnTimeSetListener listener)
{
this.context = context;
this.hour = hour;
this.minute = minute;
this.listener = listener;
}
public override Dialog OnCreateDialog (Bundle savedState)
{
var dialog = new TimePickerDialog (context, listener, hour, minute, false);
return dialog;
}
}
```
I don’t know how I can update the two time pickers separately.
I’ve also tried to put the OnTimeSet method inside this:
```
private TimePickerDialog.IOnTimeSetListener From_Time_Listener = new TimePickerDialog.IOnTimeSetListener()
{
public void OnTimeSet (TimePicker view, int hourOfDay, int minute)
{
UpdateDisplayEnd (hourOfDay, minute);
}
};
```
But that doesn’t work. It is not allowing me to put that method inside. Besides, other variables and methods will be unexpected if I do that. | 2016/03/17 | [
"https://Stackoverflow.com/questions/36064921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5655661/"
] | You are right in saying that:
```
a || b
```
Will not evaluate `b` if `a` is `true`, but:
`Where` LINQ using Lambda expression checks **every** element in the Enumerable regardless of the previous result. Thus when you do:
```
string s = "One";
var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));
```
It checks every element in the query whenever the `Where` lambda expression is valid:
```
x == s || !string.IsNullOrEmpty(x)); //x = "One", x == s is true
x == s || !string.IsNullOrEmpty(x)); //x = "Two", !string.IsNullOrEmpty(x) is true
x == s || !string.IsNullOrEmpty(x)); //x = "Three", !string.IsNullOrEmpty(x) is true
```
Thus you got all the elements.
Consider using `TakeWhile` if you want to stop taking the query result as soon as a condition is no longer reached. | The operator is correct . In your first example:
```
string s = "One";
var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));
foreach(var number in numbers)
{
Console.WriteLine(number);
// output:
// One <-- First condition is met
// Two <-- First condition is not met so goes into the OR operator and returns true
// Three <--Same as above
}
```
<https://msdn.microsoft.com/en-us/library/6373h346.aspx> |
47,296,821 | I had a component in a ReactJS app I am working on that I sweeeearrr is not used anywhere. It even gave me the warning that "footer is defined but not used'. It isn't render anywhere and it never did anything, modify state... yet I'm getting an error message that says that the page cannot be rendered because the file is missing after I deleted it.
Is this simply a matter that I must be missing a connection somewhere? | 2017/11/14 | [
"https://Stackoverflow.com/questions/47296821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | A few troubleshooting tips. It's helpful if you include these details in your question so we know what you've already tried. Try one at a time and see if the error resolves:
1. Restart your server (webpack-dev?).
2. Clear browser cache or open an incognito window and load the page again.
3. String-search your project for the file name. | >
> yet I'm getting an error message that says that the page cannot be rendered because the file is missing after I deleted it.
>
>
>
An unused import / require statement is left in there.
Solution
========
Search for filename in the entire code base and remove usage.
More
====
Something like TypeScript would have caught this at compile time. |
47,296,821 | I had a component in a ReactJS app I am working on that I sweeeearrr is not used anywhere. It even gave me the warning that "footer is defined but not used'. It isn't render anywhere and it never did anything, modify state... yet I'm getting an error message that says that the page cannot be rendered because the file is missing after I deleted it.
Is this simply a matter that I must be missing a connection somewhere? | 2017/11/14 | [
"https://Stackoverflow.com/questions/47296821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | A few troubleshooting tips. It's helpful if you include these details in your question so we know what you've already tried. Try one at a time and see if the error resolves:
1. Restart your server (webpack-dev?).
2. Clear browser cache or open an incognito window and load the page again.
3. String-search your project for the file name. | A bit late but I faced this exact same problem. Here is what I did:
1. In VSCode, I opened command pallete and reloaded typescript
2. I restarted react server
And it worked for me. |
53,461,656 | I'm trying to solve my issue with .htaccess file. I found out that accessing my page with <http://www.example.com> redirects to <https://www.www.example.com>.
I have tried numerous .htaccess rules and can't figure it out.
I want to redirect http to https and non www to www.
My .htaccess file:
```
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteRule (.*) https://www.%1/$1 [R=301,L]
```
I tried separate rules or reversing order (first to https then add www) but I'm still getting double www. | 2018/11/24 | [
"https://Stackoverflow.com/questions/53461656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | It looks like it's a browser problem. I used Justin's rule and it works good in Safari but on Chrome it's getting double www.www still.
Anyways it isn't related to .htaccess as I though first and was scratching my head why it's not working. | Edited to work the way you asked.
Try this as your configuration in .htaccess:
```
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^(.*)$ https://www.%1%{REQUEST_URI} [R=301,L]
``` |
47,364 | So, like most home owners, I have gallons of partially used paint, both from my old place, and old ones from the previous owners here. I want to dispose of these both safely and efficiently (we have quite a few gallons so pricey solutions may not fly).
They're all latex paint. My municipality will take these if they're "dry". I checked, and I tossed the chunked solid ones, but what about the ones with liquid? How do I dry them? Can I just open the can? That seems like it will release a lot of VOCs, which I'd rather not. I saw some "drying agent" at Home Depot, is this a good match? Or something simple like kitty litter (we do not have a cat) would be more cost efficient? | 2014/08/11 | [
"https://diy.stackexchange.com/questions/47364",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2888/"
] | Latex paint is water soluble and non-toxic. You can dilute with water and pour it down the drain. Alternatively you can just throw it out in the trash. | I'd try the craigslist free section before I tried actually disposing of it. |
47,364 | So, like most home owners, I have gallons of partially used paint, both from my old place, and old ones from the previous owners here. I want to dispose of these both safely and efficiently (we have quite a few gallons so pricey solutions may not fly).
They're all latex paint. My municipality will take these if they're "dry". I checked, and I tossed the chunked solid ones, but what about the ones with liquid? How do I dry them? Can I just open the can? That seems like it will release a lot of VOCs, which I'd rather not. I saw some "drying agent" at Home Depot, is this a good match? Or something simple like kitty litter (we do not have a cat) would be more cost efficient? | 2014/08/11 | [
"https://diy.stackexchange.com/questions/47364",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2888/"
] | Latex paint is water soluble and non-toxic. You can dilute with water and pour it down the drain. Alternatively you can just throw it out in the trash. | Check out paintcare.org and see if that helps. |
47,364 | So, like most home owners, I have gallons of partially used paint, both from my old place, and old ones from the previous owners here. I want to dispose of these both safely and efficiently (we have quite a few gallons so pricey solutions may not fly).
They're all latex paint. My municipality will take these if they're "dry". I checked, and I tossed the chunked solid ones, but what about the ones with liquid? How do I dry them? Can I just open the can? That seems like it will release a lot of VOCs, which I'd rather not. I saw some "drying agent" at Home Depot, is this a good match? Or something simple like kitty litter (we do not have a cat) would be more cost efficient? | 2014/08/11 | [
"https://diy.stackexchange.com/questions/47364",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2888/"
] | The municipalities just don't want it liquid or with the lid on. Imagine a paint can full of paint when the compactor squishes down on it. Paint everywhere! You can put whatever you want in the paint to make it more solid. Kitty litter, the store bought stuff drying agent, sand. I have used some old mortar that I had on hand. You just want to make sure that it's a solid or semi solid, and you can put it out on the curb for pickup without worry of it spilling with no lid. It would take too long for it to air dry. Also, a film might form on the top, preventing the bottom from drying. | Check out paintcare.org and see if that helps. |
47,364 | So, like most home owners, I have gallons of partially used paint, both from my old place, and old ones from the previous owners here. I want to dispose of these both safely and efficiently (we have quite a few gallons so pricey solutions may not fly).
They're all latex paint. My municipality will take these if they're "dry". I checked, and I tossed the chunked solid ones, but what about the ones with liquid? How do I dry them? Can I just open the can? That seems like it will release a lot of VOCs, which I'd rather not. I saw some "drying agent" at Home Depot, is this a good match? Or something simple like kitty litter (we do not have a cat) would be more cost efficient? | 2014/08/11 | [
"https://diy.stackexchange.com/questions/47364",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2888/"
] | Look to see if your municipality has a home hazardous waste disposal. I have in a large metro area and they have multiple locations and open Tue-Sat. I've been in another where they were only open once a month. But it is a good location to dispose of batteries, paint, meds and other chemicals I don't need around the home. | I picked up a leaflet on paint re-use at the local B&Q (UK DIY store) the other day. If you can't give it to a community re-use scheme they say stir in sawdust/wood shavings/a proprietary paint-setting product (similar to cat litter). The set (emulsion/latex) paint can then be disposed of as normal waste and if you empty the tin in the process that may be recycled. The older alternative is to paint/spread/pour it onto scrap board or newspaper. Even a very thick coat will eventually set and you can use the same board many times. This is a good option for small quantities but a pain if you want to get rid of lots in one go. |
47,364 | So, like most home owners, I have gallons of partially used paint, both from my old place, and old ones from the previous owners here. I want to dispose of these both safely and efficiently (we have quite a few gallons so pricey solutions may not fly).
They're all latex paint. My municipality will take these if they're "dry". I checked, and I tossed the chunked solid ones, but what about the ones with liquid? How do I dry them? Can I just open the can? That seems like it will release a lot of VOCs, which I'd rather not. I saw some "drying agent" at Home Depot, is this a good match? Or something simple like kitty litter (we do not have a cat) would be more cost efficient? | 2014/08/11 | [
"https://diy.stackexchange.com/questions/47364",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2888/"
] | What I have done on several occasions is to pour unwanted latex paint out on a sheet of plastic in the sun. spread it out so there are no deep puddles. After it dries, simply fold up the plastic and dispose as any other solid waste. After the can is dry, it also can go into recycling or the trash. | I'd try the craigslist free section before I tried actually disposing of it. |
47,364 | So, like most home owners, I have gallons of partially used paint, both from my old place, and old ones from the previous owners here. I want to dispose of these both safely and efficiently (we have quite a few gallons so pricey solutions may not fly).
They're all latex paint. My municipality will take these if they're "dry". I checked, and I tossed the chunked solid ones, but what about the ones with liquid? How do I dry them? Can I just open the can? That seems like it will release a lot of VOCs, which I'd rather not. I saw some "drying agent" at Home Depot, is this a good match? Or something simple like kitty litter (we do not have a cat) would be more cost efficient? | 2014/08/11 | [
"https://diy.stackexchange.com/questions/47364",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2888/"
] | Look to see if your municipality has a home hazardous waste disposal. I have in a large metro area and they have multiple locations and open Tue-Sat. I've been in another where they were only open once a month. But it is a good location to dispose of batteries, paint, meds and other chemicals I don't need around the home. | Open the lid and let it dry out. Place it out of the way somewhere where rainwater will not cause it to overflow. Throw it out in a few weeks when it is mostly dried up. Do not worry about VOCs, this is an acceptable method of disposal. |
47,364 | So, like most home owners, I have gallons of partially used paint, both from my old place, and old ones from the previous owners here. I want to dispose of these both safely and efficiently (we have quite a few gallons so pricey solutions may not fly).
They're all latex paint. My municipality will take these if they're "dry". I checked, and I tossed the chunked solid ones, but what about the ones with liquid? How do I dry them? Can I just open the can? That seems like it will release a lot of VOCs, which I'd rather not. I saw some "drying agent" at Home Depot, is this a good match? Or something simple like kitty litter (we do not have a cat) would be more cost efficient? | 2014/08/11 | [
"https://diy.stackexchange.com/questions/47364",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2888/"
] | I picked up a leaflet on paint re-use at the local B&Q (UK DIY store) the other day. If you can't give it to a community re-use scheme they say stir in sawdust/wood shavings/a proprietary paint-setting product (similar to cat litter). The set (emulsion/latex) paint can then be disposed of as normal waste and if you empty the tin in the process that may be recycled. The older alternative is to paint/spread/pour it onto scrap board or newspaper. Even a very thick coat will eventually set and you can use the same board many times. This is a good option for small quantities but a pain if you want to get rid of lots in one go. | I'd try the craigslist free section before I tried actually disposing of it. |
47,364 | So, like most home owners, I have gallons of partially used paint, both from my old place, and old ones from the previous owners here. I want to dispose of these both safely and efficiently (we have quite a few gallons so pricey solutions may not fly).
They're all latex paint. My municipality will take these if they're "dry". I checked, and I tossed the chunked solid ones, but what about the ones with liquid? How do I dry them? Can I just open the can? That seems like it will release a lot of VOCs, which I'd rather not. I saw some "drying agent" at Home Depot, is this a good match? Or something simple like kitty litter (we do not have a cat) would be more cost efficient? | 2014/08/11 | [
"https://diy.stackexchange.com/questions/47364",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2888/"
] | Open the lid and let it dry out. Place it out of the way somewhere where rainwater will not cause it to overflow. Throw it out in a few weeks when it is mostly dried up. Do not worry about VOCs, this is an acceptable method of disposal. | Check out paintcare.org and see if that helps. |
47,364 | So, like most home owners, I have gallons of partially used paint, both from my old place, and old ones from the previous owners here. I want to dispose of these both safely and efficiently (we have quite a few gallons so pricey solutions may not fly).
They're all latex paint. My municipality will take these if they're "dry". I checked, and I tossed the chunked solid ones, but what about the ones with liquid? How do I dry them? Can I just open the can? That seems like it will release a lot of VOCs, which I'd rather not. I saw some "drying agent" at Home Depot, is this a good match? Or something simple like kitty litter (we do not have a cat) would be more cost efficient? | 2014/08/11 | [
"https://diy.stackexchange.com/questions/47364",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2888/"
] | I picked up a leaflet on paint re-use at the local B&Q (UK DIY store) the other day. If you can't give it to a community re-use scheme they say stir in sawdust/wood shavings/a proprietary paint-setting product (similar to cat litter). The set (emulsion/latex) paint can then be disposed of as normal waste and if you empty the tin in the process that may be recycled. The older alternative is to paint/spread/pour it onto scrap board or newspaper. Even a very thick coat will eventually set and you can use the same board many times. This is a good option for small quantities but a pain if you want to get rid of lots in one go. | Check out paintcare.org and see if that helps. |
47,364 | So, like most home owners, I have gallons of partially used paint, both from my old place, and old ones from the previous owners here. I want to dispose of these both safely and efficiently (we have quite a few gallons so pricey solutions may not fly).
They're all latex paint. My municipality will take these if they're "dry". I checked, and I tossed the chunked solid ones, but what about the ones with liquid? How do I dry them? Can I just open the can? That seems like it will release a lot of VOCs, which I'd rather not. I saw some "drying agent" at Home Depot, is this a good match? Or something simple like kitty litter (we do not have a cat) would be more cost efficient? | 2014/08/11 | [
"https://diy.stackexchange.com/questions/47364",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2888/"
] | The municipalities just don't want it liquid or with the lid on. Imagine a paint can full of paint when the compactor squishes down on it. Paint everywhere! You can put whatever you want in the paint to make it more solid. Kitty litter, the store bought stuff drying agent, sand. I have used some old mortar that I had on hand. You just want to make sure that it's a solid or semi solid, and you can put it out on the curb for pickup without worry of it spilling with no lid. It would take too long for it to air dry. Also, a film might form on the top, preventing the bottom from drying. | I picked up a leaflet on paint re-use at the local B&Q (UK DIY store) the other day. If you can't give it to a community re-use scheme they say stir in sawdust/wood shavings/a proprietary paint-setting product (similar to cat litter). The set (emulsion/latex) paint can then be disposed of as normal waste and if you empty the tin in the process that may be recycled. The older alternative is to paint/spread/pour it onto scrap board or newspaper. Even a very thick coat will eventually set and you can use the same board many times. This is a good option for small quantities but a pain if you want to get rid of lots in one go. |
4,107,957 | I know that a quadratic equation can be represented in the form
$$ax^2 + bx + c = 0$$ where $a$ is not equal to $0$, and $a$, $b$, and $c$ are real numbers. However, if there is an equation in the form
$$ax^2 + bx = 0$$
would it be classified as a quadratic equation since the conditions are satisfied, or would it be a linear equation since it can be simplified into $ax + b = 0$? | 2021/04/19 | [
"https://math.stackexchange.com/questions/4107957",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/483546/"
] | A quadratic equation is an equation that can be rearranged as $ax^2+bx+c=0$ where $a$ is not equal to $0$ and $b$ and $c$ are real numbers. If $a=0$ then the equation is linear not quadratic since the $x^2$ has no influence . | You need only $a≠0$ for $$ax^2+bx+c=0.$$
If the degree of your polynomial is equal to $2$, then you have a quadratic polynomial. This means , your equation $ax^2+bx=0$ is still a quadratic equation, if $a≠0.$
But, the degree of the polynomial $ax+b$ is equal to $1$. This implies, $ax+b=0$ is not a quadratic.
---
**Small Supplement:**
$ax^2+bx=0$ is not equivalent to $ax+b=0$. Because, $x=0$ is not always a root of $ax+b=0.$ |
4,107,957 | I know that a quadratic equation can be represented in the form
$$ax^2 + bx + c = 0$$ where $a$ is not equal to $0$, and $a$, $b$, and $c$ are real numbers. However, if there is an equation in the form
$$ax^2 + bx = 0$$
would it be classified as a quadratic equation since the conditions are satisfied, or would it be a linear equation since it can be simplified into $ax + b = 0$? | 2021/04/19 | [
"https://math.stackexchange.com/questions/4107957",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/483546/"
] | Hints
1. If you draw the graph of $y=ax^2+bx$ what shape is it? (Plug in some non-zero values for $a$ and $b$)
2. If you factorize $ax^2+bx=0$ and then apply null factor law, how many solutions are there? | You need only $a≠0$ for $$ax^2+bx+c=0.$$
If the degree of your polynomial is equal to $2$, then you have a quadratic polynomial. This means , your equation $ax^2+bx=0$ is still a quadratic equation, if $a≠0.$
But, the degree of the polynomial $ax+b$ is equal to $1$. This implies, $ax+b=0$ is not a quadratic.
---
**Small Supplement:**
$ax^2+bx=0$ is not equivalent to $ax+b=0$. Because, $x=0$ is not always a root of $ax+b=0.$ |
4,107,957 | I know that a quadratic equation can be represented in the form
$$ax^2 + bx + c = 0$$ where $a$ is not equal to $0$, and $a$, $b$, and $c$ are real numbers. However, if there is an equation in the form
$$ax^2 + bx = 0$$
would it be classified as a quadratic equation since the conditions are satisfied, or would it be a linear equation since it can be simplified into $ax + b = 0$? | 2021/04/19 | [
"https://math.stackexchange.com/questions/4107957",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/483546/"
] | It is a quadratic equation as it satisfies the definition.
Notice that $ax^2+bx=0$ and $ax+b=0$ are not equivalent, the first one has $0$ as a solution for sure and $\frac{-b}a$ as a root as well. | You need only $a≠0$ for $$ax^2+bx+c=0.$$
If the degree of your polynomial is equal to $2$, then you have a quadratic polynomial. This means , your equation $ax^2+bx=0$ is still a quadratic equation, if $a≠0.$
But, the degree of the polynomial $ax+b$ is equal to $1$. This implies, $ax+b=0$ is not a quadratic.
---
**Small Supplement:**
$ax^2+bx=0$ is not equivalent to $ax+b=0$. Because, $x=0$ is not always a root of $ax+b=0.$ |
4,107,957 | I know that a quadratic equation can be represented in the form
$$ax^2 + bx + c = 0$$ where $a$ is not equal to $0$, and $a$, $b$, and $c$ are real numbers. However, if there is an equation in the form
$$ax^2 + bx = 0$$
would it be classified as a quadratic equation since the conditions are satisfied, or would it be a linear equation since it can be simplified into $ax + b = 0$? | 2021/04/19 | [
"https://math.stackexchange.com/questions/4107957",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/483546/"
] | It is a quadratic equation as it satisfies the definition.
Notice that $ax^2+bx=0$ and $ax+b=0$ are not equivalent, the first one has $0$ as a solution for sure and $\frac{-b}a$ as a root as well. | A quadratic equation is an equation that can be rearranged as $ax^2+bx+c=0$ where $a$ is not equal to $0$ and $b$ and $c$ are real numbers. If $a=0$ then the equation is linear not quadratic since the $x^2$ has no influence . |
4,107,957 | I know that a quadratic equation can be represented in the form
$$ax^2 + bx + c = 0$$ where $a$ is not equal to $0$, and $a$, $b$, and $c$ are real numbers. However, if there is an equation in the form
$$ax^2 + bx = 0$$
would it be classified as a quadratic equation since the conditions are satisfied, or would it be a linear equation since it can be simplified into $ax + b = 0$? | 2021/04/19 | [
"https://math.stackexchange.com/questions/4107957",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/483546/"
] | It is a quadratic equation as it satisfies the definition.
Notice that $ax^2+bx=0$ and $ax+b=0$ are not equivalent, the first one has $0$ as a solution for sure and $\frac{-b}a$ as a root as well. | Hints
1. If you draw the graph of $y=ax^2+bx$ what shape is it? (Plug in some non-zero values for $a$ and $b$)
2. If you factorize $ax^2+bx=0$ and then apply null factor law, how many solutions are there? |
297,431 | When I create a new instance of a ChannelFactory:
```
var factory = new ChannelFactory<IMyService>();
```
and that I create a new channel, I have an exception saying that the address of the Endpoint is null.
My configuration inside my web.config is as mentioned and everything is as it is supposed to be (especially the address of the endpoint).
If I create a new MyServiceClientBase, it loads all the configuration from my channel factory:
```
var factoryWithClientBase = new MyServiceClientBase().ChannelFactory;
Console.WriteLine(factoryWithClientBase.Endpoint.Address); //output the configuration inside the web.config
var factoryWithChannelFactory = new ChannelFactory<IMyService>();
Console.WriteLine(factoryWithChannelFactory.Endpoint.Address); //output nothing (null)
```
Why? | 2008/11/18 | [
"https://Stackoverflow.com/questions/297431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24975/"
] | I finally found the answer. ChannelFactory doesn't read information from your Web.Config/app.config. ClientBase (which then work with a ChannelFactory) does.
All this costed me a few hours of work but I finally found a valid reason.
:) | Will it work if you provide the endpoint with a name like this in Web.Config:
```
<endpoint address="http://localhost:2000/MyService/" binding="wsHttpBinding"
behaviorConfiguration="wsHttpBehaviour" contract="IService"
name="MyWsHttpEndpoint" />
```
And create the channel using ChannelFactory like this:
```
var factory = new ChannelFactory<IMyService>("MyWsHttpEndpoint");
``` |
297,431 | When I create a new instance of a ChannelFactory:
```
var factory = new ChannelFactory<IMyService>();
```
and that I create a new channel, I have an exception saying that the address of the Endpoint is null.
My configuration inside my web.config is as mentioned and everything is as it is supposed to be (especially the address of the endpoint).
If I create a new MyServiceClientBase, it loads all the configuration from my channel factory:
```
var factoryWithClientBase = new MyServiceClientBase().ChannelFactory;
Console.WriteLine(factoryWithClientBase.Endpoint.Address); //output the configuration inside the web.config
var factoryWithChannelFactory = new ChannelFactory<IMyService>();
Console.WriteLine(factoryWithChannelFactory.Endpoint.Address); //output nothing (null)
```
Why? | 2008/11/18 | [
"https://Stackoverflow.com/questions/297431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24975/"
] | Will it work if you provide the endpoint with a name like this in Web.Config:
```
<endpoint address="http://localhost:2000/MyService/" binding="wsHttpBinding"
behaviorConfiguration="wsHttpBehaviour" contract="IService"
name="MyWsHttpEndpoint" />
```
And create the channel using ChannelFactory like this:
```
var factory = new ChannelFactory<IMyService>("MyWsHttpEndpoint");
``` | ChannelFactory instantiated by the new operator DOES read from web.config. AnAngel answer above is correct.
You just have to make sure that you provide your endpoint with a name.
And make sure that the endpoint contract is set correctly (very important)
I have an experience before where my web.config was generated by VS and the endpoint contract is set to the contract in the ServiceReference (as a result of adding Service Reference) which is not the one I wanted. Although it has similar name to my original contract (but reside in different namespaces)
```
<endpoint address="http://localhost:2000/MyService/" binding="wsHttpBinding"
behaviorConfiguration="wsHttpBehaviour" contract="TheCorrectNamespace.IService"
name="MyWsHttpEndpoint" />
```
The asker didn't post his web.config so I am assuming that you most likely made the mistake I did (specifying the wrong contract for endpoints) |
297,431 | When I create a new instance of a ChannelFactory:
```
var factory = new ChannelFactory<IMyService>();
```
and that I create a new channel, I have an exception saying that the address of the Endpoint is null.
My configuration inside my web.config is as mentioned and everything is as it is supposed to be (especially the address of the endpoint).
If I create a new MyServiceClientBase, it loads all the configuration from my channel factory:
```
var factoryWithClientBase = new MyServiceClientBase().ChannelFactory;
Console.WriteLine(factoryWithClientBase.Endpoint.Address); //output the configuration inside the web.config
var factoryWithChannelFactory = new ChannelFactory<IMyService>();
Console.WriteLine(factoryWithChannelFactory.Endpoint.Address); //output nothing (null)
```
Why? | 2008/11/18 | [
"https://Stackoverflow.com/questions/297431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24975/"
] | I finally found the answer. ChannelFactory doesn't read information from your Web.Config/app.config. ClientBase (which then work with a ChannelFactory) does.
All this costed me a few hours of work but I finally found a valid reason.
:) | ChannelFactory instantiated by the new operator DOES read from web.config. AnAngel answer above is correct.
You just have to make sure that you provide your endpoint with a name.
And make sure that the endpoint contract is set correctly (very important)
I have an experience before where my web.config was generated by VS and the endpoint contract is set to the contract in the ServiceReference (as a result of adding Service Reference) which is not the one I wanted. Although it has similar name to my original contract (but reside in different namespaces)
```
<endpoint address="http://localhost:2000/MyService/" binding="wsHttpBinding"
behaviorConfiguration="wsHttpBehaviour" contract="TheCorrectNamespace.IService"
name="MyWsHttpEndpoint" />
```
The asker didn't post his web.config so I am assuming that you most likely made the mistake I did (specifying the wrong contract for endpoints) |
11,873,160 | I am developing an application that needs to interract with a "lightly documented" Legacy Oracle Database. To Start that process I want to start creating a view into that Database using ODBC links into an MS Access database so I can figure out the DB structure but I can't figure out how to setup the ODBC connection to the Oracle DB.
I have been able to connect using the Host and Service Name to and view the DB using SQL Developer; but, I can't figure out how to setup ODBC. I am running Windows 7 and have installed Oracle 11g, Oracle Express Edition, the Instant Client and ODBC extensitons; but on the ODBC setup Oracle wants me to pick a TNS Service Name but there is none to pick and there is no place to specify the host. I tried to setup a TNS in tnsnames.ora; but I am not really sure I know the right location for that file.
I really thought this would be the easy part; but, it really hasn't been. | 2012/08/08 | [
"https://Stackoverflow.com/questions/11873160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1487159/"
] | Navigate to the **Control Panel** > **Administrative Tools** > **Data Sources (ODBC)**
Select the **System DSN** tab and click 'Add'. Next scroll down the lists of drivers until you find **Microsoft ODBC for Oracle**.

Fill in the required information in the above form and click 'OK'. Now you can add the tables to 'Access' by clicking on the 'External Data' tab then clicking on 'More'. Choose 'ODBC Databases', then 'Import the source data...', next click on the 'Machine Data Source' tab. | The simplest option to generate the tnsnames.ora file is to let Oracle do it. If you launch the Oracle Net Configuration Assistant (Start | Oracle in *Oracle Home Name* | Configuration and Migration Tools | Net Configuration Assistant), you should be able to choose "Local Net Service Name configuration" which allows you to add (or modify) a TNS alias. That will walk you through gathering the information you'll need to connect.
If you are more comfortable dealing with the text files directly, you can directly edit the tnsnames.ora file in %Oracle Home%\network\ADMIN\tnsnames.ora using this as a template.
```
<TNS alias> =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = <hostname or IP>)(PORT = <port>))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = <database service name>)
)
)
``` |
11,873,160 | I am developing an application that needs to interract with a "lightly documented" Legacy Oracle Database. To Start that process I want to start creating a view into that Database using ODBC links into an MS Access database so I can figure out the DB structure but I can't figure out how to setup the ODBC connection to the Oracle DB.
I have been able to connect using the Host and Service Name to and view the DB using SQL Developer; but, I can't figure out how to setup ODBC. I am running Windows 7 and have installed Oracle 11g, Oracle Express Edition, the Instant Client and ODBC extensitons; but on the ODBC setup Oracle wants me to pick a TNS Service Name but there is none to pick and there is no place to specify the host. I tried to setup a TNS in tnsnames.ora; but I am not really sure I know the right location for that file.
I really thought this would be the easy part; but, it really hasn't been. | 2012/08/08 | [
"https://Stackoverflow.com/questions/11873160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1487159/"
] | Navigate to the **Control Panel** > **Administrative Tools** > **Data Sources (ODBC)**
Select the **System DSN** tab and click 'Add'. Next scroll down the lists of drivers until you find **Microsoft ODBC for Oracle**.

Fill in the required information in the above form and click 'OK'. Now you can add the tables to 'Access' by clicking on the 'External Data' tab then clicking on 'More'. Choose 'ODBC Databases', then 'Import the source data...', next click on the 'Machine Data Source' tab. | In tnsnames.ora, try changing SERVICE\_NAME to SID. That worked for me. |
11,873,160 | I am developing an application that needs to interract with a "lightly documented" Legacy Oracle Database. To Start that process I want to start creating a view into that Database using ODBC links into an MS Access database so I can figure out the DB structure but I can't figure out how to setup the ODBC connection to the Oracle DB.
I have been able to connect using the Host and Service Name to and view the DB using SQL Developer; but, I can't figure out how to setup ODBC. I am running Windows 7 and have installed Oracle 11g, Oracle Express Edition, the Instant Client and ODBC extensitons; but on the ODBC setup Oracle wants me to pick a TNS Service Name but there is none to pick and there is no place to specify the host. I tried to setup a TNS in tnsnames.ora; but I am not really sure I know the right location for that file.
I really thought this would be the easy part; but, it really hasn't been. | 2012/08/08 | [
"https://Stackoverflow.com/questions/11873160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1487159/"
] | Navigate to the **Control Panel** > **Administrative Tools** > **Data Sources (ODBC)**
Select the **System DSN** tab and click 'Add'. Next scroll down the lists of drivers until you find **Microsoft ODBC for Oracle**.

Fill in the required information in the above form and click 'OK'. Now you can add the tables to 'Access' by clicking on the 'External Data' tab then clicking on 'More'. Choose 'ODBC Databases', then 'Import the source data...', next click on the 'Machine Data Source' tab. | My Experience
1. TNSNAMES.ORA is as follows.
XE =
(DESCRIPTION =
(ADDRESS\_LIST =
(ADDRESS =
(PROTOCOL = TCP)
(HOST = 192.168.2.116)
(PORT = 1521)
)
)
(CONNECT\_DATA =
(SERVICE\_NAME = XE)
)
)
2. Set Windows Environment Variables (ControlPanel --> System --> Detail..)
2-1. Add to PATH
c:\oraclexe\instantclient\_11\_2\ --- install directory of instantclient
2-2. Add New Environment Variable
TNS\_ADMIN c:\oraclexe\instantclient\_11\_2\ --> install directory
NLS\_LANG = JAPANESE\_JAPAN.JA16SJISTILDE
3. Windows command prompt
cd c:\Windows\SysWow64 <--I use 32bit ODBC in 64bit Win7
odbcad32.exe
Name : ICODBC <-- as you like
Service Name : XE
User Name: system
Press Connection Test Button |
11,873,160 | I am developing an application that needs to interract with a "lightly documented" Legacy Oracle Database. To Start that process I want to start creating a view into that Database using ODBC links into an MS Access database so I can figure out the DB structure but I can't figure out how to setup the ODBC connection to the Oracle DB.
I have been able to connect using the Host and Service Name to and view the DB using SQL Developer; but, I can't figure out how to setup ODBC. I am running Windows 7 and have installed Oracle 11g, Oracle Express Edition, the Instant Client and ODBC extensitons; but on the ODBC setup Oracle wants me to pick a TNS Service Name but there is none to pick and there is no place to specify the host. I tried to setup a TNS in tnsnames.ora; but I am not really sure I know the right location for that file.
I really thought this would be the easy part; but, it really hasn't been. | 2012/08/08 | [
"https://Stackoverflow.com/questions/11873160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1487159/"
] | The simplest option to generate the tnsnames.ora file is to let Oracle do it. If you launch the Oracle Net Configuration Assistant (Start | Oracle in *Oracle Home Name* | Configuration and Migration Tools | Net Configuration Assistant), you should be able to choose "Local Net Service Name configuration" which allows you to add (or modify) a TNS alias. That will walk you through gathering the information you'll need to connect.
If you are more comfortable dealing with the text files directly, you can directly edit the tnsnames.ora file in %Oracle Home%\network\ADMIN\tnsnames.ora using this as a template.
```
<TNS alias> =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = <hostname or IP>)(PORT = <port>))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = <database service name>)
)
)
``` | In tnsnames.ora, try changing SERVICE\_NAME to SID. That worked for me. |
11,873,160 | I am developing an application that needs to interract with a "lightly documented" Legacy Oracle Database. To Start that process I want to start creating a view into that Database using ODBC links into an MS Access database so I can figure out the DB structure but I can't figure out how to setup the ODBC connection to the Oracle DB.
I have been able to connect using the Host and Service Name to and view the DB using SQL Developer; but, I can't figure out how to setup ODBC. I am running Windows 7 and have installed Oracle 11g, Oracle Express Edition, the Instant Client and ODBC extensitons; but on the ODBC setup Oracle wants me to pick a TNS Service Name but there is none to pick and there is no place to specify the host. I tried to setup a TNS in tnsnames.ora; but I am not really sure I know the right location for that file.
I really thought this would be the easy part; but, it really hasn't been. | 2012/08/08 | [
"https://Stackoverflow.com/questions/11873160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1487159/"
] | The simplest option to generate the tnsnames.ora file is to let Oracle do it. If you launch the Oracle Net Configuration Assistant (Start | Oracle in *Oracle Home Name* | Configuration and Migration Tools | Net Configuration Assistant), you should be able to choose "Local Net Service Name configuration" which allows you to add (or modify) a TNS alias. That will walk you through gathering the information you'll need to connect.
If you are more comfortable dealing with the text files directly, you can directly edit the tnsnames.ora file in %Oracle Home%\network\ADMIN\tnsnames.ora using this as a template.
```
<TNS alias> =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = <hostname or IP>)(PORT = <port>))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = <database service name>)
)
)
``` | My Experience
1. TNSNAMES.ORA is as follows.
XE =
(DESCRIPTION =
(ADDRESS\_LIST =
(ADDRESS =
(PROTOCOL = TCP)
(HOST = 192.168.2.116)
(PORT = 1521)
)
)
(CONNECT\_DATA =
(SERVICE\_NAME = XE)
)
)
2. Set Windows Environment Variables (ControlPanel --> System --> Detail..)
2-1. Add to PATH
c:\oraclexe\instantclient\_11\_2\ --- install directory of instantclient
2-2. Add New Environment Variable
TNS\_ADMIN c:\oraclexe\instantclient\_11\_2\ --> install directory
NLS\_LANG = JAPANESE\_JAPAN.JA16SJISTILDE
3. Windows command prompt
cd c:\Windows\SysWow64 <--I use 32bit ODBC in 64bit Win7
odbcad32.exe
Name : ICODBC <-- as you like
Service Name : XE
User Name: system
Press Connection Test Button |
73,833,899 | Currently in my SceneKit scene for a game in iOS using Swift the render distance is very limited, there is a noticeable cutoff in the terrain
[](https://i.stack.imgur.com/btFEi.jpg)
of the players perspective, i cant find a "max render distance" setting anywhere and the only option ive seen so far is to just cover it with fog, im clearly missing something as ive seen plenty of games with larger render distances but after searching across google, documentation and stack overflow i cant seem to get an answer, can anyone help?
[](https://i.stack.imgur.com/Ed9rO.png) | 2022/09/24 | [
"https://Stackoverflow.com/questions/73833899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15243101/"
] | Camera Far Clipping Plane
-------------------------
To adjust a max distance between the camera and a visible surface, use `zFar` instance property. If a 3D object's surface is farther from the camera than this distance, the surface is clipped and does not appear. The default value in SceneKit is 100.0 meters.
```
arscnView.pointOfView?.camera?.zFar = 500.0
``` | Im a dingdong and figured out what i was missing.
What i was looking for was a setting in the camera that your scene is using as the point of view, theres a setting called 'Z clipping" which clips out anything closer then the "near" value or further then the "far" value, and by default far is set to 100 units. just adjust that setting either in code or within XCODE and set it to a higher value to view the entire scene.
[](https://i.stack.imgur.com/MN0IG.png) |
24,782,717 | I'm using `hibernate 4.2.6` and `PostgreSQL 9.1`
I've been trying to execute sql query with hibernate. I've written:
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
createSQLQuery(sql);//has no effect. Query doesn't execute.
session.getTransaction().commit();
session.close();
```
This query does not executed in DB. But if I write
```
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
Properties connectionProps = new Properties();
connectionProps.put("user", "postgres");
connectionProps.put("password", "123");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/solid",connectionProps);
conn.createStatement().execute(sql);
```
corresponding row will add to table. Why hibernate doesn't work, but native query wth JDBC works? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24782717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] | This should help you.
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);",product.getName(), product.getCost());
session.createSQLQuery(sql).executeUpdate();
session.getTransaction().commit();
session.close();
``` | Its always better to use PreparedStatement *(You dont want to give way to SQL Injections)*.
```
String sql = "INSERT INTO products (name,cost) VALUES (?,?)";
Session sess = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
Connection con = sess.connection();
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, product.getName());
pstmt.setInt(2, product.getCost());
pstmt.executeUpdate();
con.commit();
pstmt.close();
``` |
24,782,717 | I'm using `hibernate 4.2.6` and `PostgreSQL 9.1`
I've been trying to execute sql query with hibernate. I've written:
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
createSQLQuery(sql);//has no effect. Query doesn't execute.
session.getTransaction().commit();
session.close();
```
This query does not executed in DB. But if I write
```
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
Properties connectionProps = new Properties();
connectionProps.put("user", "postgres");
connectionProps.put("password", "123");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/solid",connectionProps);
conn.createStatement().execute(sql);
```
corresponding row will add to table. Why hibernate doesn't work, but native query wth JDBC works? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24782717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] | This should help you.
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);",product.getName(), product.getCost());
session.createSQLQuery(sql).executeUpdate();
session.getTransaction().commit();
session.close();
``` | Another issue that might hit you (like it hit me) is this:
You want to run a native query, but can't get it to work in your production code? Pay attention if you are using a different database user for the application than the schema owner. In that case you may have to add the schema prefix to the referenced tables in order to make it work.
In my example I am using an entity manager instead of the session:
```
String sql = "select id from some_table";
Query query = em.createNativeQuery(sql);
List<Long> results = query.getResultList();
```
if some\_table is owned by e.g. dba while the application is running as user, you will need to modify the query to:
```
String sql = "select id from dba.some_table";
```
Having Hibernate set to prefix all tables with
```
<prop key="hibernate.default_schema">dba</prop>
```
does apparently NOT affect native queries. |
24,782,717 | I'm using `hibernate 4.2.6` and `PostgreSQL 9.1`
I've been trying to execute sql query with hibernate. I've written:
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
createSQLQuery(sql);//has no effect. Query doesn't execute.
session.getTransaction().commit();
session.close();
```
This query does not executed in DB. But if I write
```
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
Properties connectionProps = new Properties();
connectionProps.put("user", "postgres");
connectionProps.put("password", "123");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/solid",connectionProps);
conn.createStatement().execute(sql);
```
corresponding row will add to table. Why hibernate doesn't work, but native query wth JDBC works? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24782717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] | This should help you.
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);",product.getName(), product.getCost());
session.createSQLQuery(sql).executeUpdate();
session.getTransaction().commit();
session.close();
``` | The solution that work for me is the following:
```
public List<T> queryNativeExecute(String query) throws CustomException {
List<T> result =null;
Session session =null;
Transaction transaction=null;
try{
session = HibernateUtil.getSessionJavaConfigFactory().openSession();
transaction = session.beginTransaction();
session.createNativeQuery(query).executeUpdate();
transaction.commit();
}catch(Exception exception){
result=null;
if (transaction !=null && transaction.isActive()){
transaction.rollback();
}
throw new CustomException(exception.getMessage(),exception,error.ErrorCode.DATABASE_TABLE,this.getClass().getSimpleName());
}finally{
if (session !=null){
session.close();
}
}
return result;
}
``` |
24,782,717 | I'm using `hibernate 4.2.6` and `PostgreSQL 9.1`
I've been trying to execute sql query with hibernate. I've written:
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
createSQLQuery(sql);//has no effect. Query doesn't execute.
session.getTransaction().commit();
session.close();
```
This query does not executed in DB. But if I write
```
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
Properties connectionProps = new Properties();
connectionProps.put("user", "postgres");
connectionProps.put("password", "123");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/solid",connectionProps);
conn.createStatement().execute(sql);
```
corresponding row will add to table. Why hibernate doesn't work, but native query wth JDBC works? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24782717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] | This should help you.
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);",product.getName(), product.getCost());
session.createSQLQuery(sql).executeUpdate();
session.getTransaction().commit();
session.close();
``` | worked with me in spring-boot and hibernate 5.4.2 using the entity manager
```
@Autowired
EntityManager em;
public List<String> getDistinctColumnValues(String tableName, String columnName) {
List<String> result = em.createNativeQuery("select distinct (" + columnName + ") from " + tableName).getResultList();
return result;
}
``` |
24,782,717 | I'm using `hibernate 4.2.6` and `PostgreSQL 9.1`
I've been trying to execute sql query with hibernate. I've written:
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
createSQLQuery(sql);//has no effect. Query doesn't execute.
session.getTransaction().commit();
session.close();
```
This query does not executed in DB. But if I write
```
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
Properties connectionProps = new Properties();
connectionProps.put("user", "postgres");
connectionProps.put("password", "123");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/solid",connectionProps);
conn.createStatement().execute(sql);
```
corresponding row will add to table. Why hibernate doesn't work, but native query wth JDBC works? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24782717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] | Its always better to use PreparedStatement *(You dont want to give way to SQL Injections)*.
```
String sql = "INSERT INTO products (name,cost) VALUES (?,?)";
Session sess = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
Connection con = sess.connection();
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, product.getName());
pstmt.setInt(2, product.getCost());
pstmt.executeUpdate();
con.commit();
pstmt.close();
``` | Another issue that might hit you (like it hit me) is this:
You want to run a native query, but can't get it to work in your production code? Pay attention if you are using a different database user for the application than the schema owner. In that case you may have to add the schema prefix to the referenced tables in order to make it work.
In my example I am using an entity manager instead of the session:
```
String sql = "select id from some_table";
Query query = em.createNativeQuery(sql);
List<Long> results = query.getResultList();
```
if some\_table is owned by e.g. dba while the application is running as user, you will need to modify the query to:
```
String sql = "select id from dba.some_table";
```
Having Hibernate set to prefix all tables with
```
<prop key="hibernate.default_schema">dba</prop>
```
does apparently NOT affect native queries. |
24,782,717 | I'm using `hibernate 4.2.6` and `PostgreSQL 9.1`
I've been trying to execute sql query with hibernate. I've written:
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
createSQLQuery(sql);//has no effect. Query doesn't execute.
session.getTransaction().commit();
session.close();
```
This query does not executed in DB. But if I write
```
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
Properties connectionProps = new Properties();
connectionProps.put("user", "postgres");
connectionProps.put("password", "123");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/solid",connectionProps);
conn.createStatement().execute(sql);
```
corresponding row will add to table. Why hibernate doesn't work, but native query wth JDBC works? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24782717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] | Its always better to use PreparedStatement *(You dont want to give way to SQL Injections)*.
```
String sql = "INSERT INTO products (name,cost) VALUES (?,?)";
Session sess = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
Connection con = sess.connection();
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, product.getName());
pstmt.setInt(2, product.getCost());
pstmt.executeUpdate();
con.commit();
pstmt.close();
``` | The solution that work for me is the following:
```
public List<T> queryNativeExecute(String query) throws CustomException {
List<T> result =null;
Session session =null;
Transaction transaction=null;
try{
session = HibernateUtil.getSessionJavaConfigFactory().openSession();
transaction = session.beginTransaction();
session.createNativeQuery(query).executeUpdate();
transaction.commit();
}catch(Exception exception){
result=null;
if (transaction !=null && transaction.isActive()){
transaction.rollback();
}
throw new CustomException(exception.getMessage(),exception,error.ErrorCode.DATABASE_TABLE,this.getClass().getSimpleName());
}finally{
if (session !=null){
session.close();
}
}
return result;
}
``` |
24,782,717 | I'm using `hibernate 4.2.6` and `PostgreSQL 9.1`
I've been trying to execute sql query with hibernate. I've written:
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
createSQLQuery(sql);//has no effect. Query doesn't execute.
session.getTransaction().commit();
session.close();
```
This query does not executed in DB. But if I write
```
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
Properties connectionProps = new Properties();
connectionProps.put("user", "postgres");
connectionProps.put("password", "123");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/solid",connectionProps);
conn.createStatement().execute(sql);
```
corresponding row will add to table. Why hibernate doesn't work, but native query wth JDBC works? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24782717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] | Its always better to use PreparedStatement *(You dont want to give way to SQL Injections)*.
```
String sql = "INSERT INTO products (name,cost) VALUES (?,?)";
Session sess = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
Connection con = sess.connection();
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, product.getName());
pstmt.setInt(2, product.getCost());
pstmt.executeUpdate();
con.commit();
pstmt.close();
``` | worked with me in spring-boot and hibernate 5.4.2 using the entity manager
```
@Autowired
EntityManager em;
public List<String> getDistinctColumnValues(String tableName, String columnName) {
List<String> result = em.createNativeQuery("select distinct (" + columnName + ") from " + tableName).getResultList();
return result;
}
``` |
24,782,717 | I'm using `hibernate 4.2.6` and `PostgreSQL 9.1`
I've been trying to execute sql query with hibernate. I've written:
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
createSQLQuery(sql);//has no effect. Query doesn't execute.
session.getTransaction().commit();
session.close();
```
This query does not executed in DB. But if I write
```
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
Properties connectionProps = new Properties();
connectionProps.put("user", "postgres");
connectionProps.put("password", "123");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/solid",connectionProps);
conn.createStatement().execute(sql);
```
corresponding row will add to table. Why hibernate doesn't work, but native query wth JDBC works? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24782717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] | Another issue that might hit you (like it hit me) is this:
You want to run a native query, but can't get it to work in your production code? Pay attention if you are using a different database user for the application than the schema owner. In that case you may have to add the schema prefix to the referenced tables in order to make it work.
In my example I am using an entity manager instead of the session:
```
String sql = "select id from some_table";
Query query = em.createNativeQuery(sql);
List<Long> results = query.getResultList();
```
if some\_table is owned by e.g. dba while the application is running as user, you will need to modify the query to:
```
String sql = "select id from dba.some_table";
```
Having Hibernate set to prefix all tables with
```
<prop key="hibernate.default_schema">dba</prop>
```
does apparently NOT affect native queries. | The solution that work for me is the following:
```
public List<T> queryNativeExecute(String query) throws CustomException {
List<T> result =null;
Session session =null;
Transaction transaction=null;
try{
session = HibernateUtil.getSessionJavaConfigFactory().openSession();
transaction = session.beginTransaction();
session.createNativeQuery(query).executeUpdate();
transaction.commit();
}catch(Exception exception){
result=null;
if (transaction !=null && transaction.isActive()){
transaction.rollback();
}
throw new CustomException(exception.getMessage(),exception,error.ErrorCode.DATABASE_TABLE,this.getClass().getSimpleName());
}finally{
if (session !=null){
session.close();
}
}
return result;
}
``` |
24,782,717 | I'm using `hibernate 4.2.6` and `PostgreSQL 9.1`
I've been trying to execute sql query with hibernate. I've written:
```
Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
createSQLQuery(sql);//has no effect. Query doesn't execute.
session.getTransaction().commit();
session.close();
```
This query does not executed in DB. But if I write
```
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
Properties connectionProps = new Properties();
connectionProps.put("user", "postgres");
connectionProps.put("password", "123");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/solid",connectionProps);
conn.createStatement().execute(sql);
```
corresponding row will add to table. Why hibernate doesn't work, but native query wth JDBC works? | 2014/07/16 | [
"https://Stackoverflow.com/questions/24782717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] | Another issue that might hit you (like it hit me) is this:
You want to run a native query, but can't get it to work in your production code? Pay attention if you are using a different database user for the application than the schema owner. In that case you may have to add the schema prefix to the referenced tables in order to make it work.
In my example I am using an entity manager instead of the session:
```
String sql = "select id from some_table";
Query query = em.createNativeQuery(sql);
List<Long> results = query.getResultList();
```
if some\_table is owned by e.g. dba while the application is running as user, you will need to modify the query to:
```
String sql = "select id from dba.some_table";
```
Having Hibernate set to prefix all tables with
```
<prop key="hibernate.default_schema">dba</prop>
```
does apparently NOT affect native queries. | worked with me in spring-boot and hibernate 5.4.2 using the entity manager
```
@Autowired
EntityManager em;
public List<String> getDistinctColumnValues(String tableName, String columnName) {
List<String> result = em.createNativeQuery("select distinct (" + columnName + ") from " + tableName).getResultList();
return result;
}
``` |
13,607,252 | I have to position a popup element dynamically inside a container. I'm trying to get the border width of the container. I've found several questions like this one:
[How to get border width in jQuery/javascript](https://stackoverflow.com/questions/3787502/how-to-get-border-width-in-jquery-javascript)
My problem has been discussed but I haven't found any answers. How do you get the border width when the property is thick, thin, or medium?
There's word on the street that you can usually expect thin, medium, and thick to be 2px, 4px, and 6px respectively, but the CSS spec doesn't require that.
Has anyone run across an easy (or if not easy at least consistent) way to get the width of the border on one edge of a DOM element? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13607252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103075/"
] | You could use the `.innerWidth()` and `.outerWidth()` to get the the width with and without the borders and subtract the second from the first one.
```
var someElement = $("#someId");
var outer = someElement.outerWidth();
var inner = someElement.innerWidth();
alert(outer - inner); // alerts the border width in pixels
``` | Get Border width :
```
<script type="text/javascript">
$(document).ready(function(){
var widthBorder = $("div").css("border");
alert(widthBorder);
//you can split between sintax 'px'
});
</script>
``` |
13,607,252 | I have to position a popup element dynamically inside a container. I'm trying to get the border width of the container. I've found several questions like this one:
[How to get border width in jQuery/javascript](https://stackoverflow.com/questions/3787502/how-to-get-border-width-in-jquery-javascript)
My problem has been discussed but I haven't found any answers. How do you get the border width when the property is thick, thin, or medium?
There's word on the street that you can usually expect thin, medium, and thick to be 2px, 4px, and 6px respectively, but the CSS spec doesn't require that.
Has anyone run across an easy (or if not easy at least consistent) way to get the width of the border on one edge of a DOM element? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13607252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103075/"
] | You could use the `.innerWidth()` and `.outerWidth()` to get the the width with and without the borders and subtract the second from the first one.
```
var someElement = $("#someId");
var outer = someElement.outerWidth();
var inner = someElement.innerWidth();
alert(outer - inner); // alerts the border width in pixels
``` | I have a solution using an additional inner container to circumvent the problem and calculate the real border withs of all sides of the container. So if having this additional inner container is possible in your situation, then [this fiddle](http://jsfiddle.net/XxZ37/1/) works for me in Chrome/FF/Safari/IE7/IE8 and with pixel border definitions as well as thin/medium/thick:
```
var BorderWrapper = {
getBorderWidth: function(elem) {
elem = jQuery(elem);
var elemInner = jQuery(elem).find('.borderElemInner');
var posOuter = elem.position();
var posInner = elemInner.position();
var result = {
top: posInner.top - posOuter.top - parseInt(elem.css('marginTop')),
right: 0,
bottom: 0,
left: posInner.left - posOuter.left - parseInt(elem.css('marginLeft'))
};
result.right = jQuery(elem).outerWidth()
- jQuery(elemInner).outerWidth()
- result.left;
result.bottom = jQuery(elem).outerHeight()
- jQuery(elemInner).outerHeight()
- result.top;
return result;
}
};
```
It uses jQuery's ''.position()'', ''.outerWidth()'' and ''.outerHeight()'' and also accounts for margin of the outer container.
Maybe someone can verify this in IE9? I dont have it :) |
13,607,252 | I have to position a popup element dynamically inside a container. I'm trying to get the border width of the container. I've found several questions like this one:
[How to get border width in jQuery/javascript](https://stackoverflow.com/questions/3787502/how-to-get-border-width-in-jquery-javascript)
My problem has been discussed but I haven't found any answers. How do you get the border width when the property is thick, thin, or medium?
There's word on the street that you can usually expect thin, medium, and thick to be 2px, 4px, and 6px respectively, but the CSS spec doesn't require that.
Has anyone run across an easy (or if not easy at least consistent) way to get the width of the border on one edge of a DOM element? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13607252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103075/"
] | You could use the `.innerWidth()` and `.outerWidth()` to get the the width with and without the borders and subtract the second from the first one.
```
var someElement = $("#someId");
var outer = someElement.outerWidth();
var inner = someElement.innerWidth();
alert(outer - inner); // alerts the border width in pixels
``` | ```
<script type="text/javascript">
$(document).ready(function(){
var widthBorder = $("div").css("border","5px");
// you can increase your pixel size according to your requirement.
});
</script>
``` |
13,607,252 | I have to position a popup element dynamically inside a container. I'm trying to get the border width of the container. I've found several questions like this one:
[How to get border width in jQuery/javascript](https://stackoverflow.com/questions/3787502/how-to-get-border-width-in-jquery-javascript)
My problem has been discussed but I haven't found any answers. How do you get the border width when the property is thick, thin, or medium?
There's word on the street that you can usually expect thin, medium, and thick to be 2px, 4px, and 6px respectively, but the CSS spec doesn't require that.
Has anyone run across an easy (or if not easy at least consistent) way to get the width of the border on one edge of a DOM element? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13607252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103075/"
] | usualy if you have:
```
<div id="container">myContainer</div>
```
you can get the Border-Width attribute by jQuery:
```
var borderWidth = $('#container').css('borderWidth');
alert(borderWidth);
```
or for each side by:
```
var left = $('#container').css('borderLeftWidth');
var right = $('#container').css('borderRightWidth');
var top = $('#container').css('borderTopWidth');
var bottom = $('#container').css('borderBottomWidth');
alert(left+" "+right+" "+top+" "+bottom);
``` | Get Border width :
```
<script type="text/javascript">
$(document).ready(function(){
var widthBorder = $("div").css("border");
alert(widthBorder);
//you can split between sintax 'px'
});
</script>
``` |
13,607,252 | I have to position a popup element dynamically inside a container. I'm trying to get the border width of the container. I've found several questions like this one:
[How to get border width in jQuery/javascript](https://stackoverflow.com/questions/3787502/how-to-get-border-width-in-jquery-javascript)
My problem has been discussed but I haven't found any answers. How do you get the border width when the property is thick, thin, or medium?
There's word on the street that you can usually expect thin, medium, and thick to be 2px, 4px, and 6px respectively, but the CSS spec doesn't require that.
Has anyone run across an easy (or if not easy at least consistent) way to get the width of the border on one edge of a DOM element? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13607252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103075/"
] | usualy if you have:
```
<div id="container">myContainer</div>
```
you can get the Border-Width attribute by jQuery:
```
var borderWidth = $('#container').css('borderWidth');
alert(borderWidth);
```
or for each side by:
```
var left = $('#container').css('borderLeftWidth');
var right = $('#container').css('borderRightWidth');
var top = $('#container').css('borderTopWidth');
var bottom = $('#container').css('borderBottomWidth');
alert(left+" "+right+" "+top+" "+bottom);
``` | I have a solution using an additional inner container to circumvent the problem and calculate the real border withs of all sides of the container. So if having this additional inner container is possible in your situation, then [this fiddle](http://jsfiddle.net/XxZ37/1/) works for me in Chrome/FF/Safari/IE7/IE8 and with pixel border definitions as well as thin/medium/thick:
```
var BorderWrapper = {
getBorderWidth: function(elem) {
elem = jQuery(elem);
var elemInner = jQuery(elem).find('.borderElemInner');
var posOuter = elem.position();
var posInner = elemInner.position();
var result = {
top: posInner.top - posOuter.top - parseInt(elem.css('marginTop')),
right: 0,
bottom: 0,
left: posInner.left - posOuter.left - parseInt(elem.css('marginLeft'))
};
result.right = jQuery(elem).outerWidth()
- jQuery(elemInner).outerWidth()
- result.left;
result.bottom = jQuery(elem).outerHeight()
- jQuery(elemInner).outerHeight()
- result.top;
return result;
}
};
```
It uses jQuery's ''.position()'', ''.outerWidth()'' and ''.outerHeight()'' and also accounts for margin of the outer container.
Maybe someone can verify this in IE9? I dont have it :) |
13,607,252 | I have to position a popup element dynamically inside a container. I'm trying to get the border width of the container. I've found several questions like this one:
[How to get border width in jQuery/javascript](https://stackoverflow.com/questions/3787502/how-to-get-border-width-in-jquery-javascript)
My problem has been discussed but I haven't found any answers. How do you get the border width when the property is thick, thin, or medium?
There's word on the street that you can usually expect thin, medium, and thick to be 2px, 4px, and 6px respectively, but the CSS spec doesn't require that.
Has anyone run across an easy (or if not easy at least consistent) way to get the width of the border on one edge of a DOM element? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13607252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103075/"
] | usualy if you have:
```
<div id="container">myContainer</div>
```
you can get the Border-Width attribute by jQuery:
```
var borderWidth = $('#container').css('borderWidth');
alert(borderWidth);
```
or for each side by:
```
var left = $('#container').css('borderLeftWidth');
var right = $('#container').css('borderRightWidth');
var top = $('#container').css('borderTopWidth');
var bottom = $('#container').css('borderBottomWidth');
alert(left+" "+right+" "+top+" "+bottom);
``` | ```
<script type="text/javascript">
$(document).ready(function(){
var widthBorder = $("div").css("border","5px");
// you can increase your pixel size according to your requirement.
});
</script>
``` |
13,607,252 | I have to position a popup element dynamically inside a container. I'm trying to get the border width of the container. I've found several questions like this one:
[How to get border width in jQuery/javascript](https://stackoverflow.com/questions/3787502/how-to-get-border-width-in-jquery-javascript)
My problem has been discussed but I haven't found any answers. How do you get the border width when the property is thick, thin, or medium?
There's word on the street that you can usually expect thin, medium, and thick to be 2px, 4px, and 6px respectively, but the CSS spec doesn't require that.
Has anyone run across an easy (or if not easy at least consistent) way to get the width of the border on one edge of a DOM element? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13607252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103075/"
] | I played around with this for a little longer and the only solution I was able to come up with which would kind-off sort out the issue is similar to this:
```
var thinBorder = 1;
var mediumBorder = 3;
var thickBorder = 5;
function getLeftBorderWidth($element) {
var leftBorderWidth = $element.css("borderLeftWidth");
var borderWidth = 0;
switch (leftBorderWidth) {
case "thin":
borderWidth = thinBorder;
break;
case "medium":
borderWidth = mediumBorder;
break;
case "thick":
borderWidth = thickBorder;
break;
default:
borderWidth = Math.round(parseFloat(leftBorderWidth));
break;
}
return borderWidth;
}
function getRightBorderWidth($element) {
var rightBorderWidth = $element.css("borderRightWidth");
var borderWidth = 0;
switch (rightBorderWidth) {
case "thin":
borderWidth = thinBorder;
break;
case "medium":
borderWidth = mediumBorder;
break;
case "thick":
borderWidth = thickBorder;
break;
default:
borderWidth = Math.round(parseFloat(rightBorderWidth));
break;
}
return borderWidth;
}
```
### [DEMO](http://jsfiddle.net/FranWahl/3PvmW/)
Note the `Math.round()` and `parseFloat()`. Those are there because IE9 returns `0.99px` for `thin` instead of `1px` and `4.99px` for `thick` instead of `5px`.
**Edit**
You mentioned in the comments that IE7 has a different size for thin, medium and thick.
They seem to be off by only .5px which will be hard to deal with, seeing you most liekly need full numbers.
My suggestion would be to either simply ignore the .5px of a difference and acknowledge the most likely unnoticable imperfections when using IE7 and lower or if you are hell-bend on dealing with it to adjust the constants by that much similar to:
```
var thinBorder = 1;
var mediumBorder = 3;
var thickBorder = 5;
// Will be -1 if MSIE is not detected in the version string
var IEVersion = navigator.appVersion.indexOf("MSIE");
// Check if it was found then parse the version number. Version 7 will be 17 but you can trim that off with the below.
If(IEVersion > -1){
IEVersion = parseInt(navigator.appVersion.split("MSIE")[1]);
}
// Now you can simply check if you are in an ancient version of IE and adjsut any default values accordingly.
If(IEVersion < 7){
thinBorder = 0.5;
mediumBorder = 3.5;
thickBorder = 4.5;
}
/// rest as normal
```
Any of the above is by no means a copy-paste solution but merely a demonstration on a few ways one could deal with this issue. You would naturally wrap all those helpers into separate functions, plug-ins or extensions.
In your final solution you might even still need to deal with float off-sets and rounding issue.
This should be able to get you started though well enough. | Get Border width :
```
<script type="text/javascript">
$(document).ready(function(){
var widthBorder = $("div").css("border");
alert(widthBorder);
//you can split between sintax 'px'
});
</script>
``` |
13,607,252 | I have to position a popup element dynamically inside a container. I'm trying to get the border width of the container. I've found several questions like this one:
[How to get border width in jQuery/javascript](https://stackoverflow.com/questions/3787502/how-to-get-border-width-in-jquery-javascript)
My problem has been discussed but I haven't found any answers. How do you get the border width when the property is thick, thin, or medium?
There's word on the street that you can usually expect thin, medium, and thick to be 2px, 4px, and 6px respectively, but the CSS spec doesn't require that.
Has anyone run across an easy (or if not easy at least consistent) way to get the width of the border on one edge of a DOM element? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13607252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103075/"
] | I played around with this for a little longer and the only solution I was able to come up with which would kind-off sort out the issue is similar to this:
```
var thinBorder = 1;
var mediumBorder = 3;
var thickBorder = 5;
function getLeftBorderWidth($element) {
var leftBorderWidth = $element.css("borderLeftWidth");
var borderWidth = 0;
switch (leftBorderWidth) {
case "thin":
borderWidth = thinBorder;
break;
case "medium":
borderWidth = mediumBorder;
break;
case "thick":
borderWidth = thickBorder;
break;
default:
borderWidth = Math.round(parseFloat(leftBorderWidth));
break;
}
return borderWidth;
}
function getRightBorderWidth($element) {
var rightBorderWidth = $element.css("borderRightWidth");
var borderWidth = 0;
switch (rightBorderWidth) {
case "thin":
borderWidth = thinBorder;
break;
case "medium":
borderWidth = mediumBorder;
break;
case "thick":
borderWidth = thickBorder;
break;
default:
borderWidth = Math.round(parseFloat(rightBorderWidth));
break;
}
return borderWidth;
}
```
### [DEMO](http://jsfiddle.net/FranWahl/3PvmW/)
Note the `Math.round()` and `parseFloat()`. Those are there because IE9 returns `0.99px` for `thin` instead of `1px` and `4.99px` for `thick` instead of `5px`.
**Edit**
You mentioned in the comments that IE7 has a different size for thin, medium and thick.
They seem to be off by only .5px which will be hard to deal with, seeing you most liekly need full numbers.
My suggestion would be to either simply ignore the .5px of a difference and acknowledge the most likely unnoticable imperfections when using IE7 and lower or if you are hell-bend on dealing with it to adjust the constants by that much similar to:
```
var thinBorder = 1;
var mediumBorder = 3;
var thickBorder = 5;
// Will be -1 if MSIE is not detected in the version string
var IEVersion = navigator.appVersion.indexOf("MSIE");
// Check if it was found then parse the version number. Version 7 will be 17 but you can trim that off with the below.
If(IEVersion > -1){
IEVersion = parseInt(navigator.appVersion.split("MSIE")[1]);
}
// Now you can simply check if you are in an ancient version of IE and adjsut any default values accordingly.
If(IEVersion < 7){
thinBorder = 0.5;
mediumBorder = 3.5;
thickBorder = 4.5;
}
/// rest as normal
```
Any of the above is by no means a copy-paste solution but merely a demonstration on a few ways one could deal with this issue. You would naturally wrap all those helpers into separate functions, plug-ins or extensions.
In your final solution you might even still need to deal with float off-sets and rounding issue.
This should be able to get you started though well enough. | I have a solution using an additional inner container to circumvent the problem and calculate the real border withs of all sides of the container. So if having this additional inner container is possible in your situation, then [this fiddle](http://jsfiddle.net/XxZ37/1/) works for me in Chrome/FF/Safari/IE7/IE8 and with pixel border definitions as well as thin/medium/thick:
```
var BorderWrapper = {
getBorderWidth: function(elem) {
elem = jQuery(elem);
var elemInner = jQuery(elem).find('.borderElemInner');
var posOuter = elem.position();
var posInner = elemInner.position();
var result = {
top: posInner.top - posOuter.top - parseInt(elem.css('marginTop')),
right: 0,
bottom: 0,
left: posInner.left - posOuter.left - parseInt(elem.css('marginLeft'))
};
result.right = jQuery(elem).outerWidth()
- jQuery(elemInner).outerWidth()
- result.left;
result.bottom = jQuery(elem).outerHeight()
- jQuery(elemInner).outerHeight()
- result.top;
return result;
}
};
```
It uses jQuery's ''.position()'', ''.outerWidth()'' and ''.outerHeight()'' and also accounts for margin of the outer container.
Maybe someone can verify this in IE9? I dont have it :) |
13,607,252 | I have to position a popup element dynamically inside a container. I'm trying to get the border width of the container. I've found several questions like this one:
[How to get border width in jQuery/javascript](https://stackoverflow.com/questions/3787502/how-to-get-border-width-in-jquery-javascript)
My problem has been discussed but I haven't found any answers. How do you get the border width when the property is thick, thin, or medium?
There's word on the street that you can usually expect thin, medium, and thick to be 2px, 4px, and 6px respectively, but the CSS spec doesn't require that.
Has anyone run across an easy (or if not easy at least consistent) way to get the width of the border on one edge of a DOM element? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13607252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103075/"
] | I played around with this for a little longer and the only solution I was able to come up with which would kind-off sort out the issue is similar to this:
```
var thinBorder = 1;
var mediumBorder = 3;
var thickBorder = 5;
function getLeftBorderWidth($element) {
var leftBorderWidth = $element.css("borderLeftWidth");
var borderWidth = 0;
switch (leftBorderWidth) {
case "thin":
borderWidth = thinBorder;
break;
case "medium":
borderWidth = mediumBorder;
break;
case "thick":
borderWidth = thickBorder;
break;
default:
borderWidth = Math.round(parseFloat(leftBorderWidth));
break;
}
return borderWidth;
}
function getRightBorderWidth($element) {
var rightBorderWidth = $element.css("borderRightWidth");
var borderWidth = 0;
switch (rightBorderWidth) {
case "thin":
borderWidth = thinBorder;
break;
case "medium":
borderWidth = mediumBorder;
break;
case "thick":
borderWidth = thickBorder;
break;
default:
borderWidth = Math.round(parseFloat(rightBorderWidth));
break;
}
return borderWidth;
}
```
### [DEMO](http://jsfiddle.net/FranWahl/3PvmW/)
Note the `Math.round()` and `parseFloat()`. Those are there because IE9 returns `0.99px` for `thin` instead of `1px` and `4.99px` for `thick` instead of `5px`.
**Edit**
You mentioned in the comments that IE7 has a different size for thin, medium and thick.
They seem to be off by only .5px which will be hard to deal with, seeing you most liekly need full numbers.
My suggestion would be to either simply ignore the .5px of a difference and acknowledge the most likely unnoticable imperfections when using IE7 and lower or if you are hell-bend on dealing with it to adjust the constants by that much similar to:
```
var thinBorder = 1;
var mediumBorder = 3;
var thickBorder = 5;
// Will be -1 if MSIE is not detected in the version string
var IEVersion = navigator.appVersion.indexOf("MSIE");
// Check if it was found then parse the version number. Version 7 will be 17 but you can trim that off with the below.
If(IEVersion > -1){
IEVersion = parseInt(navigator.appVersion.split("MSIE")[1]);
}
// Now you can simply check if you are in an ancient version of IE and adjsut any default values accordingly.
If(IEVersion < 7){
thinBorder = 0.5;
mediumBorder = 3.5;
thickBorder = 4.5;
}
/// rest as normal
```
Any of the above is by no means a copy-paste solution but merely a demonstration on a few ways one could deal with this issue. You would naturally wrap all those helpers into separate functions, plug-ins or extensions.
In your final solution you might even still need to deal with float off-sets and rounding issue.
This should be able to get you started though well enough. | ```
<script type="text/javascript">
$(document).ready(function(){
var widthBorder = $("div").css("border","5px");
// you can increase your pixel size according to your requirement.
});
</script>
``` |
62,543,396 | i have this query which is very simple but i dont want to use index here due to some constraints.
so my worry is how to avoid huge load on server if we are calling non indexed item in where clause.
the solution i feel will be limit.
i am sure of having data in 1000 rows so if i use limit i can check the available values.
```
SELECT *
from tableA
where status='1' and student='$student_no'
order by id desc
limit 1000
```
here student column is not indexed in mysql so my worry is it will cause huge load in server
i tried with explain and it seems to be ok but problem is less no of rows in table and as u know mysql goes crazy with more data like millions of rows.
so what are my options ??
i should add index for student ??
if i will add index then i dont need 1000 rows in limit. one row is sufficient and as i said table is going to be several millions of rows so it requires lot of space so i was thinking to avoid indexing of student column and other query is 1000 row with desc row should not cause load on server as id is indexed.
any help will be great | 2020/06/23 | [
"https://Stackoverflow.com/questions/62543396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13095122/"
] | For that specific layout I would use VBox instead of AnchorPane:
```
Label label = new Label("User Name");
ChoiceBox<String> cb = new ChoiceBox<>();
VBox container = new VBox();
container.setPadding(new Insets(20, 0, 0, 0));
container.setSpacing(10);
List<String> items = List.of("<New User>", "EasyGoing1");
cb.getItems().addAll(items);
container.getChildren().addAll(label, cb);
```
On the other hand, in a `ChoiceBox`, the popup will move to line up the item that matches the one in the `ChoiceBox`. If you add more items you'll see the effect. I guess that's the intended behavior to avoid the need to scroll to selected item. | Oboe was correct, if I use a ComboBox instead of a ChoiceBox, the control behaves as I want it to. After looking up the difference between the two, I think a ComboBox will suit my needs just fine.
Thank you Oboe.
If anyone is interested, here is the code behaving as desired:
```
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import com.sun.tools.javac.util.List;
public class SimpleForm extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
anchorPane = new AnchorPane();
stage = new Stage();
scene = new Scene(anchorPane, width, height);
start();
}
private AnchorPane anchorPane;
private Stage stage;
private Scene scene;
private double width = 300;
private double height = 550;
private ComboBox<String> comboBox;
private Label label;
public void start() {
comboBox = new ComboBox<>();
comboBox.setPrefWidth(150);
label = new Label("User Name");
String item1 = "<New User>";
String item2 = "John Doe";
String item4 = "Jane Doe";
String item3 = "Jack Doe";
VBox container = new VBox();
container.setPadding(new Insets(20, 0, 0, 0));
container.setSpacing(10);
List<String> items = List.of(item1, item2, item3, item4);
comboBox.getItems().addAll(items);
container.getChildren().addAll(label, comboBox);
anchorPane.getChildren().add(container);
stage.setScene(scene);
stage.show();
}
}
``` |
28,890,813 | Using bootstrap v3 adapt each level of Pascal Triangle. Each level must adapt to width according each device, level 1 one single adaptive box, level 2 3 single adaptive box, etc. | 2015/03/06 | [
"https://Stackoverflow.com/questions/28890813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639143/"
] | There is a wrong offset between your injected value and the name of it
You injected `fetchSet` but you did not use it in the function signature
This
```
function CardInfoController (fetchCard, _, $routeParams, $filter, $location) {
```
Should be
```
function CardInfoController (fetchCard, fetchSet, _, $routeParams, $filter, $location) {
```
And the cosmic order of the great signature is restored | `$routeParams` is a service of the `ngRoute` module, you have to add it to your module declaration:
```
angular
.module('card-info.controller', ['ui.bootstrap', 'ngRoute'])
.controller('CardInfoController', CardInfoController);
```
Source: [$routeParams](https://docs.angularjs.org/api/ngRoute/service/$routeParams) |
10,325,599 | I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?
```
for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
``` | 2012/04/26 | [
"https://Stackoverflow.com/questions/10325599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200295/"
] | How about using `--since` and `--before`?
For example, this will delete all branches that have not received any commits for a week:
```
for k in $(git branch | sed /\*/d); do
if [ -z "$(git log -1 --since='1 week ago' -s $k)" ]; then
git branch -D $k
fi
done
```
If you want to delete all branches that are more than a week old, use `--before`:
```
for k in $(git branch | sed /\*/d); do
if [ -z "$(git log -1 --before='1 week ago' -s $k)" ]; then
git branch -D $k
fi
done
```
Be warned though that this will also delete branches that where not merged into master or whatever the checked out branch is. | *The poor man's method:*
List the branches by the date of last commit:
```
git branch --sort=committerdate | xargs echo
```
this will list the branches while `xargs echo` pipe makes it inline (*thx [Jesse](https://stackoverflow.com/questions/10325599/delete-all-branches-that-are-more-than-x-days-weeks-old/49998249#comment96947958_49998249)*).
You will see **all your branches with old ones at the beginning**:
```
1_branch 2_branch 3_branch 4_branch
```
Copy the **first n ones**, which are outdated and paste at the end of the batch delete command:
```
git branch -D 1_branch 2_branch
```
This will delete the selected ones only, so you have more control over the process.
*To list the branches by creation date, use the `--sort=authordate:iso8601` command as suggested by [Amy](https://davidwalsh.name/sort-git-branches#comment-502442)*
### Remove remote branches
Use
`git branch -r --sort=committerdate | xargs echo` *(says [kustomrtr](https://stackoverflow.com/questions/10325599/delete-all-branches-that-are-more-than-x-days-weeks-old/49998249#comment103834030_49998249))* to review the remote branches, than `git push origin -d 1_branch 2_branch` to delete the merged ones
*(thx [Jonas](https://stackoverflow.com/questions/10325599/delete-all-branches-that-are-more-than-x-days-weeks-old/49998249#comment114742932_49998249))*. |
10,325,599 | I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?
```
for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
``` | 2012/04/26 | [
"https://Stackoverflow.com/questions/10325599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200295/"
] | This is what worked for me:
```
for k in $(git branch -r | sed /\*/d); do
if [ -z "$(git log -1 --since='Aug 10, 2016' -s $k)" ]; then
branch_name_with_no_origin=$(echo $k | sed -e "s/origin\///")
echo deleting branch: $branch_name_with_no_origin
git push origin --delete $branch_name_with_no_origin
fi
done
```
The crucial part is that the branch name (variable $k) contains the `/origin/` part eg `origin/feature/my-cool-new-branch`
However, if you try to git push --delete, it'll fail with an error like:
unable to delete 'origin/feature/my-cool-new-branch': remote ref does not exist.
So we use sed to remove the `/origin/` part so that we are left with a branch name like `feature/my-cool-new-branch` and now git push --delete will work. | For how using **PowerShell:**
* **Delete all merged branches** excluding notMatch pattern
```
git branch -r --merged | Select-String -NotMatch "(^\*|master)" | %{ $_ -replace ".*/", "" } | %{ git push origin --delete $_ }
```
* **List all merged branches** in txt file
```
git branch -r --merged | Select-String -NotMatch "(^\*|master)" | %{ $_ -replace ".*/", "" } | Set-Content -Path .\deleted-branches.txt
``` |
10,325,599 | I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?
```
for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
``` | 2012/04/26 | [
"https://Stackoverflow.com/questions/10325599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200295/"
] | The [above code](https://stackoverflow.com/a/10325758/537998) did not work for me, but it was close. Instead, I used the following:
```
for k in $(git branch | sed /\*/d); do
if [[ ! $(git log -1 --since='2 weeks ago' -s $k) ]]; then
git branch -D $k
fi
done
``` | I'm assuming that you want to delete just the refs, not the commits in the branches. To delete all merged branches except the most recent `__X__`:
```
git branch -d `for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk 'BEGIN{ORS=" "}; {if(NR>__X__) print $2}'`
```
To delete all branches before timestamp `__Y__`:
```
git branch -d `for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk 'BEGIN{ORS=" "}; {if($1<__Y__) print $2}'`
```
Replace the `-d` option by `-D` if you want to delete branches that haven't been merged as well... but be careful, because that will cause the dangling commits to be garbage-collected at some point. |
10,325,599 | I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?
```
for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
``` | 2012/04/26 | [
"https://Stackoverflow.com/questions/10325599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200295/"
] | Safe way to show the delete commands only for local branches merged into master with the last commit over a month ago.
```sh
for k in $(git branch --format="%(refname:short)" --merged master); do
if (($(git log -1 --since='1 month ago' -s $k|wc -l)==0)); then
echo git branch -d $k
fi
done
```
This *does nothing* but to output something like:
```
git branch -d issue_3212
git branch -d fix_ui_search
git branch -d issue_3211
```
Which I copy and paste directly (remove the echo to delete it directly)
This is very safe. | Sometimes it needs to know if a branch has been merged to the master branch. For that purpose could be used the following script:
```
#!/usr/bin/env bash
read -p "If you want delete branhes type 'D', otherwise press 'Enter' and branches will be printed out only: " action
[[ $action = "D" ]] && ECHO="" || ECHO="echo"
for b in $(git branch -r --merged origin/master | sed /\*/d | egrep -v "^\*|master|develop"); do
if [ "$(git log $b --since "10 months ago" | wc -l)" -eq 0 ]; then
$ECHO git push origin --delete "${b/origin\/}" --no-verify;
fi
done
```
Tested on Ubuntu 18.04 |
10,325,599 | I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?
```
for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
``` | 2012/04/26 | [
"https://Stackoverflow.com/questions/10325599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200295/"
] | How about using `--since` and `--before`?
For example, this will delete all branches that have not received any commits for a week:
```
for k in $(git branch | sed /\*/d); do
if [ -z "$(git log -1 --since='1 week ago' -s $k)" ]; then
git branch -D $k
fi
done
```
If you want to delete all branches that are more than a week old, use `--before`:
```
for k in $(git branch | sed /\*/d); do
if [ -z "$(git log -1 --before='1 week ago' -s $k)" ]; then
git branch -D $k
fi
done
```
Be warned though that this will also delete branches that where not merged into master or whatever the checked out branch is. | Based on @daniel-baulig's answer and the comments I came up with this:
```
for k in $(git branch -r --format="%(refname:short)" | sed s#^origin/##); do
if [ -z "$(git log -1 --since='4 week ago' -s $k)" ]; then
## Info about the branches before deleting
git log -1 --format="%ci %ce - %H $k" -s $k;
## Delete from the remote
git push origin --delete $k;
## Delete the local branch, regardless of whether it's been merged or not
git branch -D $k
fi;
done
```
This can be used to delete all old branches (merged or NOT).
The motivation for doing so is that it is unlikely that branches that has not been touched in a month rot and never make it to master. Naturally, the timeframe for pruning old branches depends on how fast the master branch moves. |
10,325,599 | I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?
```
for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
``` | 2012/04/26 | [
"https://Stackoverflow.com/questions/10325599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200295/"
] | How about using `--since` and `--before`?
For example, this will delete all branches that have not received any commits for a week:
```
for k in $(git branch | sed /\*/d); do
if [ -z "$(git log -1 --since='1 week ago' -s $k)" ]; then
git branch -D $k
fi
done
```
If you want to delete all branches that are more than a week old, use `--before`:
```
for k in $(git branch | sed /\*/d); do
if [ -z "$(git log -1 --before='1 week ago' -s $k)" ]; then
git branch -D $k
fi
done
```
Be warned though that this will also delete branches that where not merged into master or whatever the checked out branch is. | For how using **PowerShell:**
* **Delete all merged branches** excluding notMatch pattern
```
git branch -r --merged | Select-String -NotMatch "(^\*|master)" | %{ $_ -replace ".*/", "" } | %{ git push origin --delete $_ }
```
* **List all merged branches** in txt file
```
git branch -r --merged | Select-String -NotMatch "(^\*|master)" | %{ $_ -replace ".*/", "" } | Set-Content -Path .\deleted-branches.txt
``` |
10,325,599 | I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?
```
for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
``` | 2012/04/26 | [
"https://Stackoverflow.com/questions/10325599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200295/"
] | This is what worked for me:
```
for k in $(git branch -r | sed /\*/d); do
if [ -z "$(git log -1 --since='Aug 10, 2016' -s $k)" ]; then
branch_name_with_no_origin=$(echo $k | sed -e "s/origin\///")
echo deleting branch: $branch_name_with_no_origin
git push origin --delete $branch_name_with_no_origin
fi
done
```
The crucial part is that the branch name (variable $k) contains the `/origin/` part eg `origin/feature/my-cool-new-branch`
However, if you try to git push --delete, it'll fail with an error like:
unable to delete 'origin/feature/my-cool-new-branch': remote ref does not exist.
So we use sed to remove the `/origin/` part so that we are left with a branch name like `feature/my-cool-new-branch` and now git push --delete will work. | ```
for k in $(git branch -r | sed /\*/d); do
if [ -n "$(git log -1 --before='80 week ago' -s $k)" ]; then
git push origin --delete "${k/origin\//}"
fi
done
``` |
10,325,599 | I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?
```
for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
``` | 2012/04/26 | [
"https://Stackoverflow.com/questions/10325599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200295/"
] | ```
for k in $(git branch -r | sed /\*/d); do
if [ -n "$(git log -1 --before='80 week ago' -s $k)" ]; then
git push origin --delete "${k/origin\//}"
fi
done
``` | I'm assuming that you want to delete just the refs, not the commits in the branches. To delete all merged branches except the most recent `__X__`:
```
git branch -d `for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk 'BEGIN{ORS=" "}; {if(NR>__X__) print $2}'`
```
To delete all branches before timestamp `__Y__`:
```
git branch -d `for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk 'BEGIN{ORS=" "}; {if($1<__Y__) print $2}'`
```
Replace the `-d` option by `-D` if you want to delete branches that haven't been merged as well... but be careful, because that will cause the dangling commits to be garbage-collected at some point. |
10,325,599 | I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?
```
for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
``` | 2012/04/26 | [
"https://Stackoverflow.com/questions/10325599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200295/"
] | Safe way to show the delete commands only for local branches merged into master with the last commit over a month ago.
```sh
for k in $(git branch --format="%(refname:short)" --merged master); do
if (($(git log -1 --since='1 month ago' -s $k|wc -l)==0)); then
echo git branch -d $k
fi
done
```
This *does nothing* but to output something like:
```
git branch -d issue_3212
git branch -d fix_ui_search
git branch -d issue_3211
```
Which I copy and paste directly (remove the echo to delete it directly)
This is very safe. | ```
for k in $(git branch -r | sed /\*/d); do
if [ -n "$(git log -1 --before='80 week ago' -s $k)" ]; then
git push origin --delete "${k/origin\//}"
fi
done
``` |
10,325,599 | I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?
```
for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
``` | 2012/04/26 | [
"https://Stackoverflow.com/questions/10325599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200295/"
] | Delete 5 oldest remote branches
```
git branch -r --sort=committerdate | head -n 5 | sed 's/ origin\///' | xargs git push origin --delete
``` | For how using **PowerShell:**
* **Delete all merged branches** excluding notMatch pattern
```
git branch -r --merged | Select-String -NotMatch "(^\*|master)" | %{ $_ -replace ".*/", "" } | %{ git push origin --delete $_ }
```
* **List all merged branches** in txt file
```
git branch -r --merged | Select-String -NotMatch "(^\*|master)" | %{ $_ -replace ".*/", "" } | Set-Content -Path .\deleted-branches.txt
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.