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 |
|---|---|---|---|---|---|
4,049,200 | I understand conceptually that a function $f\colon A\to\mathbf R$ is differentiable at a point $a\in A$ if it can be well approximated by a line there; more precisely, if we can find a constant $f'(a)$ such that $$f(a+h) = f(a) + f'(a)h+o(h).$$
>
> My goal: I want to understand (intuitively) what it means when a function is twice differentiable, or thrice, etc, and likewise what it means when it isn't.
>
>
>
In a very loose sense, I have the intuition that a function is somehow smooth*er* around a point if it has higher order differentiability there, and I suppose this somehow corresponds to the fact that it can be approximated well not only by a line but even better by a polynomial. (e.g. twice differentiability is $f(a+h) = f(a) + f'(a)h + \tfrac12f''(a)h^2 + o(h^2)$, etc.). Does this mean polynomials canonically define the notion of "smoothness"?
Perhaps I can best get across what I'm asking for with an example. When I look at the graphs of
$$y=x|x| \qquad \text{and} \qquad y=x^3$$
for instance, I see that the latter grows quicker than the former, but around zero, they both basically look "smooth" to me. Yes I know that one is made of the absolute value function which is pointy, but if you just showed me these two pictures:
[](https://i.stack.imgur.com/ZWB02.png) [](https://i.stack.imgur.com/brZcC.png)
I wouldn't really feel that one is somehow "smoother" around zero than the other.
Is there a better way I can think about this? | 2021/03/04 | [
"https://math.stackexchange.com/questions/4049200",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/714716/"
] | Here are some thoughts:
To study, as always, I use my favourite tool of [Taylor's theorem](https://brianbabu890.medium.com/)(\*):
$$ f(a+h) = f(a) + h f'(a) + \frac{h^2}{2} f''(a) +O(h^3)$$
Now, let's analyze $f''(a)$, if $f(a+h)$ is not differentiable, it means the left hand derivative and right hand derivative are not equal i.e(Or may be the limit themself don't exist, but let us forget the case for now):
$$ \lim\_{h \to 0} \frac{f'(a+h) - f'(a)}{h} \neq \frac{ f'(a) - f'(a-h ) }{h}$$
Let's call the right hand 2nd derivative as $f\_{R}$ and left hand 2nd derivative as $f\_{L}$, this leads to 'two' series of the function locally. That is, for points to the right of $f$, we have
$$ f(a+h) = f(a) + hf'(a) + \frac{h^2}{2} f\_{R}''(a) + O(h^3)$$
And another series for the left of $f$ as:
$$ f(a-h) = f(a) - h f'(a) + \frac{h^2}{2} f\_{L}''(a) + O(h^3)$$
Now, here's the deal, the second order derivative and higher terms only become really relevant (for most nice functions) after $h>1$, this because if $h<1$ then $h^2 <h$, so it turns out that if it is only the second derivative and above which of a function which doesn't match, the Taylor series approximates well.. but outside that bound, we need to be careful and using the piecewise definition.
---
\*: The link is to an article I've written on it, I highly suggest reading it if you want a real insight into the theorem.
\*\*: Right hand derivative: $ \frac{f'(a+h)-f'(a)}{h} $ and the left hand derivative $ \frac{f'(a) - f'(a-h)}{h}$
\*\*\*: If we restrict ourselves to the differentiability of second derivatives, then we can think of it as the convexity of the graph suddenly changing. | I think that there is a sense in which polynomials can indeed be viewed as "defining the notion of smoothness" because a function whose $n$th derivative is identically $0$ is a polynomial of degree $n-1$. |
4,049,200 | I understand conceptually that a function $f\colon A\to\mathbf R$ is differentiable at a point $a\in A$ if it can be well approximated by a line there; more precisely, if we can find a constant $f'(a)$ such that $$f(a+h) = f(a) + f'(a)h+o(h).$$
>
> My goal: I want to understand (intuitively) what it means when a function is twice differentiable, or thrice, etc, and likewise what it means when it isn't.
>
>
>
In a very loose sense, I have the intuition that a function is somehow smooth*er* around a point if it has higher order differentiability there, and I suppose this somehow corresponds to the fact that it can be approximated well not only by a line but even better by a polynomial. (e.g. twice differentiability is $f(a+h) = f(a) + f'(a)h + \tfrac12f''(a)h^2 + o(h^2)$, etc.). Does this mean polynomials canonically define the notion of "smoothness"?
Perhaps I can best get across what I'm asking for with an example. When I look at the graphs of
$$y=x|x| \qquad \text{and} \qquad y=x^3$$
for instance, I see that the latter grows quicker than the former, but around zero, they both basically look "smooth" to me. Yes I know that one is made of the absolute value function which is pointy, but if you just showed me these two pictures:
[](https://i.stack.imgur.com/ZWB02.png) [](https://i.stack.imgur.com/brZcC.png)
I wouldn't really feel that one is somehow "smoother" around zero than the other.
Is there a better way I can think about this? | 2021/03/04 | [
"https://math.stackexchange.com/questions/4049200",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/714716/"
] | Here are some thoughts:
To study, as always, I use my favourite tool of [Taylor's theorem](https://brianbabu890.medium.com/)(\*):
$$ f(a+h) = f(a) + h f'(a) + \frac{h^2}{2} f''(a) +O(h^3)$$
Now, let's analyze $f''(a)$, if $f(a+h)$ is not differentiable, it means the left hand derivative and right hand derivative are not equal i.e(Or may be the limit themself don't exist, but let us forget the case for now):
$$ \lim\_{h \to 0} \frac{f'(a+h) - f'(a)}{h} \neq \frac{ f'(a) - f'(a-h ) }{h}$$
Let's call the right hand 2nd derivative as $f\_{R}$ and left hand 2nd derivative as $f\_{L}$, this leads to 'two' series of the function locally. That is, for points to the right of $f$, we have
$$ f(a+h) = f(a) + hf'(a) + \frac{h^2}{2} f\_{R}''(a) + O(h^3)$$
And another series for the left of $f$ as:
$$ f(a-h) = f(a) - h f'(a) + \frac{h^2}{2} f\_{L}''(a) + O(h^3)$$
Now, here's the deal, the second order derivative and higher terms only become really relevant (for most nice functions) after $h>1$, this because if $h<1$ then $h^2 <h$, so it turns out that if it is only the second derivative and above which of a function which doesn't match, the Taylor series approximates well.. but outside that bound, we need to be careful and using the piecewise definition.
---
\*: The link is to an article I've written on it, I highly suggest reading it if you want a real insight into the theorem.
\*\*: Right hand derivative: $ \frac{f'(a+h)-f'(a)}{h} $ and the left hand derivative $ \frac{f'(a) - f'(a-h)}{h}$
\*\*\*: If we restrict ourselves to the differentiability of second derivatives, then we can think of it as the convexity of the graph suddenly changing. | I think it would be difficult to deduce that $x|x|$ is not twice differentiable at $x=0$ simply by looking at its graph, but this is how I would think about it. Every function $y=f(x)$ can trivially be parameterised with respect to the $x$-coordinate, meaning that we can define its displacement function as $s(t)=(t,f(t))$, and its velocity function as $v(t)=(1,f'(t))$. The second derivative then has a slightly more concrete interpretation as the rate of change of the vertical component of the velocity function.
In the case of $y=x^3$, $s(t)=(t,t^3)$ and $v(t)=(1,3t^2)$. In the below animation, the velocity vector is represented by the red arrow, and the vertical component of that velocity vector is also shown separately in green:
[](https://i.stack.imgur.com/LIu2r.gif)
Notice how the green arrow slows down smoothly before it gets to zero, and then starts speeding up again. This is in constrast to how $y=x|x|$ behaves around $0$:
[](https://i.stack.imgur.com/j1tby.gif)
Since the derivative of $x|x|$ is $|x|$, the green vector arrow is moving downwards at a constant rate, and then it *instantly* changes direction and goes up at the same rate when $x>0$. Looking at how the red and green vector arrows suddenly pop up gives us a clue about the differentiability of $x|x|$ at $0$. Of course, this animation is not entirely convincing, and things get much harder when you start talking about third and fourth derivatives, but this is how like to think about intuitively. @Fakemistake's car analogy also helped me in understanding this. |
3,219,233 | I have fixed area 2d space filled with rectangles. I'd like to move the rectangles around, add new ones, remove some, but not allow them to overlap. If all of the rects are the same height and width (50x50px), what data structure should I use to store their position and what space they are using and what lookup method should I use against that structure when adding new rects to the scene? | 2010/07/10 | [
"https://Stackoverflow.com/questions/3219233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388434/"
] | This is the easy part of the classic [collision detection](http://en.wikipedia.org/wiki/Collision_detection) problem. Mostly [AABB Trees](http://www.cyberkreations.com/kreationsedge/?page_id=27) (not sure if that's the *best* link, but that's the name, anyway) are used to solve it efficiently, but look up anything collision detection algorithms use for bounding box collision detection. An AABB (Axis Aligned Bounding Box) Tree is for rectangles that are "aligned"-- that is, rectangles that cannot be rotated.
For non-aligned rectangles, just take the smallest axis-aligned rectangle that contains your rotated rectangle. Indeed an AABB tree is used to speed up collision detection for arbitrary polygons, by taking their bounding boxes. In the case of where an axis-aligned bounding box is equal to all your objects, it's even better.
However, if you don't mind performance, using a flat list of rectangles and doing an O(n2) search would really be easier: in pseudocode:
```
function intersection_free(rectangles)
for rect in rectangles
for rect2 in rectangles
if intersects(rect, rect2)
return false;
return true;
```
Simplicity is a wonderful thing, isn't it? | I'm not sure I fully understand your environment but you could consider using a 2-dimensional array which is essentially a matrix. Each spot would represent one of your squares in your 2D space. |
3,219,233 | I have fixed area 2d space filled with rectangles. I'd like to move the rectangles around, add new ones, remove some, but not allow them to overlap. If all of the rects are the same height and width (50x50px), what data structure should I use to store their position and what space they are using and what lookup method should I use against that structure when adding new rects to the scene? | 2010/07/10 | [
"https://Stackoverflow.com/questions/3219233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388434/"
] | In general, you should use a multidimensional data structure when dealing with these kind of problems. [kd-tree](http://en.wikipedia.org/wiki/Kd-tree) and [R-tree](http://en.wikipedia.org/wiki/R-tree) are good starting point to learn the subject. Since these structures are relatively complex, consider using it only if you need to deal with 1000's of rectangles / do fast calculations.
However, in your specific case - And if the plane size is limited - you can use a grid (let's say 100x100) of cells, that divides the plane, and store a list of rectangles in each cell, according to the top-left corrdinates of each rectangle. When searching for collision, search in the relevant cell and it's neighbours only. Since your rectangles size is constant, this may be the best solution for you.
Note that you can store the 2D array in a 1D array where each grid-cell index is 100X+Y. Now, you can store grid-cells in a map to save memory.
If you are dealing with a small/slow scale problem, Just store the rectangles in a list and walk over the list to search for a collision. | I'm not sure I fully understand your environment but you could consider using a 2-dimensional array which is essentially a matrix. Each spot would represent one of your squares in your 2D space. |
276,562 | New to mathematica and have looked into the matrix page but can't find anything to help.
y= (4,3,3,1), u1=(1,1,0,1), u2= (-1,3,1,-2), u3=(-1,0,1,1) | 2022/11/27 | [
"https://mathematica.stackexchange.com/questions/276562",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/85306/"
] | We can minimize the square of the distance of `λ1*u1 + λ2*u2 + λ3*u3` and `y`.
```
u1 = {1, 1, 0, 1};
u2 = {-1, 3, 1, -2};
u3 = {-1, 0, 1, 1};
y = {4, 3, 3, 1};
sol=Minimize[(λ1*u1 + λ2*u2 + λ3*u3 - y) . (λ1*u1 + λ2*u2 + λ3*u3 - y), {λ1, λ2,λ3}]
proj = λ1*u1 + λ2*u2 + λ3*u3 /. sol[[2]]
```
[](https://i.stack.imgur.com/8ZQEw.png) | ```
W = {{1, 1, 0, 1}, {-1, 3, 1, -2}, {-1, 0, 1, 1}};
y = {4, 3, 3, 1};
```
Find the coefficients `x` that minimize the squared deviation:
```
x = LeastSquares[Transpose[W], y]
(* {8/3, 2/5, 0} *)
```
From this, calculate the vector `z` that approximates `y` optimally in the least-squares sense:
```
z = Transpose[W] . x
(* {34/15, 58/15, 2/5, 28/15} *)
```
This is the same method as what cvgmt suggests but with an explicit call to the [least-squares minimizer](https://reference.wolfram.com/language/ref/LeastSquares.html). |
59,482,652 | I have the following js code structure;
```
Promise_1.then(function(){
for(){
Promise2.then(function(){
...
})
}
}).then(
Promise_3.then(function(){
for(){
Promise4.then(function(){
...
})
}
})
).then(
function(){
// SOME CODE
}
)
```
I want to execute SOME CODE after the above promises are resolved. But the SOME CODE is executing before the above promises are resolved. I know I can enclose SOME CODE in `setTimeout()` which will solve the problem as suggested by other answers on SO but I think it's not a good idea. The actual code on which I am working is as follow;
```
user_xp = 0
connections_blocks.methods.get_deposit_blocks(current_email).call({
from: new_web3.eth.Contract.defaultAccount
}, function (err, result) {
deposit_blocks = result
console.log(deposit_blocks)
deposit_blocks = deposit_blocks.split(",")
deposit_blocks.splice(0, 1)
for (i_ in deposit_blocks) {
console.log(deposit_blocks[i_])
user_xp + new_web3.eth.getBlock(deposit_blocks[i_]).then(function (deposit_block) {
user_xp = user_xp + deposit_block.gasUsed
console.log(user_xp)
})
}
}).then(
connections_blocks.methods.get_send_blocks(current_email).call({
from: new_web3.eth.Contract.defaultAccount
}, function (err, result) {
send_blocks = result
console.log(send_blocks)
send_blocks = send_blocks.split(",")
send_blocks.splice(0, 1)
for (i_ = 0; i_ < send_blocks.length; i_ = i_ + 2) {
console.log(send_blocks[i_])
user_xp + new_web3.eth.getBlock(send_blocks[i_]).then(function (send_block) {
user_xp = user_xp + send_block.gasUsed
console.log(user_xp)
})
}
})).then(
setTimeout(function () {
console.log(user_xp)
xp = document.getElementById('xp')
xp.innerHTML = "XP:" + user_xp
},1000)
)
```
In the above code, I am just using `setTimeout()` which is solving my problem. But I want the code to execute automatically only when the above promises are resolved. Is there any easy way to do that in JS w/o putting promises in functions and making it more complex.
**UPDATE**
I am using the following web3's function to fetch data from the solidity's smart contract which actually returns a promise with the data as `promiseValue`
[myContract.methods.myMethod([parameters).call(options,[callback])](https://web3js.readthedocs.io/en/v1.2.4/web3-eth-contract.html#methods-mymethod-call) | 2019/12/25 | [
"https://Stackoverflow.com/questions/59482652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9108471/"
] | ```html
<form action="{{ route('accounts.update', $user->id) }}" method="post">
@csrf
@method('PUT')
<div class="form-group row">
<label for="balance" class="col-md-4 col-form-label text-md-right">{{ __('Enter Client\'s Balance :') }}</label>
<div class="col-md-6">
<input id="balance" type="text" class="form-control @error('balance') is-invalid @enderror" name="balance" value="" autocomplete="balance" autofocus>
</div>
</div>
<div class="form-group row">
<label for="amount" class="col-md-4 col-form-label text-md-right">{{ __('Enter Client\'s Amount:') }}</label>
<div class="col-md-6">
<input id="amount" type="text" class="form-control @error('amt') is-invalid @enderror" name="amt" value="
" required autocomplete="amt" autofocus>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer text-center">
<button type="submit" class="btn btn-primary">Update Account</button>
</div>
</form>
``` | I think you should remove **name="\_method"** attribute from your **form** tag because it's reserved by laravel for hidden inputs
example :
```
<input type="hidden" name="_method" value="PUT"> // same as @method('PUT')
```
see : <https://laravel.com/docs/5.7/routing#form-method-spoofing> |
59,482,652 | I have the following js code structure;
```
Promise_1.then(function(){
for(){
Promise2.then(function(){
...
})
}
}).then(
Promise_3.then(function(){
for(){
Promise4.then(function(){
...
})
}
})
).then(
function(){
// SOME CODE
}
)
```
I want to execute SOME CODE after the above promises are resolved. But the SOME CODE is executing before the above promises are resolved. I know I can enclose SOME CODE in `setTimeout()` which will solve the problem as suggested by other answers on SO but I think it's not a good idea. The actual code on which I am working is as follow;
```
user_xp = 0
connections_blocks.methods.get_deposit_blocks(current_email).call({
from: new_web3.eth.Contract.defaultAccount
}, function (err, result) {
deposit_blocks = result
console.log(deposit_blocks)
deposit_blocks = deposit_blocks.split(",")
deposit_blocks.splice(0, 1)
for (i_ in deposit_blocks) {
console.log(deposit_blocks[i_])
user_xp + new_web3.eth.getBlock(deposit_blocks[i_]).then(function (deposit_block) {
user_xp = user_xp + deposit_block.gasUsed
console.log(user_xp)
})
}
}).then(
connections_blocks.methods.get_send_blocks(current_email).call({
from: new_web3.eth.Contract.defaultAccount
}, function (err, result) {
send_blocks = result
console.log(send_blocks)
send_blocks = send_blocks.split(",")
send_blocks.splice(0, 1)
for (i_ = 0; i_ < send_blocks.length; i_ = i_ + 2) {
console.log(send_blocks[i_])
user_xp + new_web3.eth.getBlock(send_blocks[i_]).then(function (send_block) {
user_xp = user_xp + send_block.gasUsed
console.log(user_xp)
})
}
})).then(
setTimeout(function () {
console.log(user_xp)
xp = document.getElementById('xp')
xp.innerHTML = "XP:" + user_xp
},1000)
)
```
In the above code, I am just using `setTimeout()` which is solving my problem. But I want the code to execute automatically only when the above promises are resolved. Is there any easy way to do that in JS w/o putting promises in functions and making it more complex.
**UPDATE**
I am using the following web3's function to fetch data from the solidity's smart contract which actually returns a promise with the data as `promiseValue`
[myContract.methods.myMethod([parameters).call(options,[callback])](https://web3js.readthedocs.io/en/v1.2.4/web3-eth-contract.html#methods-mymethod-call) | 2019/12/25 | [
"https://Stackoverflow.com/questions/59482652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9108471/"
] | ```html
<form action="{{ route('accounts.update', $user->id) }}" method="post">
@csrf
@method('PUT')
<div class="form-group row">
<label for="balance" class="col-md-4 col-form-label text-md-right">{{ __('Enter Client\'s Balance :') }}</label>
<div class="col-md-6">
<input id="balance" type="text" class="form-control @error('balance') is-invalid @enderror" name="balance" value="" autocomplete="balance" autofocus>
</div>
</div>
<div class="form-group row">
<label for="amount" class="col-md-4 col-form-label text-md-right">{{ __('Enter Client\'s Amount:') }}</label>
<div class="col-md-6">
<input id="amount" type="text" class="form-control @error('amt') is-invalid @enderror" name="amt" value="
" required autocomplete="amt" autofocus>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer text-center">
<button type="submit" class="btn btn-primary">Update Account</button>
</div>
</form>
``` | HTML form is not supporting PUT/PATCH method. So when you want to perform PUT/PATCH action using HTML form in Laravel, you have to add `@method('put')` and set form method as `method="post"`. So you can change your code as:
```
<form action="{{ route('accounts.update', $user->id) }}" method="post">
@csrf
@method('PUT')
....
</form>
``` |
67,260,014 | I've been reading F# articles and they use single case variants to create distinct incompatible types. However in Ocaml I can use private module types or abstract types to create distinct types. Is it common in Ocaml to use single case variants like in F# or Haskell? | 2021/04/26 | [
"https://Stackoverflow.com/questions/67260014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118651/"
] | For what it's worth it seems to me this wasn't particularly common in OCaml in the past.
I've been reluctant to do this myself because it has always cost something: the representation of `type t = T of int` was always bigger than just the representation of an int.
However recently (probably a few years) it's possible to declare types as unboxed, which removes this obstacle:
```
type [@unboxed] t = T of int
```
As a result I've personally been using single-constructor types much more frequently recently. There are many advantages. For me the main one is that I can have a distinct type that's independent of whether it's representation happens to be the same as another type.
You can of course use modules to get this effect, as you say. But that is a fairly heavy solution.
(All of this is just my opinion naturally.) | Yet another case for single-constructor types (although it does not quite match your initial question of creating distinct types): fancy records. (By contrast with other answers, this is more a syntactic convenience than a fundamental feature.)
Indeed, using a [relatively recent feature](https://www.ocaml.org/releases/4.12/htmlman/inlinerecords.html) (introduced with OCaml 4.03, in 2016) which allows writing constructor arguments with a record syntax (including mutable fields!), you can prefix regular records with a constructor name, Coq-style.
```ml
type t = MakeT of {
mutable x : int ;
mutable y : string ;
}
let some_t = MakeT { x = 4 ; y = "tea" }
(* val some_t : t = MakeT {x = 4; y = "tea"} *)
```
It does not change anything at runtime (just like `Constr (a,b)` has the same representation as `(a,b)`, provided `Constr` is the only constructor of its type). The constructor makes the code a bit more explicit to the human eye, and it also provides the type information required to disambiguate field names, thus avoiding the need for type annotations. It is similar in function to the usual module trick, but more systematic.
Patterns work just the same:
```ml
let (MakeT { x ; y }) = some_t
(* val x : int = 4 *)
(* val y : string = "tea" *)
```
You can also access the “contained” record (at no runtime cost), read and modify its fields. This contained record however is not a first-class value: you cannot store it, pass it to a function nor return it.
```ml
let (MakeT fields) = some_t in fields.x (* returns 4 *)
let (MakeT fields) = some_t in fields.x <- 42
(* some_t is now MakeT {x = 42; y = "tea"} *)
let (MakeT fields) = some_t in fields
(* ^^^^^^
Error: This form is not allowed as the type of the inlined record could escape. *)
``` |
67,260,014 | I've been reading F# articles and they use single case variants to create distinct incompatible types. However in Ocaml I can use private module types or abstract types to create distinct types. Is it common in Ocaml to use single case variants like in F# or Haskell? | 2021/04/26 | [
"https://Stackoverflow.com/questions/67260014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118651/"
] | For what it's worth it seems to me this wasn't particularly common in OCaml in the past.
I've been reluctant to do this myself because it has always cost something: the representation of `type t = T of int` was always bigger than just the representation of an int.
However recently (probably a few years) it's possible to declare types as unboxed, which removes this obstacle:
```
type [@unboxed] t = T of int
```
As a result I've personally been using single-constructor types much more frequently recently. There are many advantages. For me the main one is that I can have a distinct type that's independent of whether it's representation happens to be the same as another type.
You can of course use modules to get this effect, as you say. But that is a fairly heavy solution.
(All of this is just my opinion naturally.) | Another use case of single-constructor (polymorphic) variants is documenting something to the caller of a function. For instance, perhaps there's a caveat with the value that your function returns:
```
val create : unit -> [ `Must_call_close of t ]
```
Using a variant forces the caller of your function to pattern-match on this variant in their code:
```
let (`Must_call_close t) = create () in (* ... *)
```
This makes it more likely that they'll pay attention to the message in the variant, as opposed to documentation in an .mli file that could get missed.
For this use case, polymorphic variants are a bit easier to work with as you don't need to define an intermediate type for the variant. |
67,260,014 | I've been reading F# articles and they use single case variants to create distinct incompatible types. However in Ocaml I can use private module types or abstract types to create distinct types. Is it common in Ocaml to use single case variants like in F# or Haskell? | 2021/04/26 | [
"https://Stackoverflow.com/questions/67260014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118651/"
] | Another specialized use case fo a single constructor variant is to erase some type information with a GADT (and an existential quantification).
For instance, in
```ml
type showable = Show: 'a * ('a -> string) -> showable
let show (Show (x,f)) = f x
let showables = [ Show (0,string_of_int); Show("string", Fun.id) ]
```
The constructor `Show` pairs an element of a given type with a printing function, then forget the concrete type of the element. This makes it possible to have a list of `showable` elements, even if each elements had a different concrete types. | Yet another case for single-constructor types (although it does not quite match your initial question of creating distinct types): fancy records. (By contrast with other answers, this is more a syntactic convenience than a fundamental feature.)
Indeed, using a [relatively recent feature](https://www.ocaml.org/releases/4.12/htmlman/inlinerecords.html) (introduced with OCaml 4.03, in 2016) which allows writing constructor arguments with a record syntax (including mutable fields!), you can prefix regular records with a constructor name, Coq-style.
```ml
type t = MakeT of {
mutable x : int ;
mutable y : string ;
}
let some_t = MakeT { x = 4 ; y = "tea" }
(* val some_t : t = MakeT {x = 4; y = "tea"} *)
```
It does not change anything at runtime (just like `Constr (a,b)` has the same representation as `(a,b)`, provided `Constr` is the only constructor of its type). The constructor makes the code a bit more explicit to the human eye, and it also provides the type information required to disambiguate field names, thus avoiding the need for type annotations. It is similar in function to the usual module trick, but more systematic.
Patterns work just the same:
```ml
let (MakeT { x ; y }) = some_t
(* val x : int = 4 *)
(* val y : string = "tea" *)
```
You can also access the “contained” record (at no runtime cost), read and modify its fields. This contained record however is not a first-class value: you cannot store it, pass it to a function nor return it.
```ml
let (MakeT fields) = some_t in fields.x (* returns 4 *)
let (MakeT fields) = some_t in fields.x <- 42
(* some_t is now MakeT {x = 42; y = "tea"} *)
let (MakeT fields) = some_t in fields
(* ^^^^^^
Error: This form is not allowed as the type of the inlined record could escape. *)
``` |
67,260,014 | I've been reading F# articles and they use single case variants to create distinct incompatible types. However in Ocaml I can use private module types or abstract types to create distinct types. Is it common in Ocaml to use single case variants like in F# or Haskell? | 2021/04/26 | [
"https://Stackoverflow.com/questions/67260014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118651/"
] | Another specialized use case fo a single constructor variant is to erase some type information with a GADT (and an existential quantification).
For instance, in
```ml
type showable = Show: 'a * ('a -> string) -> showable
let show (Show (x,f)) = f x
let showables = [ Show (0,string_of_int); Show("string", Fun.id) ]
```
The constructor `Show` pairs an element of a given type with a printing function, then forget the concrete type of the element. This makes it possible to have a list of `showable` elements, even if each elements had a different concrete types. | Another use case of single-constructor (polymorphic) variants is documenting something to the caller of a function. For instance, perhaps there's a caveat with the value that your function returns:
```
val create : unit -> [ `Must_call_close of t ]
```
Using a variant forces the caller of your function to pattern-match on this variant in their code:
```
let (`Must_call_close t) = create () in (* ... *)
```
This makes it more likely that they'll pay attention to the message in the variant, as opposed to documentation in an .mli file that could get missed.
For this use case, polymorphic variants are a bit easier to work with as you don't need to define an intermediate type for the variant. |
67,260,014 | I've been reading F# articles and they use single case variants to create distinct incompatible types. However in Ocaml I can use private module types or abstract types to create distinct types. Is it common in Ocaml to use single case variants like in F# or Haskell? | 2021/04/26 | [
"https://Stackoverflow.com/questions/67260014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118651/"
] | Yet another case for single-constructor types (although it does not quite match your initial question of creating distinct types): fancy records. (By contrast with other answers, this is more a syntactic convenience than a fundamental feature.)
Indeed, using a [relatively recent feature](https://www.ocaml.org/releases/4.12/htmlman/inlinerecords.html) (introduced with OCaml 4.03, in 2016) which allows writing constructor arguments with a record syntax (including mutable fields!), you can prefix regular records with a constructor name, Coq-style.
```ml
type t = MakeT of {
mutable x : int ;
mutable y : string ;
}
let some_t = MakeT { x = 4 ; y = "tea" }
(* val some_t : t = MakeT {x = 4; y = "tea"} *)
```
It does not change anything at runtime (just like `Constr (a,b)` has the same representation as `(a,b)`, provided `Constr` is the only constructor of its type). The constructor makes the code a bit more explicit to the human eye, and it also provides the type information required to disambiguate field names, thus avoiding the need for type annotations. It is similar in function to the usual module trick, but more systematic.
Patterns work just the same:
```ml
let (MakeT { x ; y }) = some_t
(* val x : int = 4 *)
(* val y : string = "tea" *)
```
You can also access the “contained” record (at no runtime cost), read and modify its fields. This contained record however is not a first-class value: you cannot store it, pass it to a function nor return it.
```ml
let (MakeT fields) = some_t in fields.x (* returns 4 *)
let (MakeT fields) = some_t in fields.x <- 42
(* some_t is now MakeT {x = 42; y = "tea"} *)
let (MakeT fields) = some_t in fields
(* ^^^^^^
Error: This form is not allowed as the type of the inlined record could escape. *)
``` | Another use case of single-constructor (polymorphic) variants is documenting something to the caller of a function. For instance, perhaps there's a caveat with the value that your function returns:
```
val create : unit -> [ `Must_call_close of t ]
```
Using a variant forces the caller of your function to pattern-match on this variant in their code:
```
let (`Must_call_close t) = create () in (* ... *)
```
This makes it more likely that they'll pay attention to the message in the variant, as opposed to documentation in an .mli file that could get missed.
For this use case, polymorphic variants are a bit easier to work with as you don't need to define an intermediate type for the variant. |
32,393,748 | I have a SQL Server table like this
```
ProdID Code
-------- ------
1001 A
2001 B
1001 C
3001 D
3001 E
1001 F
1001 Z
2001 G
2001 H
3001 I
4001 J
```
I am expecting output as
```
ProdID Code
-------- ------
1001 Z
1001 F
2001 H
2001 G
3001 I
3001 E
```
Only to show latest 2 data. If any id has less than 2 data I don't want to show it (like `ProdID 4001`). | 2015/09/04 | [
"https://Stackoverflow.com/questions/32393748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Try this
```
;With cte As
(Select ProdID, Code, Row_Number() Over(Partition By ProdID Order By Code Desc) As rn,
Count(*) Over(Partition By ProdID) As NbrRows
From mytable)
Select ProdID, Code
From cte
Where rn <= 2 And NbrRows > 1
Order By ProdID, Code desc;
```
**`[sql fiddle demo](http://sqlfiddle.com/#!6/9ee7f/1)`** | Using `ROW_NUMBER` and `COUNT`:
[**SQL Fiddle**](http://sqlfiddle.com/#!3/152f7/1/0)
```
;WITH cte AS(
SELECT *,
rn = ROW_NUMBER() OVER(PARTITION BY ProdID ORDER BY Code DESC),
cnt = COUNT(*) OVER(PARTITION BY ProdID)
FROM tbl
)
SELECT
ProdID, Code
FROM cte
WHERE
rn <= 2
AND cnt >= 2
``` |
33,628,183 | I want to do the following:
```
button.setBackgroundResource(R.layout.caracbout);
```
But this function only works like this:
```
button.setBackgroundResource(R.drawable.xxxx);
```
my button is
```
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".6"
android:background="@layout/boutcarac"
android:textColor="#000000"
android:text="Refresh"
android:clickable="true"
android:onClick="refreshfiche"/>
```
and my layout caracbout xml is like
```
<item android:state_pressed="true" >
<shape android:shape="rectangle" >
<corners android:radius="5dip"/>
<stroke
android:width="1dip"
android:color="#000000" />
<gradient
android:angle="-90"
android:startColor="#0000"
android:endColor="#fff5d6" />
</shape>
</item>
<item style="@style/typocarac">
<shape android:shape="rectangle" >
<corners android:radius="5dip"/>
<stroke
android:width="1dip"
android:color="#fff5d6" />
<gradient
android:angle="-90"
android:startColor="#fff5d6"
android:endColor="#0000" />
</shape>
</item>
```
and I must change the item android:state\_pressed="true", so I want to create a xml caracbout2 and set it in the java. But I dont know how can I do that.
Thanks! | 2015/11/10 | [
"https://Stackoverflow.com/questions/33628183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5546215/"
] | You can set the background like this,
```
Button btn = (Button) findViewById(R.id.btn);
btn.setBackgroundResource(R.drawable.ic_launcher);
``` | Layouts are not background images. They contain the information which is necessary to draw application views/screens. To draw a button with custom background you can use drawable resource file.
<http://developer.android.com/guide/topics/resources/drawable-resource.html> |
33,628,183 | I want to do the following:
```
button.setBackgroundResource(R.layout.caracbout);
```
But this function only works like this:
```
button.setBackgroundResource(R.drawable.xxxx);
```
my button is
```
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".6"
android:background="@layout/boutcarac"
android:textColor="#000000"
android:text="Refresh"
android:clickable="true"
android:onClick="refreshfiche"/>
```
and my layout caracbout xml is like
```
<item android:state_pressed="true" >
<shape android:shape="rectangle" >
<corners android:radius="5dip"/>
<stroke
android:width="1dip"
android:color="#000000" />
<gradient
android:angle="-90"
android:startColor="#0000"
android:endColor="#fff5d6" />
</shape>
</item>
<item style="@style/typocarac">
<shape android:shape="rectangle" >
<corners android:radius="5dip"/>
<stroke
android:width="1dip"
android:color="#fff5d6" />
<gradient
android:angle="-90"
android:startColor="#fff5d6"
android:endColor="#0000" />
</shape>
</item>
```
and I must change the item android:state\_pressed="true", so I want to create a xml caracbout2 and set it in the java. But I dont know how can I do that.
Thanks! | 2015/11/10 | [
"https://Stackoverflow.com/questions/33628183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5546215/"
] | create your caracbout2 xml file in directory drawable and use R.drawable.caracbout2 in java
you can learn from [this](http://developer.android.com/intl/zh-cn/guide/topics/resources/drawable-resource.html) for drawable resource. | Layouts are not background images. They contain the information which is necessary to draw application views/screens. To draw a button with custom background you can use drawable resource file.
<http://developer.android.com/guide/topics/resources/drawable-resource.html> |
2,156,505 | When it's $\frac z{z-1}$ the answer in the discrete domain can be found in the general tables = $u[n]$, but for $\frac z{z+1}$ I can't find the rule. Some examples say it's $(−1)^nu[n] $ or $a^k\cos(k\pi)$, which one is it and why? | 2017/02/22 | [
"https://math.stackexchange.com/questions/2156505",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/299075/"
] | To be well defined, the $z$ transform must include the ROC (radius of convergence). You can see that in this example.
You can write:
$$\frac{z}{z+1}=\frac{1}{1+z^{-1}}=\sum\_{n=0}^{\infty}(-z^{-1})^n \tag{1}$$
which is the $Z$ transform of $(−1)^nu[n]$
but also you can write
$$\frac{z}{z+1}=z \frac{1}{1+z}=z \sum\_{m=0}^{\infty}(-z)^m = \sum\_{m=0}^{\infty} (-1)^m z^{m+1} \tag{2}$$
which, setting $n=-(m+1)$ gives
$$\sum\_{n=-\infty}^{-1} (-1)^{n+1} z^{-n}$$
which is is $Z$ transform of $(-1)^{n+1}u(-n+1)$
So which one is the correct inverse transform? It depends on the ROC. Eq $(1)$ only converges when $|z^{-1}|<1$ or $|z|>1$ (outside the unit circle), while eq $(2)$ only converges for $|z|<1$
Hence, to do the anti-transform it's not enough to have the $Z$ transform as a mere formula, you need to have also the ROC. Or at least the data of the original sequence being causal or anticausal. | $$\frac{z}{z+1}=\frac{1}{1-(-z^{-1})}=\sum\_{n=0}^{\infty}(-z^{-1})^n=\sum\_{n=0}^{\infty}(-1)^nz^{-n}=\mathcal{Z}\{(-1)^nu[n]\},\quad |z|>1$$ |
1,640,512 | I have a Fritzbox 7490. I set the IPv4 DNS Server to OpenDNS (208.67.222.222 and 208.67.220.220), but somehow these server are not used when I make requests.
How I noticed it:
There is a Domain that is being blocked by my ISP (it's s.to, but I don't know what is on there I just used it for my test scenario because I know this site is blocked). My ISP forwards one to 167.233.14.14 aka notice.cuii.info.
When use nslookup it will show me the IP from that filtered list of my provider
```bsh
~$ nslookup s.to
Server: 127.0.0.53
Address: 127.0.0.53#53
Non-authoritative answer:
s.to canonical name = notice.cuii.info.
Name: notice.cuii.info
Address: 167.233.14.14
```
The DNS I use seems to work fine:
```bsh
~$ nslookup s.to 208.67.222.222
Server: 208.67.222.222
Address: 208.67.222.222#53
Non-authoritative answer:
Name: s.to
Address: 186.2.163.237
~$ nslookup s.to 208.67.220.220
Server: 208.67.220.220
Address: 208.67.220.220#53
Non-authoritative answer:
Name: s.to
Address: 186.2.163.237
```
In my browser I also get forwarded to the wrong IP.
I configured the DNS some month ago. There already have been one or two router restarts. The router wasn't sold by this ISP. I got it from my previous ISP (which won't forward to cuii.info), but I had to switch the ISP because I moved to another place.
Anyone an idea why I don't get the correct IP by default?
PS: There is no DNS configured on my PC settings, browser and phone. But all of them go to the wrong IP.
PPS: I'm not trying to get around the law and do bad stuff on the web. The provider just blocks these sites without a judicial order. That's what bothers me. | 2021/04/09 | [
"https://superuser.com/questions/1640512",
"https://superuser.com",
"https://superuser.com/users/1055592/"
] | Wireless networks are considered to be an increased risk over wired networks by some. Previous wireless security protocols (e.g. [WEP](https://en.wikipedia.org/wiki/Wired_Equivalent_Privacy#Weak_security), [WPA1/ WPA2](https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access#Security_issues)) have shown to contain serious security flaws at some point, which allowed unauthorized access. Other argue that WiFi networks can be made safe with best practices, like a fully updated access point, correctly configured (WPA2/AES,no WPS, CRACK patched) and strong passwords matching or exceeding 16 characters.
The issue is compounded by the fact that many networks are often long lived with devices that are not updated. Some had flaws in underlying protocol (WEP) which would not be fixed.
Another issue is that these attacks can be performed remotely, off-premise and are hard to track down (e.g. WPA1/2 offline cracking, should be fixed in WPA3). Wired connections on the other hand require physical access to the the equipment to compromise.
>
> ... not considered secure despite the presence of some safeguards such as encryption, reliability, SSID, use VPN, and integrity?
>
>
>
Wireless networks are very handy and their use should be continued. But wireless networks have been shown to be easily compromised in the past and should be treated with appropriate security measures, like network isolation, strong resource authentication and possibly VPNs. Large big budget environments continue to use WiFi, but it is [recommended](https://us-cert.cisa.gov/ncas/tips/ST18-247) to isolate the WiFi network from the rest of the network to minimize risk. | The most common type of wireless security is Wi-Fi security which is not considered secure in Windows 10 despite the presence of some safeguards such as encryption, reliability, SSID, use VPN, and integrity. This is because:
1. It uses an older security standard. For example, this can occur if you connect to a Wi-Fi network that uses WEP or TKIP for security. These security standards are older and have known flaws. To fix this issue, see [Wi-Fi network not secure in Windows 10](https://support.microsoft.com/en-us/windows/wi-fi-network-not-secure-in-windows-10-9170b675-921b-3aa5-7e43-fcb2059d159c)
Read more about [wireless security](https://en.wikipedia.org/wiki/Wireless_security) and consider upvoting. thanks! |
112,306 | * I'm running OS X 10.9 with Server 3.0.1 on a Mac residing on a private subnet sitting behind a router whose WAN port is plugged into a cable modem, hence the ISP is a well known cable internet service provider.
* This server has its DNS correctly configured (i.e., the result of "sudo changeip -checkhostname" on the server via command line yields perfect results).
* This server is running an Open Directory Master.
* Dynamic DNS is correctly configured for the router, and resolves the public IP address assigned by my ISP to the same domain name as the server (I forward any required ports for services I run).
* This server also has installed a server certificate signed by a trusted CA (i.e., Go Daddy) and is working perfectly for all OS X Server services including Open Directory.
* This server also has the Mail service configured (SMTP and IMAP) with no problems (I can send and receive mail to/from the server.
* This server server also has push notifications enabled and has a push notification certificate installed perfectly (obtained from Apple's push notification certificate portal, just renewed a few days ago).
* I have some iOS devices running iOS 7.0.4. I have configured Mail on these iOS devices to send and receive mail to/from the aforementioned server for a few different user accounts on the server. This works fine (tested, can send and receive mail no problems).
* The aforementioned iOS devices mail settings for the aforementioned server have been configured to receive push notifications when mail is received to said user accounts on the server.
With all of that said, the iOS devices are **sometimes** able to receive push notifications from the [Apple Push Notification Service](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html) (APNS "cloud") in situations when the iOS devices reside on the same private subnet as the Mac server (via Wi-Fi), and when they reside on the public Internet (via cellular data networks or public Wi-Fi networks such as coffee shops).
Thus, push notifications **do** work when mail messages on the server are received, but not always. After a period of time has elapsed on the server whereby no email messages have been received (seems to be several hours but I haven't yet been able to pinpoint it precisely), the server apparently loses what is supposed to be a **persistent** connection with the APNS gateway. OS X Server unfortunately does not log when this connection is lost. Then, when a new email message finally arrives again after several hours and is received by the server, the iOS devices do **not** receive their expected push notifications and instead OS X Server consistently logs an error message like this one (the only differences being of course the process ID and time/date stamp):
```
11/26/13 5:48:11.762 AM push_notify[181]: stream: received error: The operation couldn’t be completed. Connection reset by peer on: incoming stream: APN to host: gateway.push.apple.com:2195
```
Once the above error type is recorded in the logs, a subsequent email message sent to the server successfully generates a push notification message on the configured iOS devices so long as the subsequent message is sent before minimal time has elapsed (i.e., several hours). I do not port forward ports 2195 or 2196 from the router to the Mac server because Apple's [support document](http://support.apple.com/kb/TS4264) implies these ports are for outgoing traffic (from the server to the APNS gateway) unless I've misunderstood.
An excerpt in Apple's Mac Developer Library Technical Note TN2265 caught my attention with respect to **idle**:
>
> An occasional disconnect while your provider is idle is nothing to be
> concerned about; just re-establish the connection and carry on. If one
> of the push servers is down, the load balancing mechanism will
> transparently direct your new connection to another server assuming
> you connect by hostname and not by static IP address.
>
>
>
Is OS X Server (the "provider" in this context) essentially just "carrying on" by "re-establishing" the connection to APNS after being "idle" for several hours as noted in the logs per the stream error aformentioned?
Someone I spoke with about this posited the above problems may be due to the router's WAN port not being assigned a static IP address by my ISP, but of all the Apple developer documentation and support docs I've looked at about push notifications with OS X Server do not state a static IP address is required.
note: I have also tested this with the same hardware and settings but running OS X 10.8.5 Mountain Lion with Server app 2.2.1 with essentially the same results but IMHO better log verbosity, as in:
```
11/29/13 11:16:55.713 PM push_notify[11951]: stream: received error: The operation couldn’t be completed. Connection reset by peer on: incoming stream: APN to host: gateway.push.apple.com:2195
11/29/13 11:16:55.722 PM push_notify[11951]: Disconnected from apn server gateway.push.apple.com for topic com.apple.mail.XServer.2a132c32-dda4-45a1-68e1-b3cca3865c12: error Connection reset by peer
11/29/13 11:16:55.722 PM push_notify[11951]: will attempt to reconnect stream APN to host gateway.push.apple.com:2195 in 15 seconds
```
Any help or suggestions resolving this would be greatly appreciated, it may be something simple I've overlooked. | 2013/11/30 | [
"https://apple.stackexchange.com/questions/112306",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/63748/"
] | This problem was been resolved. The ASUS "Dark Knight" router which was providing the private LAN (NAT) and port forwarding to the Mac running OS X Server has a firmware bug. The bug manifest by DROPPING the ESTABLISHED TCP connection on port 2195 between the Mac running OS X Server and APNS, after two hours of quiescence. The router should not have dropped this connection, there was no firewall rule instructing it to do so. The lesson learned is to be much more selective and wise with regard to choosing routers (especially consumer off-the-shelf variety) for use with servers even for servers run in a small business context (like a Mac Mini Server).
Heading
======= | My first steps in diagnosis would be to forward both those ports and see what happens (I might even put the machine into a DMZ for a couple of hours).
I'd then put a packet sniffer on the 17.0.0.0/8 address block and see what traffic on what ports is going across the net when it does work and when it doesn't. |
112,306 | * I'm running OS X 10.9 with Server 3.0.1 on a Mac residing on a private subnet sitting behind a router whose WAN port is plugged into a cable modem, hence the ISP is a well known cable internet service provider.
* This server has its DNS correctly configured (i.e., the result of "sudo changeip -checkhostname" on the server via command line yields perfect results).
* This server is running an Open Directory Master.
* Dynamic DNS is correctly configured for the router, and resolves the public IP address assigned by my ISP to the same domain name as the server (I forward any required ports for services I run).
* This server also has installed a server certificate signed by a trusted CA (i.e., Go Daddy) and is working perfectly for all OS X Server services including Open Directory.
* This server also has the Mail service configured (SMTP and IMAP) with no problems (I can send and receive mail to/from the server.
* This server server also has push notifications enabled and has a push notification certificate installed perfectly (obtained from Apple's push notification certificate portal, just renewed a few days ago).
* I have some iOS devices running iOS 7.0.4. I have configured Mail on these iOS devices to send and receive mail to/from the aforementioned server for a few different user accounts on the server. This works fine (tested, can send and receive mail no problems).
* The aforementioned iOS devices mail settings for the aforementioned server have been configured to receive push notifications when mail is received to said user accounts on the server.
With all of that said, the iOS devices are **sometimes** able to receive push notifications from the [Apple Push Notification Service](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html) (APNS "cloud") in situations when the iOS devices reside on the same private subnet as the Mac server (via Wi-Fi), and when they reside on the public Internet (via cellular data networks or public Wi-Fi networks such as coffee shops).
Thus, push notifications **do** work when mail messages on the server are received, but not always. After a period of time has elapsed on the server whereby no email messages have been received (seems to be several hours but I haven't yet been able to pinpoint it precisely), the server apparently loses what is supposed to be a **persistent** connection with the APNS gateway. OS X Server unfortunately does not log when this connection is lost. Then, when a new email message finally arrives again after several hours and is received by the server, the iOS devices do **not** receive their expected push notifications and instead OS X Server consistently logs an error message like this one (the only differences being of course the process ID and time/date stamp):
```
11/26/13 5:48:11.762 AM push_notify[181]: stream: received error: The operation couldn’t be completed. Connection reset by peer on: incoming stream: APN to host: gateway.push.apple.com:2195
```
Once the above error type is recorded in the logs, a subsequent email message sent to the server successfully generates a push notification message on the configured iOS devices so long as the subsequent message is sent before minimal time has elapsed (i.e., several hours). I do not port forward ports 2195 or 2196 from the router to the Mac server because Apple's [support document](http://support.apple.com/kb/TS4264) implies these ports are for outgoing traffic (from the server to the APNS gateway) unless I've misunderstood.
An excerpt in Apple's Mac Developer Library Technical Note TN2265 caught my attention with respect to **idle**:
>
> An occasional disconnect while your provider is idle is nothing to be
> concerned about; just re-establish the connection and carry on. If one
> of the push servers is down, the load balancing mechanism will
> transparently direct your new connection to another server assuming
> you connect by hostname and not by static IP address.
>
>
>
Is OS X Server (the "provider" in this context) essentially just "carrying on" by "re-establishing" the connection to APNS after being "idle" for several hours as noted in the logs per the stream error aformentioned?
Someone I spoke with about this posited the above problems may be due to the router's WAN port not being assigned a static IP address by my ISP, but of all the Apple developer documentation and support docs I've looked at about push notifications with OS X Server do not state a static IP address is required.
note: I have also tested this with the same hardware and settings but running OS X 10.8.5 Mountain Lion with Server app 2.2.1 with essentially the same results but IMHO better log verbosity, as in:
```
11/29/13 11:16:55.713 PM push_notify[11951]: stream: received error: The operation couldn’t be completed. Connection reset by peer on: incoming stream: APN to host: gateway.push.apple.com:2195
11/29/13 11:16:55.722 PM push_notify[11951]: Disconnected from apn server gateway.push.apple.com for topic com.apple.mail.XServer.2a132c32-dda4-45a1-68e1-b3cca3865c12: error Connection reset by peer
11/29/13 11:16:55.722 PM push_notify[11951]: will attempt to reconnect stream APN to host gateway.push.apple.com:2195 in 15 seconds
```
Any help or suggestions resolving this would be greatly appreciated, it may be something simple I've overlooked. | 2013/11/30 | [
"https://apple.stackexchange.com/questions/112306",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/63748/"
] | We originally filed a bug report regarding this problem with Apple (at the time we weren't deterministically certain it was a bug, but considering the efforts we made to resolve this with Apple Enterprise support, it seemed probabilistically to be a bug). Recently Apple engineering responded to us stating they have attempted to fix this bug in Server app version 4. Server 4 requires to be run on OS X 10.10 Yosemite. We have tested with Server 4.0.3 running on OS X 10.10.2 Yosemite with two iPhones each running iOS 8.1.3 and our router remains a Ubiquiti EdgeRouter (with no changes to the router configuration). For earlier versions of Server, assuming this bug remains unfixed in those versions, the workaround offered by Josh may be your best best. | My first steps in diagnosis would be to forward both those ports and see what happens (I might even put the machine into a DMZ for a couple of hours).
I'd then put a packet sniffer on the 17.0.0.0/8 address block and see what traffic on what ports is going across the net when it does work and when it doesn't. |
112,306 | * I'm running OS X 10.9 with Server 3.0.1 on a Mac residing on a private subnet sitting behind a router whose WAN port is plugged into a cable modem, hence the ISP is a well known cable internet service provider.
* This server has its DNS correctly configured (i.e., the result of "sudo changeip -checkhostname" on the server via command line yields perfect results).
* This server is running an Open Directory Master.
* Dynamic DNS is correctly configured for the router, and resolves the public IP address assigned by my ISP to the same domain name as the server (I forward any required ports for services I run).
* This server also has installed a server certificate signed by a trusted CA (i.e., Go Daddy) and is working perfectly for all OS X Server services including Open Directory.
* This server also has the Mail service configured (SMTP and IMAP) with no problems (I can send and receive mail to/from the server.
* This server server also has push notifications enabled and has a push notification certificate installed perfectly (obtained from Apple's push notification certificate portal, just renewed a few days ago).
* I have some iOS devices running iOS 7.0.4. I have configured Mail on these iOS devices to send and receive mail to/from the aforementioned server for a few different user accounts on the server. This works fine (tested, can send and receive mail no problems).
* The aforementioned iOS devices mail settings for the aforementioned server have been configured to receive push notifications when mail is received to said user accounts on the server.
With all of that said, the iOS devices are **sometimes** able to receive push notifications from the [Apple Push Notification Service](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html) (APNS "cloud") in situations when the iOS devices reside on the same private subnet as the Mac server (via Wi-Fi), and when they reside on the public Internet (via cellular data networks or public Wi-Fi networks such as coffee shops).
Thus, push notifications **do** work when mail messages on the server are received, but not always. After a period of time has elapsed on the server whereby no email messages have been received (seems to be several hours but I haven't yet been able to pinpoint it precisely), the server apparently loses what is supposed to be a **persistent** connection with the APNS gateway. OS X Server unfortunately does not log when this connection is lost. Then, when a new email message finally arrives again after several hours and is received by the server, the iOS devices do **not** receive their expected push notifications and instead OS X Server consistently logs an error message like this one (the only differences being of course the process ID and time/date stamp):
```
11/26/13 5:48:11.762 AM push_notify[181]: stream: received error: The operation couldn’t be completed. Connection reset by peer on: incoming stream: APN to host: gateway.push.apple.com:2195
```
Once the above error type is recorded in the logs, a subsequent email message sent to the server successfully generates a push notification message on the configured iOS devices so long as the subsequent message is sent before minimal time has elapsed (i.e., several hours). I do not port forward ports 2195 or 2196 from the router to the Mac server because Apple's [support document](http://support.apple.com/kb/TS4264) implies these ports are for outgoing traffic (from the server to the APNS gateway) unless I've misunderstood.
An excerpt in Apple's Mac Developer Library Technical Note TN2265 caught my attention with respect to **idle**:
>
> An occasional disconnect while your provider is idle is nothing to be
> concerned about; just re-establish the connection and carry on. If one
> of the push servers is down, the load balancing mechanism will
> transparently direct your new connection to another server assuming
> you connect by hostname and not by static IP address.
>
>
>
Is OS X Server (the "provider" in this context) essentially just "carrying on" by "re-establishing" the connection to APNS after being "idle" for several hours as noted in the logs per the stream error aformentioned?
Someone I spoke with about this posited the above problems may be due to the router's WAN port not being assigned a static IP address by my ISP, but of all the Apple developer documentation and support docs I've looked at about push notifications with OS X Server do not state a static IP address is required.
note: I have also tested this with the same hardware and settings but running OS X 10.8.5 Mountain Lion with Server app 2.2.1 with essentially the same results but IMHO better log verbosity, as in:
```
11/29/13 11:16:55.713 PM push_notify[11951]: stream: received error: The operation couldn’t be completed. Connection reset by peer on: incoming stream: APN to host: gateway.push.apple.com:2195
11/29/13 11:16:55.722 PM push_notify[11951]: Disconnected from apn server gateway.push.apple.com for topic com.apple.mail.XServer.2a132c32-dda4-45a1-68e1-b3cca3865c12: error Connection reset by peer
11/29/13 11:16:55.722 PM push_notify[11951]: will attempt to reconnect stream APN to host gateway.push.apple.com:2195 in 15 seconds
```
Any help or suggestions resolving this would be greatly appreciated, it may be something simple I've overlooked. | 2013/11/30 | [
"https://apple.stackexchange.com/questions/112306",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/63748/"
] | This problem was been resolved. The ASUS "Dark Knight" router which was providing the private LAN (NAT) and port forwarding to the Mac running OS X Server has a firmware bug. The bug manifest by DROPPING the ESTABLISHED TCP connection on port 2195 between the Mac running OS X Server and APNS, after two hours of quiescence. The router should not have dropped this connection, there was no firewall rule instructing it to do so. The lesson learned is to be much more selective and wise with regard to choosing routers (especially consumer off-the-shelf variety) for use with servers even for servers run in a small business context (like a Mac Mini Server).
Heading
======= | I believe that @user3051849 has the root cause, but in my case I can't swap out the router. So, enclosed are my two workarounds. As of OSX Server 3.1.2 this problem remains.
Use Apple's launchctl to create a job that runs every 2 hours to restart the mail server. So, this should only be used on mail servers that are not busy. Create a plist file in /Library/LaunchDaemons/MailRestart.plist, the contents should be:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>mailrestart</string>
<key>ProgramArguments</key>
<array>
<string>/etc/periodic/daily/500.restart-mail</string>
</array>
<key>StartInterval</key>
<integer>7200</integer> <!-- Every 2 hours -->
<key>StandardOutPath</key>
<string>/var/log/daily.out</string>
</dict>
</plist>
```
Note that this launch agent runs Apple's `/etc/periodic/daily/500.restart-mail` script every 2 hours (7200 seconds). In case Apple removes the restart mail script, here is a [copy](https://gist.github.com/josh-h/e869c0957b2f44367cac) for your convenience.
As an aside, it seems Apple is aware of connection problems with their push service, as they created the periodic script to restart the mail server during the daily run of the `periodic` service. However, their fix is rather weak, because in my case the periodic service runs daily, but my connection to the push service is dropped after 2 hours of inactivity. So, I need something more frequent than a daily mail server restart.
Next from a shell invoke:
```
sudo launchctl load /Library/LaunchDaemons/MailRestart.plist
```
This command loads the script into the Launch Control service causing the script to run every 2 hours, logging to /var/log/daily.out (the same destination that the periodic service logs too). In my case I needed to change this to under an hour, rather than every 2.
**A Better Approach**
An alternative solution is to leave the mail daemon alone and kill the process that handles push notifications, ie. push\_notify. This has the added benefit of not killing the mail daemons which may interrupt imap connections. For example, the command:
```
sudo launchctl stop com.apple.push_notify
```
Stops the push\_notify service, launchd immediately restarts the service afterwards. So, the new process will have a fresh connection to Apple's notification servers. I'll leave it as an exercise to the reader to wrap the above into a script and invoke it from a modified plist as above. |
112,306 | * I'm running OS X 10.9 with Server 3.0.1 on a Mac residing on a private subnet sitting behind a router whose WAN port is plugged into a cable modem, hence the ISP is a well known cable internet service provider.
* This server has its DNS correctly configured (i.e., the result of "sudo changeip -checkhostname" on the server via command line yields perfect results).
* This server is running an Open Directory Master.
* Dynamic DNS is correctly configured for the router, and resolves the public IP address assigned by my ISP to the same domain name as the server (I forward any required ports for services I run).
* This server also has installed a server certificate signed by a trusted CA (i.e., Go Daddy) and is working perfectly for all OS X Server services including Open Directory.
* This server also has the Mail service configured (SMTP and IMAP) with no problems (I can send and receive mail to/from the server.
* This server server also has push notifications enabled and has a push notification certificate installed perfectly (obtained from Apple's push notification certificate portal, just renewed a few days ago).
* I have some iOS devices running iOS 7.0.4. I have configured Mail on these iOS devices to send and receive mail to/from the aforementioned server for a few different user accounts on the server. This works fine (tested, can send and receive mail no problems).
* The aforementioned iOS devices mail settings for the aforementioned server have been configured to receive push notifications when mail is received to said user accounts on the server.
With all of that said, the iOS devices are **sometimes** able to receive push notifications from the [Apple Push Notification Service](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html) (APNS "cloud") in situations when the iOS devices reside on the same private subnet as the Mac server (via Wi-Fi), and when they reside on the public Internet (via cellular data networks or public Wi-Fi networks such as coffee shops).
Thus, push notifications **do** work when mail messages on the server are received, but not always. After a period of time has elapsed on the server whereby no email messages have been received (seems to be several hours but I haven't yet been able to pinpoint it precisely), the server apparently loses what is supposed to be a **persistent** connection with the APNS gateway. OS X Server unfortunately does not log when this connection is lost. Then, when a new email message finally arrives again after several hours and is received by the server, the iOS devices do **not** receive their expected push notifications and instead OS X Server consistently logs an error message like this one (the only differences being of course the process ID and time/date stamp):
```
11/26/13 5:48:11.762 AM push_notify[181]: stream: received error: The operation couldn’t be completed. Connection reset by peer on: incoming stream: APN to host: gateway.push.apple.com:2195
```
Once the above error type is recorded in the logs, a subsequent email message sent to the server successfully generates a push notification message on the configured iOS devices so long as the subsequent message is sent before minimal time has elapsed (i.e., several hours). I do not port forward ports 2195 or 2196 from the router to the Mac server because Apple's [support document](http://support.apple.com/kb/TS4264) implies these ports are for outgoing traffic (from the server to the APNS gateway) unless I've misunderstood.
An excerpt in Apple's Mac Developer Library Technical Note TN2265 caught my attention with respect to **idle**:
>
> An occasional disconnect while your provider is idle is nothing to be
> concerned about; just re-establish the connection and carry on. If one
> of the push servers is down, the load balancing mechanism will
> transparently direct your new connection to another server assuming
> you connect by hostname and not by static IP address.
>
>
>
Is OS X Server (the "provider" in this context) essentially just "carrying on" by "re-establishing" the connection to APNS after being "idle" for several hours as noted in the logs per the stream error aformentioned?
Someone I spoke with about this posited the above problems may be due to the router's WAN port not being assigned a static IP address by my ISP, but of all the Apple developer documentation and support docs I've looked at about push notifications with OS X Server do not state a static IP address is required.
note: I have also tested this with the same hardware and settings but running OS X 10.8.5 Mountain Lion with Server app 2.2.1 with essentially the same results but IMHO better log verbosity, as in:
```
11/29/13 11:16:55.713 PM push_notify[11951]: stream: received error: The operation couldn’t be completed. Connection reset by peer on: incoming stream: APN to host: gateway.push.apple.com:2195
11/29/13 11:16:55.722 PM push_notify[11951]: Disconnected from apn server gateway.push.apple.com for topic com.apple.mail.XServer.2a132c32-dda4-45a1-68e1-b3cca3865c12: error Connection reset by peer
11/29/13 11:16:55.722 PM push_notify[11951]: will attempt to reconnect stream APN to host gateway.push.apple.com:2195 in 15 seconds
```
Any help or suggestions resolving this would be greatly appreciated, it may be something simple I've overlooked. | 2013/11/30 | [
"https://apple.stackexchange.com/questions/112306",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/63748/"
] | We originally filed a bug report regarding this problem with Apple (at the time we weren't deterministically certain it was a bug, but considering the efforts we made to resolve this with Apple Enterprise support, it seemed probabilistically to be a bug). Recently Apple engineering responded to us stating they have attempted to fix this bug in Server app version 4. Server 4 requires to be run on OS X 10.10 Yosemite. We have tested with Server 4.0.3 running on OS X 10.10.2 Yosemite with two iPhones each running iOS 8.1.3 and our router remains a Ubiquiti EdgeRouter (with no changes to the router configuration). For earlier versions of Server, assuming this bug remains unfixed in those versions, the workaround offered by Josh may be your best best. | I believe that @user3051849 has the root cause, but in my case I can't swap out the router. So, enclosed are my two workarounds. As of OSX Server 3.1.2 this problem remains.
Use Apple's launchctl to create a job that runs every 2 hours to restart the mail server. So, this should only be used on mail servers that are not busy. Create a plist file in /Library/LaunchDaemons/MailRestart.plist, the contents should be:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>mailrestart</string>
<key>ProgramArguments</key>
<array>
<string>/etc/periodic/daily/500.restart-mail</string>
</array>
<key>StartInterval</key>
<integer>7200</integer> <!-- Every 2 hours -->
<key>StandardOutPath</key>
<string>/var/log/daily.out</string>
</dict>
</plist>
```
Note that this launch agent runs Apple's `/etc/periodic/daily/500.restart-mail` script every 2 hours (7200 seconds). In case Apple removes the restart mail script, here is a [copy](https://gist.github.com/josh-h/e869c0957b2f44367cac) for your convenience.
As an aside, it seems Apple is aware of connection problems with their push service, as they created the periodic script to restart the mail server during the daily run of the `periodic` service. However, their fix is rather weak, because in my case the periodic service runs daily, but my connection to the push service is dropped after 2 hours of inactivity. So, I need something more frequent than a daily mail server restart.
Next from a shell invoke:
```
sudo launchctl load /Library/LaunchDaemons/MailRestart.plist
```
This command loads the script into the Launch Control service causing the script to run every 2 hours, logging to /var/log/daily.out (the same destination that the periodic service logs too). In my case I needed to change this to under an hour, rather than every 2.
**A Better Approach**
An alternative solution is to leave the mail daemon alone and kill the process that handles push notifications, ie. push\_notify. This has the added benefit of not killing the mail daemons which may interrupt imap connections. For example, the command:
```
sudo launchctl stop com.apple.push_notify
```
Stops the push\_notify service, launchd immediately restarts the service afterwards. So, the new process will have a fresh connection to Apple's notification servers. I'll leave it as an exercise to the reader to wrap the above into a script and invoke it from a modified plist as above. |
201,761 | I know that there are differences in measurement due to quantisation, probability, and collapse in quantum physics, but I am having trouble explaining how these ideas relate to measurement in an understandable manner.
In what ways does measurement in quantum mechanics differ from measurement in classical mechanics? | 2015/08/21 | [
"https://physics.stackexchange.com/questions/201761",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/89829/"
] | In quantum phyiscs we have a state.
In classical physics we have a state.
The former is function from configuration space at each time and the later is a point in configuration space for each time.
What we call a measurement in classical physics reveals as much information as we want about the state without changing the state.
What we call measurement in quantum physics changes the state (to orthogonally project it onto an eigenspace of an operator). So in general it changes the state (unless it was already an eigenvector of that operator).
In classical physics we can control how precisely we learn the results of the measurement.
In classical physics the state of the measurement device can give information about the state of the subject as precisely as we want.
In quantum physics the state of the measurement device coevolves with the state of the subject in a such a way as give the different projections onto the different eigenspaces in a way that is not solely determined by the subject's state but only the frequencies of getting the projections is determined solely by the subject's state. Frequencies of results if you do the measurement again and again on different but identically prepared subject states. The relative frequencies are the relative size of the squares of the orthogonal projections. | All the essential elements are already mentioned in this answer and the linked post in comments. So I'll try to give you more intuition with examples.
In principle all measurements performed on a system, will disturb it in some way, be it a classical or quantum system. In the former case, the disturbance for the most part is negligible. Telescope observations are based on catching photons from the Sun (or other light sources) that have bounced off a comet or planet. By bouncing it is clearly implied that the photons exchanged momentum with the object (comet, planet, ...) and thus disturbed it (goes without saying that the object would be equally disturbed regardless of whether the photons went unnoticed by our telescope or not). But without the photons and the involved exchange, we wouldn't be able to measure the position of the object. This was an example where you can entirely ignore the disturbance that is caused, so if you will, a *classical measurement*.
Another nice classical example would be measuring the voltage across a resistor in a circuit. One way or another you will have to set up another circuit that bypasses the resistor, e.g. by measuring the current through a galvanometer connected to the resistor. In any way your measurement is inevitably disturbed as your reading of the voltage is reduced due to the secondary circuit.
So it is clear that even in classical systems a measurement involves some form of interaction with the measured object. So what's different for quantum systems? Short answer would be that in quantum system, the caused disturbance is almost never negligible anymore. For example instead of our earlier macroscopic setup of comet-telescope, consider now a tiny particle and a microscope. The precision with which we can define the position of the particle is limited by the resolution of our microscope which is $\alpha \lambda$ where $\alpha$ is some numerical factor (that depends e.g. on the diameter of the objective) and $\lambda$ the wavelength of the light used. So in order to improve our precision, $\lambda$ has to be made as small as possible, but this means ever higher energetic photons! The resulting scattering between the energetic photons and the particle will involve huge jolts to the system, entirely changing its momentum state.
But more generally, the act of measuring the system will jog its original state onto another one. A bit more formally, if our system is originally in some coherent superposition of its eigenstates, the measurement will result in the system falling onto one of its eigenstates, with some probability. So if you consider the state of your system being $|\phi\rangle$ before the measurement, and that of the measurement device being $|M\rangle,$ the current uncoupled state of our global system will look like:
$$
|\psi\_{input} \rangle = |\phi\rangle |M\rangle = (a|\psi\_1\rangle + b |\psi\_2\rangle)|M\rangle
$$
Notice that the input state can be factored as a product of its constituents. Now the output state will be an entanglement between the device's state and our system, in the form (with $\theta$ a non-zero real number):
$$
|\psi\_{output}\rangle = a |e^{i\theta} M \rangle |\psi\_1\rangle + b |e^{-i\theta} M \rangle |\psi\_2\rangle
$$
Comparing the input and output states, you will hopefully be able to convince yourself of the consequence of the type of interaction involved between device-system during a measurement.
On a last note, a main fundamental difference between measurements in quantum systems (or more correctly a difference in *measurability of system properties*) and classical ones is the fact that in the former there are conjugate pairs of observables such as position and momentum that are not measurable simultaneously, not even in principle, whereas classically the state of the system corresponds to a point in its phase space at any instant in time $t,$ which by definition is a tuple of position and momentum $(\vec{r}(t),\vec{p}(t)).$ If you are interested, the book by [J.J. Binney, The physics of Quantum Mechanics](http://rads.stackoverflow.com/amzn/click/0199688575) is filled with intuitive explanations and examples. |
69,014 | I have been looking all over and either I can't find anything or I
can't find anything that works... so here I am.
How can I go about setting up SSL/HTTPS with regards to Mongrel?
Thanks in advance! | 2009/09/26 | [
"https://serverfault.com/questions/69014",
"https://serverfault.com",
"https://serverfault.com/users/21287/"
] | You run it through a real webserver first, like nginx or Apache, which does the SSL work for you, and then passes back a header saying whether or not the connection was made via SSL (only important if you're doing things like redirecting if a needs-to-be-secure page was accessed without SSL).
In theory, I guess you could stick stunnel in front of mongrel and do it that way, but the reasons not to are huge and scary, so just don't. | I struggled with this for a while. Mongrel prefers 'The Ruby Way' which is different then the Apache way.
Configure Apache HTTP to serve HTTPS traffic. Then proxy the plaintext/HTTP connections on the backend.
1. Install mod\_proxy. I actually had to recompile httpd to include proxy support.
LoadModule proxy\_module modules/mod\_proxy.so
LoadModule proxy\_http\_module modules/mod\_proxy\_http.so
LoadModule proxy\_connect\_module modules/mod\_proxy\_connect.so
2. Use mod\_rewrite's [proxy] parameter to rewrite all traffic to the Mongrel host. My host is a VirtualHost, with a name like 'ruby.example.org'.
RewriteRule ^/(.\*) <http://127.0.0.1:3000/>$1 [proxy]
3. Restrict access to the proxy. See httpd.apache.org/docs/2.2/mod/mod\_proxy.html#access
```
<Proxy *>
Order Deny,Allow
Deny from all
# Restrict access from my local network
Allow from 192.168.0
</Proxy>
``` |
69,014 | I have been looking all over and either I can't find anything or I
can't find anything that works... so here I am.
How can I go about setting up SSL/HTTPS with regards to Mongrel?
Thanks in advance! | 2009/09/26 | [
"https://serverfault.com/questions/69014",
"https://serverfault.com",
"https://serverfault.com/users/21287/"
] | It should of course be noted that Mongrel simply "doesn't do" SSL itself. | I struggled with this for a while. Mongrel prefers 'The Ruby Way' which is different then the Apache way.
Configure Apache HTTP to serve HTTPS traffic. Then proxy the plaintext/HTTP connections on the backend.
1. Install mod\_proxy. I actually had to recompile httpd to include proxy support.
LoadModule proxy\_module modules/mod\_proxy.so
LoadModule proxy\_http\_module modules/mod\_proxy\_http.so
LoadModule proxy\_connect\_module modules/mod\_proxy\_connect.so
2. Use mod\_rewrite's [proxy] parameter to rewrite all traffic to the Mongrel host. My host is a VirtualHost, with a name like 'ruby.example.org'.
RewriteRule ^/(.\*) <http://127.0.0.1:3000/>$1 [proxy]
3. Restrict access to the proxy. See httpd.apache.org/docs/2.2/mod/mod\_proxy.html#access
```
<Proxy *>
Order Deny,Allow
Deny from all
# Restrict access from my local network
Allow from 192.168.0
</Proxy>
``` |
37,079,953 | I have three model classes
```
public class Item1{
public int Id;
public List<Item2> Item2List { get; set; }
}
public class Item2{
public int Id;
//this is the FK
public int Item1Id {get;set;}
public Item1 Item1 {get;set;}
//Not in db. Ignored field in EntityTypeConfiguration
public int Item3Count;
public List<Item3> Item3List { get; set; }
}
public class Item3{
public int Id;
//this is the FK
public int Item2Id {get;set;}
public Item2 Item2 {get;set;}
}
```
I want to return the list of Item1 along with list of associated Item2, and load the COUNT of Item3List associated with Item 2 without loading the Item3List.
Here is what I am doing right now:
```
public IEnumerable<Item1> GetItems()
{
return base.Query().Include(item1 => item1.Item2List.Select(item2 => item2.Item3List)).ToList();
}
```
This returns me the list of all 3 objects Item1, Item2 and Item3. But I only need the count of Item3List in Item3Count, and not the entire Item3List list. How can I achieve that? I tried this below, but it throws error.
```
return base.Query().Include(item1 => item1.Item2List.Select(item2 => new Item2 {
Item3Count = item2.Item3List.Count()
})).ToList();
```
>
> The Include path expression must refer to a navigation property
> defined on the type. Use dotted paths for reference navigation
> properties and the Select operator for collection navigation
> properties. Parameter name: path
>
>
> | 2016/05/06 | [
"https://Stackoverflow.com/questions/37079953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6301786/"
] | What you want is not possible. Of course you can't populate a not-mapped property in an EF LINQ query, because that's the idea of not mapping it. But you already knew that.
What you'd really like to do is something like this:
```
context.Item1s.Select(item1 => new Item1
{
Id = item1.Id,
Item2s = item1.Item2List.Select(item2 => new Item2List
{
Id = item2.Id,
Item3Count = item2.Item3List.Count()
})
})
```
But EF doesn't allow you to construct an entity object in an EF query.
The alternatives are not appealing.
You could build a structure of anonymous types ...
```
context.Item1s.Select(item1 => new
{
Item1 = item1,
Item2s = item1.Item2List.Select(item2 => new
{
Item2 = item2,
Item3Count = item2.Item3List.Count()
})
})
```
... and use this to construct a list of `Item1` objects, each having their `Item2List`s of `Item2`s with `Item3Count` values.
Better, but still not close to what would be ideal, is to use AutoMapper and map the entities to DTOs:
```
Mapper.CreateMap<Item1,Item1Dto>();
Mapper.CreateMap<Item2,Item2Dto>();
```
You can use AutoMapper's [flattening feature](https://github.com/AutoMapper/AutoMapper/wiki/Flattening) to populate `Item3Count`. To do this, `Item2Dto` should have a property `Item3ListCount` and AutoMapper will translate this to `Item3List.Count()`. | You are not using the ef conventions. Refer to <https://msdn.microsoft.com/en-us/data/jj819164.aspx> for that.
You have to do something like this:
---
```
public class Item1{
public int Item1Id{get;set;}
public ICollection<Item2> Item2s{ get; set; }
}
public class Item2{
public int Item2Id{get;set;}
//Not in db. Ignored field in mapping
[NotMapped]
public int Item3Count => Item3s.Count;
//this is the FK
public int Item1Id{get;set;}
public Item1 Item1 {get;set;}
public ICollection<Item3> Item3s{ get; set; }
}
public class Item3{
public int Item3Id;
//FK
public int Item2Id {get;set;}
public Item2 Item2 {get;set;}
}
```
---
Now:
```
public IEnumerable<int> GetCounts()
{
//get the items1 including its List of item2
var items1 = base.Query().Include(item1 => item1.Item2s);
//get the counts
var counts = items1.Select(item1 => item1.Item2s.Select(item2 => item2.Item3Count));
//now in counts you have what you want, do what you please with it
//and return it
return counts;
```
}
---
I haven't tried this by it should works for you. |
283,211 | I want to use the Whitney Mann U test (i.e. Wilcoxon Rank Sum) test to test for differences in an ordinal outcome variable (say a 5 point Likert item) among two randomly selected samples. I've read a few articles online and I'm not sure what challenges are introduced when the data are in fact ordinal. Hopefully you all can help me understand the implications of working with ordinal data.
A page hosted by the stats department at [Purdue](http://www.stat.purdue.edu/~tqin/system101/method/method_wilcoxon_rank_sum_sas.htm) and another hosted by the Institute for Digital Research and Education at [UCLA](https://stats.idre.ucla.edu/other/mult-pkg/whatstat/) claim we can use the Mann-Whitney U test when:
1. Comparing two samples.
2. The two groups of data are independent.
3. The type of variable could be continuous or ordinal.
4. The data might not be normally distributed.
However, a STA3024 file hosted by the stats department at [UFL](http://www.stat.ufl.edu/~winner/sta3024/chapter14.pdf), a STAT464 page hosted by the stats department at [PennState](https://onlinecourses.science.psu.edu/stat464/node/36), a STAT105 file hosted by the stats department at [UCLA](http://www.stat.ucla.edu/~hqxu/stat105/pdf/ch15.pdf), and an article hosted by the stats department at [Iowa -- Ames](http://homepage.divms.uiowa.edu/~kcowles/s166_2007/chenxieproject.pdf) claim this test is only appropriate for observations drawn from continuous distributions. How does the actual discrete reality of an ordinal sample affect the validity (and hypotheses) of this test (if at all)?
While the UFL file claimed continuity was important, it goes on to show an example of the Wilcoxon Rank Sum test (i.e., the Whitney-Mann U test) using responses that fall on a 5 point Likert scale. In fact, it argues that using this test with ordinal data is reasonable since the WMU test "uses only the order of the responses, not their actual values." What is happening with these data and this test to make this valid? | 2017/06/02 | [
"https://stats.stackexchange.com/questions/283211",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/14233/"
] | If you want to compare Likert item data from two groups with methods that I believe no one will object to, you have a couple of options.
One is ordinal regression, which is very flexible for experimental design, and is relatively easy in some software packages.
Another is the Cochran-Armitage test. The traditional form can compare only two groups, but some implementations can handle more than two groups.
You will find different opinions on using traditional nonparametric tests like Wilcoxon–Mann–Whitney (WMW) on Likert item data.
From what I can gather, the common objections to using WMW with Likert item data are a) the test has an assumption of a continuous dependent variable, and b) the test may not behave well when there are many ties in the data (as would be case for Likert data.)
From what I can gather, the common defenses for using WMW with Likert item data is that a) the test is fine handling ordinal data, and b) the test accounts for ties, at least in modern implementations. I have also heard the argument that Likert item data represents a latent continuous variable, and so doesn't violate the continuity assumption.
I'm not a statistician, so I won't attempt to evaluate these arguments.
In my experience, the traditional nonparametric tests are generally well-behaved with Likert item data. At the bottom of the page, [there are simulations here comparing WMW and Kruskal–Wallis to ordinal regression](http://rcompanion.org/handbook/E_01.html).
I also think that the hypothesis that WMW tests, that of stochastic equality, makes sense in many situations with Likert item data.
As a final note, I think the advice of @DavidSmith --- using a chi-square test of association for Likert item data --- is usually not a good approach. The problem with this approach is that it discards the information about the ordinal nature of the data, and tests a hypothesis, I think, that is not generally what the analyst is interested in. | Neither web site is entirely wrong but neither gives you the full story, either.
I also think you are confusing the names of somewhat different tests. The Mann-Whitney and the Wilcoxon test are essentially the same and they are used to compare two distinct samples. The signed rank test, an extension of the the Wilcoxon test.
I am writing this under the impression that you have two samples, each with the same variable measured on a scale or 1, 2, 3, 4, 5. The tests you mention have no bearing.
The basic test you need is an old-fashioned chi-square test for independence. This is a general-purpose test, however, and does not take the ordering of the five categories into account. There are several proposed procedures that take the ordering into account. It isn't clear which method to use or if the ordering is that important to account for. |
53,297,935 | I have problem when I custom font on Flutter
My folder font
myapp/fonts/SairaSemiCondensed-Bold.ttf
here my pubspec.ymal
```
fonts:
- family: SairaSemiCondensed
fonts:
- asset: fonts/fonts:SairaSemiCondensed-Bold.ttf
weight: 700
```
I got error like this
```
Error on line 55, column 4 of pubspec.yaml: Expected a key while parsing a
block mapping.
fonts:
^
pub get failed (65)
```
Can anyone help me? | 2018/11/14 | [
"https://Stackoverflow.com/questions/53297935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8561296/"
] | Try
```
fonts:
- family: SairaSemiCondensed
fonts:
- asset: fonts/fonts:SairaSemiCondensed-Bold.ttf
weight: 700 # indented more
```
but it's more likely that the indentation of the whole block is wrong (or missing). Try to indent all lines in your questions one tab or 2 spaces more.
Indentation is significant in yaml.
Try to follow indentation exactly as shown in <https://flutter.io/docs/cookbook/design/fonts> if my suggestion above doesn't work. | try removing the {:} colon in the fonts directory and write
```
fonts:
- family: SairaSemiCondensed
fonts:
- asset: fonts/SairaSemiCondensed-Bold.ttf
weight: 700 # indented more
```
INSTEAD |
53,297,935 | I have problem when I custom font on Flutter
My folder font
myapp/fonts/SairaSemiCondensed-Bold.ttf
here my pubspec.ymal
```
fonts:
- family: SairaSemiCondensed
fonts:
- asset: fonts/fonts:SairaSemiCondensed-Bold.ttf
weight: 700
```
I got error like this
```
Error on line 55, column 4 of pubspec.yaml: Expected a key while parsing a
block mapping.
fonts:
^
pub get failed (65)
```
Can anyone help me? | 2018/11/14 | [
"https://Stackoverflow.com/questions/53297935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8561296/"
] | Try
```
fonts:
- family: SairaSemiCondensed
fonts:
- asset: fonts/fonts:SairaSemiCondensed-Bold.ttf
weight: 700 # indented more
```
but it's more likely that the indentation of the whole block is wrong (or missing). Try to indent all lines in your questions one tab or 2 spaces more.
Indentation is significant in yaml.
Try to follow indentation exactly as shown in <https://flutter.io/docs/cookbook/design/fonts> if my suggestion above doesn't work. | The issue was coming up with me.
please recheck all lines in your `pubspec.yaml` file. it's spaces issue. |
53,297,935 | I have problem when I custom font on Flutter
My folder font
myapp/fonts/SairaSemiCondensed-Bold.ttf
here my pubspec.ymal
```
fonts:
- family: SairaSemiCondensed
fonts:
- asset: fonts/fonts:SairaSemiCondensed-Bold.ttf
weight: 700
```
I got error like this
```
Error on line 55, column 4 of pubspec.yaml: Expected a key while parsing a
block mapping.
fonts:
^
pub get failed (65)
```
Can anyone help me? | 2018/11/14 | [
"https://Stackoverflow.com/questions/53297935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8561296/"
] | The issue was coming up with me.
please recheck all lines in your `pubspec.yaml` file. it's spaces issue. | try removing the {:} colon in the fonts directory and write
```
fonts:
- family: SairaSemiCondensed
fonts:
- asset: fonts/SairaSemiCondensed-Bold.ttf
weight: 700 # indented more
```
INSTEAD |
40,827,710 | I am trying to learn functional programming and Scala, so I'm reading the "Functional Programming in Scala" by Chiusano and Bjarnason. I' m having trouble understanding what fold left and fold right methods do in case of a list. I've looked around here but I haven't find something beginner friendly. So the code provided by the book is:
```
def foldRight[A,B](as: List[A], z: B)(f: (A, B) => B): B = as match {
case Nil => z
case Cons(h, t) => f(h, foldRight(t, z)(f))
}
def foldLeft[A,B](l: List[A], z: B)(f: (B, A) => B): B = l match {
case Nil => z
case Cons(h,t) => foldLeft(t, f(z,h))(f)
}
```
Where Cons and Nil are:
```
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
```
So what do actually fold left and right do? Why are needed as "utility" methods? There are many other methods that use them and I have trouble to understand them as well, since I don't get those two. | 2016/11/27 | [
"https://Stackoverflow.com/questions/40827710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3342710/"
] | According to my experience, one of the best ways to workout the intuition is to see how it works on the very simple examples:
```
List(1, 3, 8).foldLeft(100)(_ - _) == ((100 - 1) - 3) - 8 == 88
List(1, 3, 8).foldRight(100)(_ - _) == 1 - (3 - (8 - 100)) == -94
```
As you can see, `foldLeft/Right` just passes the element of the list and the result of the previous application to the the operation in second parentheses.
It should be also mentioned that if you apply these methods to the same list, they will return equal results only if the applied operation is associative. | Say you have a list of numbers, and you want to add them all up. How would you do that?
You add the first and the second, then take the result of that, add that to the third, take the result of that, add it to the fourth.. and so on.
That's what fold let's you do.
```
List(1,2,3,4,5).foldLeft(0)(_ + _)
```
The "+" is the function you want to apply, with the first operand being the result of its application to the elements so far, and the second operand being the next element.
As you don't have a "result so far" for the first application, you provide a start value - in this case 0, as it is the identity element for addition.
Say you want to multiply all of your list elements, with fold, that'd be
```
List(1,2,3,4,5).foldLeft(1)(_ * _)
```
Fold has it's own [Wikipedia page](https://en.wikipedia.org/wiki/Fold_(higher-order_function)#Folds_on_lists) you might want to check.
Of course there are also ScalaDoc entries for [foldLeft](http://www.scala-lang.org/api/current/scala/collection/immutable/List.html#foldLeft[B](z:B)(op:(B,A)=>B):B) and [foldRight](http://www.scala-lang.org/api/current/scala/collection/immutable/List.html#foldRight[B](z:B)(op:(A,B)=>B):B). |
60,077,241 | `d = {1: ['a'], 3: ['b','c'], 4: ['a','d'], 5: ['b','c','d']}`, this is just an example. I have a large file of such key-values pair. My question is how can I find values that is present in multiple key-value pair. I want to fetch that key-value pair. For this example, the first value corresponding to key `1` is `'a'` and it is present in `4:['a','d']`, so I want to fetch `4: ['a', 'd']` pair.
Note that, I have a huge dictionary containing over millions entries. | 2020/02/05 | [
"https://Stackoverflow.com/questions/60077241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10899026/"
] | In order to have an Excel-DNA function that allows passing in an *unknown* number of arguments at run-time, you need to use `params object[]` in your function arguments.
```
public static class MyFunctions
{
[ExcelFunction]
public static object Hello(params object[] values)
{
return "Hello " + DateTime.Now;
}
}
```
Then it doesn't matter if you call it with hard-coded values e.g. `=Hello(10, 20)` or if you use cell references e.g. `=Hello(A1,A5,A10)`.
However, variable number of arguments is not supported out-of-the-box by Excel-DNA, and as such you'll have to use the [`ExcelDna.Registration`](https://github.com/Excel-DNA/Registration) helper library in order to register your functions.
Install the [ExcelDna.Registration NuGet package](https://www.nuget.org/packages/ExcelDna.Registration/), then inside of your `.dna` file, mark your add-in assembly reference to use `ExplicitRegistration` e.g.:
```
<?xml version="1.0" encoding="utf-8"?>
<DnaLibrary Name="My Add-In" (...)>
<ExternalLibrary Path="MyAddIn.dll" ExplicitRegistration="true" (...) />
</DnaLibrary>
```
Then, in your `AutoOpen`, you register the functions with a `ProcessParamsRegistrations` call... e.g.
```
public class AddIn : IExcelAddIn
{
public void AutoOpen()
{
ExcelRegistration
.GetExcelFunctions()
.ProcessParamsRegistrations()
.RegisterFunctions();
// ...
}
public void AutoClose()
{
// ...
}
}
```
---
>
> Implicit vs Explicit Registration of functions
>
>
>
By default, Excel-DNA searches for every `public static` method in your assembly and registers them as functions with Excel. That's the *implicit* registration process.
`ExplicitRegistration="true"` turns **off** the implicit registration and thus nothing gets registered automatically - you have to do it yourself - which is what I'm doing in the `AutoOpen` above with the `... RegisterFunctions()` call. **If you don't turn off the *implicit* registration, then functions end-up being registered twice** (once by the implicit process, then again by your code) **and you get error messages** | The others answers are useful if you'd like to allow multiple parameters, and perhaps easiest for an end user to use. But you could also pass the discontinuous ranges directly into the single `AllowReference=true` parameter you start with, by adding parentheses in the formula:
`=Fnc1((A1,A5,A10:A12))`
The single `ExcelReference` you get will have multiple `InnerReferences` for the disjoint parts.
The parentheses disambiguate between the use of the comma as a range union operator and as the parameter separator in a function call. |
41,913 | So if I have a custom function with a DB query within *template.php* such as
```
function innovista_get_page_children() {
$result = db_query("SELECT link_path FROM {menu_links}");
return $result;
}
```
and I have a content type specific template page, then how do I echo the results in the template file?
I tried this:
```
<?php
$results = innovista_get_page_children();
foreach($results as $result){
print $result;
}
?>
```
I get the following error
>
> Recoverable fatal error: Object of class stdClass could not be
> converted to string in include() (line 83 of
> /var/www/vhosts/vidanlawnes.co.uk/innovista2/sites/all/themes/innovista/node--level\_1.tpl.php).
>
>
>
If I remove print $result; and replace with print 'hello'... e.g
```
<?php
$results = innovista_get_page_children();
foreach($results as $result){
//print $result;
print 'hello ';
}
?>
```
It echoes hello out multiple times, so the query is providing results, but I can't seem to print them as $result. Any ideas?
Thanks for your time | 2012/09/06 | [
"https://drupal.stackexchange.com/questions/41913",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/9568/"
] | Every theme function/template runs [`hook_preprocess_HOOK()`](http://api.drupal.org/hook_preprocess_hook) and [`hook_process_hook()`](http://api.drupal.org/hook_process_hook) before executing the function/template. `hook_preprocess_HOOK` is where you'd want to set up any new variables. The hook is passed an array of variables by reference, and you add to that array. The key of the array becomes the name of the variable in your template. People often try to keep all the logic out of the template file in this way. For example to set up a variable `$foo` in a page template (ie what's used for `theme('page', ...)`) you could do this.
```
/**
* Implements hook_preprocess_page().
*/
MYMODULE_preprocess_page(&$vars) {
$vars['foo'] = 'bar';
}
``` | First I dont suggest put your function in template.php directly, (you can put in in custom module)
I suggest you act more professionaler in function, This code showed your are begginer in drupal developing,
however . this code have to work because template.php function in exist form basic drupal bootstrapping.
Your problem is your function maybe not return anything and $var will be empty.
When I was begginer in drupal put my global fuction in themplate.php and use them in every where i want, test something like this
```
function myfunction() {
$result = db_query("SELECT field FROM {table} WHERE field = 'query' ");
if ($result)
return $result;
else
return "sorry,no result";
}
```
and in your tpl file
```
<?php
$myvar = mytheme_myfunction();
print $myvar;
?>
```
I know this is not principle method but sometimes we just need it just work. :) |
41,913 | So if I have a custom function with a DB query within *template.php* such as
```
function innovista_get_page_children() {
$result = db_query("SELECT link_path FROM {menu_links}");
return $result;
}
```
and I have a content type specific template page, then how do I echo the results in the template file?
I tried this:
```
<?php
$results = innovista_get_page_children();
foreach($results as $result){
print $result;
}
?>
```
I get the following error
>
> Recoverable fatal error: Object of class stdClass could not be
> converted to string in include() (line 83 of
> /var/www/vhosts/vidanlawnes.co.uk/innovista2/sites/all/themes/innovista/node--level\_1.tpl.php).
>
>
>
If I remove print $result; and replace with print 'hello'... e.g
```
<?php
$results = innovista_get_page_children();
foreach($results as $result){
//print $result;
print 'hello ';
}
?>
```
It echoes hello out multiple times, so the query is providing results, but I can't seem to print them as $result. Any ideas?
Thanks for your time | 2012/09/06 | [
"https://drupal.stackexchange.com/questions/41913",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/9568/"
] | The error message itself is clear I think. You are trying to print an object as a string.
otherwise, your query seems correct.
```
function innovista_get_page_children() {
$result = db_query("SELECT link_path FROM {menu_links}");
return $result;
}
<?php
$results = innovista_get_page_children();
print '<pre>';
foreach($results as $result){
print_r($result);
}
print '</pre>';
?>
```
Now you will see a formatted variable information of each $result.
it will look like
```
stdClass Object (
[link_path] => admin/structure/views
)
```
So when you print the results, it will be like,
```
<?php
$results = innovista_get_page_children();
foreach($results as $result){
print $result->link_path;
print '<br/>';
}
?>
```
However, keep in mind that it's never OK to print link paths or database queries like this. It will cause huge performance problems and will arise security problems.
Try to use url() and/or l() functions for links (suggested it because you seem to make a link).
Also, in most cases, there is a function for core/contrib modules to retrive data. | Every theme function/template runs [`hook_preprocess_HOOK()`](http://api.drupal.org/hook_preprocess_hook) and [`hook_process_hook()`](http://api.drupal.org/hook_process_hook) before executing the function/template. `hook_preprocess_HOOK` is where you'd want to set up any new variables. The hook is passed an array of variables by reference, and you add to that array. The key of the array becomes the name of the variable in your template. People often try to keep all the logic out of the template file in this way. For example to set up a variable `$foo` in a page template (ie what's used for `theme('page', ...)`) you could do this.
```
/**
* Implements hook_preprocess_page().
*/
MYMODULE_preprocess_page(&$vars) {
$vars['foo'] = 'bar';
}
``` |
41,913 | So if I have a custom function with a DB query within *template.php* such as
```
function innovista_get_page_children() {
$result = db_query("SELECT link_path FROM {menu_links}");
return $result;
}
```
and I have a content type specific template page, then how do I echo the results in the template file?
I tried this:
```
<?php
$results = innovista_get_page_children();
foreach($results as $result){
print $result;
}
?>
```
I get the following error
>
> Recoverable fatal error: Object of class stdClass could not be
> converted to string in include() (line 83 of
> /var/www/vhosts/vidanlawnes.co.uk/innovista2/sites/all/themes/innovista/node--level\_1.tpl.php).
>
>
>
If I remove print $result; and replace with print 'hello'... e.g
```
<?php
$results = innovista_get_page_children();
foreach($results as $result){
//print $result;
print 'hello ';
}
?>
```
It echoes hello out multiple times, so the query is providing results, but I can't seem to print them as $result. Any ideas?
Thanks for your time | 2012/09/06 | [
"https://drupal.stackexchange.com/questions/41913",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/9568/"
] | The error message itself is clear I think. You are trying to print an object as a string.
otherwise, your query seems correct.
```
function innovista_get_page_children() {
$result = db_query("SELECT link_path FROM {menu_links}");
return $result;
}
<?php
$results = innovista_get_page_children();
print '<pre>';
foreach($results as $result){
print_r($result);
}
print '</pre>';
?>
```
Now you will see a formatted variable information of each $result.
it will look like
```
stdClass Object (
[link_path] => admin/structure/views
)
```
So when you print the results, it will be like,
```
<?php
$results = innovista_get_page_children();
foreach($results as $result){
print $result->link_path;
print '<br/>';
}
?>
```
However, keep in mind that it's never OK to print link paths or database queries like this. It will cause huge performance problems and will arise security problems.
Try to use url() and/or l() functions for links (suggested it because you seem to make a link).
Also, in most cases, there is a function for core/contrib modules to retrive data. | First I dont suggest put your function in template.php directly, (you can put in in custom module)
I suggest you act more professionaler in function, This code showed your are begginer in drupal developing,
however . this code have to work because template.php function in exist form basic drupal bootstrapping.
Your problem is your function maybe not return anything and $var will be empty.
When I was begginer in drupal put my global fuction in themplate.php and use them in every where i want, test something like this
```
function myfunction() {
$result = db_query("SELECT field FROM {table} WHERE field = 'query' ");
if ($result)
return $result;
else
return "sorry,no result";
}
```
and in your tpl file
```
<?php
$myvar = mytheme_myfunction();
print $myvar;
?>
```
I know this is not principle method but sometimes we just need it just work. :) |
463,530 | Here is what I did to fix this problem
* I installed the japanese language pack.
* I unchecked the "Hide fonts according to your language settings" option.
* I set the local language to Japanese and back to my language
* I delete the FNTCACHE.DAT in C:\Windows\System32
There is a 50% chance that when I do a cold boot, all file names and text in programs (e.g. skype) with japanese font/kanji display as squares.
A reboot often fixes the problem temporarily but it's super annoying.
Does anyone know how to fix this constantly? | 2012/08/19 | [
"https://superuser.com/questions/463530",
"https://superuser.com",
"https://superuser.com/users/152913/"
] | It's just way too simple and easy. Create a file named 火.txt and place it on your desktop, then reboot. (Tested only on Win7)
This will work because of font-caching. There are two main parts in the os that create the cache. One is the Windows Explorer, the other one the DirectWrite part of DX. The problem is, that DXW fails with Unicode. So when a programm starts up using unicode and the dxw api, the font-cache is build by dxw, not containing unicode because of the fail. If you place the txt file on your desktop, it's the explorers first turn to fill the cache. And explorer supports unicode, so the cache is initialized correctly. | * Make sure you are also using Keyboard for Japanese language.
* Also use the **Japanese locale**. |
42,136,342 | Is there a way to do this as an extension to Array as opposed to a switch statement that's going to grow and grow?
```
fileprivate var exteriorColorOptions = [ExteriorColorOption]()
fileprivate var otherOptions = [SomeOtherOption]()
: more options
func add(option:FilteredOption) {
switch(option) {
case let thing as ExteriorColorOption:
exteriorColorOptions.append(thing)
case and on and on
default:
break
}
}
```
I would like to be able to just do the following with the right extension in place:
```
exteriorColorOptions.appendIfPossible(option)
otherOptions.appendIfPossible(option)
```
Note: switch approach came from
[Swift: Test class type in switch statement](https://stackoverflow.com/questions/25724527/swift-test-class-type-in-switch-statement) | 2017/02/09 | [
"https://Stackoverflow.com/questions/42136342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/175956/"
] | This should work:
```
extension Array {
mutating func appendIfPossible<T>(newElement: T) {
if let e = newElement as? Element {
append(e)
}
}
}
```
The conditional cast `newElement as? Element` succeeds if the
new element conforms to or is an instance of (a subclass of) the arrays element type `Element`.
Example:
```
class A {}
class B: A {}
class C {}
var array: [A] = []
array.appendIfPossible(newElement: B())
print(array) // [B]
array.appendIfPossible(newElement: C())
print(array) // [B]
``` | Actually the answer is correct but maybe not exactly what you want:
```
extension Array {
mutating func safeAppend(newElement: Element?) {
if let element = newElement {
append(element)
}
}
```
This one will throw a compile time error in case you try appending an element thats not of the arrays original type.
E.g. you will see an error if you try to append an `Int` to an array of string `[String]`. |
43,099,851 | I have two collection views. Tapping unselected cells in Collection View 1 selects them, and adds the selected cell to Collection View 2. Tapping on selected cells in Collection View 1 (allHobbiesCV) will unselect them and remove them from Collection View 2 (myHobbiesCV). Essentially, all it's doing is toggling.
Cells in Collection View 2 can also be manually removed by selecting as few or many as desired, then pressing a 'Remove' button. This process works great, except the cells in Collection View 1 still remain selected, even if that particular cell was removed from Collection View 2.
**How do I use the remove button to deselect cells from Collection View 1 if they were manually selected and removed from Collection View 2?**
*Class level -*
```
var allHobbiesArray = [String]()
var allHobbiesArraySelected = [String]()
var myHobbiesArray = [String]()
var myHobbiesArraySelected = [String]()
```
**didSelectItemAt**
```
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// All Hobbies
if collectionView == allHobbiesCV {
let item = allHobbiesArray[indexPath.item]
let cell = allHobbiesCV.cellForItem(at: indexPath) as! AllHobbiesCell
if let itemIndex = allHobbiesArraySelected.index(of:item) {
// DID DESELECT
allHobbiesArraySelected.remove(at:itemIndex)
myHobbiesArray.remove(at: itemIndex)
myHobbiesCV.deleteItems(at: [IndexPath(item: itemIndex, section:0)])
cell.backgroundColor = UIColor.brown
}
else {
// DID SELECT
allHobbiesArraySelected.insert(item, at: 0)
myHobbiesArray.insert(item, at: 0)
myHobbiesCV.insertItems(at: [IndexPath(item: 0, section:0)])
cell.backgroundColor = UIColor.green
}
allHobbiesCV.deselectItem(at: indexPath, animated: false)
for cell in myHobbiesCV.visibleCells {
cell.backgroundColor = UIColor.white
}
myHobbiesArraySelected.removeAll()
//myHobbiesCV.reloadData() // needed?
}
// My Hobbies
else {
let item = myHobbiesArray[indexPath.item]
let cell = myHobbiesCV.cellForItem(at: indexPath) as! MyHobbiesCell
if let itemIndex = myHobbiesArraySelected.index(of:item) {
// DID DESELECT
myHobbiesArraySelected.remove(at: itemIndex)
cell.backgroundColor = UIColor.white
}
else {
// DID SELECT
myHobbiesArraySelected.insert(item, at: 0)
cell.backgroundColor = UIColor.red
}
myHobbiesCV.deselectItem(at: indexPath, animated: true)
}
}
```
**cellForItem**
```
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == allHobbiesCV {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ALL", for: indexPath) as! AllHobbiesCell
cell.allHobbiesCellLabel.text = allHobbiesArray[indexPath.item]
let allHobbies = allHobbiesArray[indexPath.item]
if allHobbiesArraySelected.index(of: allHobbies) != nil {
cell.backgroundColor = UIColor.green
}
else {
cell.backgroundColor = UIColor.brown
}
return cell
}
else { // myHobbiesCV
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MY", for: indexPath) as! MyHobbiesCell
cell.myHobbiesCellLabel.text = myHobbiesArray[indexPath.item]
let myHobbies = myHobbiesArray[indexPath.item]
if myHobbiesArraySelected.index(of: myHobbies) != nil {
cell.backgroundColor = UIColor.red
}
else {
cell.backgroundColor = UIColor.white
}
return cell
}
}
```
**numberOfItemsInSection**
```
if collectionView == allHobbiesCV {
return allHobbiesArray.count
}
else {
return myHobbiesArray.count
}
```
**Delete button**
```
@IBAction func deleteHobbyButtonPressed(_ sender: UIButton) {
print("all Hobbies - \(allHobbiesCV.indexPathsForSelectedItems!)")
if let selectedItemPaths = myHobbiesCV.indexPathsForSelectedItems {
var allItemIndexPaths = [IndexPath]()
var tempSelectedItems = Array(allHobbiesArraySelected) // Need to use a temporary copy otherwise the element indexes will change
for itemPath in selectedItemPaths {
let removeItem = allHobbiesArraySelected[itemPath.item]
if let removeIndex = tempSelectedItems.index(of: removeItem) {
print("if let removeIndex")
tempSelectedItems.remove(at: removeIndex)
}
if let allItemsIndex = allHobbiesArray.index(of: removeItem) {
print("if let allItemsIndex")
allItemIndexPaths.append(IndexPath(item: allItemsIndex, section: 0))
}
}
allHobbiesArraySelected = tempSelectedItems // Selected items array without the removed items
myHobbiesCV.deleteItems(at:selectedItemPaths)
myHobbiesCV.reloadData()
allHobbiesCV.reloadItems(at: allItemIndexPaths) // Reload to update the selected status
}
}
```
The problem now is nothing is evaluating in the remove button. That first print statement always returns an empty array. And nothing prints in the if let check. Is there a way to use myHobbiesArraySelected instead of indexPathsForSelectedItems? (Since I'm saving the selected items in an array now) Along with the original intended functionality of deselecting the cell in allHobbiesCV if it was manually deleted in myHobbiesCV.
Thanks friends. | 2017/03/29 | [
"https://Stackoverflow.com/questions/43099851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220994/"
] | You can use Information\_schema or sys.columns
```
select * from information_schema.columns where table_name = 'card' and table_schema = 'schema1'
except
select * from information_schema.columns where table_name = 'card' and table_schema = 'schema2'
```
--With full join
```
select * from information_schema.columns t1
full join information_schema.columns t2
on t1.table_catalog=t2.table_catalog
and t1.column_name = t2.column_name
where
t1.table_name = 'card' and t2.table_name = 'card'
and t1.table_schema = 'schema1' and t2.table_schema = 'schema2'
and (t1.column_name is null or t2.column_name is null)
``` | ```
select Column_Name from information_schema.columns where table_name = 'sysjobs' and table_schema = 'YourSchema1'
except
select Column_Name from information_schema.columns where table_name = 'sysjobservers' and table_schema = 'YourSchema2'
```
Also, what you can do it is create a variable and loop through all schemas and put the difference in a temporary table. This way you do not have to do one by one and you can automate it |
43,099,851 | I have two collection views. Tapping unselected cells in Collection View 1 selects them, and adds the selected cell to Collection View 2. Tapping on selected cells in Collection View 1 (allHobbiesCV) will unselect them and remove them from Collection View 2 (myHobbiesCV). Essentially, all it's doing is toggling.
Cells in Collection View 2 can also be manually removed by selecting as few or many as desired, then pressing a 'Remove' button. This process works great, except the cells in Collection View 1 still remain selected, even if that particular cell was removed from Collection View 2.
**How do I use the remove button to deselect cells from Collection View 1 if they were manually selected and removed from Collection View 2?**
*Class level -*
```
var allHobbiesArray = [String]()
var allHobbiesArraySelected = [String]()
var myHobbiesArray = [String]()
var myHobbiesArraySelected = [String]()
```
**didSelectItemAt**
```
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// All Hobbies
if collectionView == allHobbiesCV {
let item = allHobbiesArray[indexPath.item]
let cell = allHobbiesCV.cellForItem(at: indexPath) as! AllHobbiesCell
if let itemIndex = allHobbiesArraySelected.index(of:item) {
// DID DESELECT
allHobbiesArraySelected.remove(at:itemIndex)
myHobbiesArray.remove(at: itemIndex)
myHobbiesCV.deleteItems(at: [IndexPath(item: itemIndex, section:0)])
cell.backgroundColor = UIColor.brown
}
else {
// DID SELECT
allHobbiesArraySelected.insert(item, at: 0)
myHobbiesArray.insert(item, at: 0)
myHobbiesCV.insertItems(at: [IndexPath(item: 0, section:0)])
cell.backgroundColor = UIColor.green
}
allHobbiesCV.deselectItem(at: indexPath, animated: false)
for cell in myHobbiesCV.visibleCells {
cell.backgroundColor = UIColor.white
}
myHobbiesArraySelected.removeAll()
//myHobbiesCV.reloadData() // needed?
}
// My Hobbies
else {
let item = myHobbiesArray[indexPath.item]
let cell = myHobbiesCV.cellForItem(at: indexPath) as! MyHobbiesCell
if let itemIndex = myHobbiesArraySelected.index(of:item) {
// DID DESELECT
myHobbiesArraySelected.remove(at: itemIndex)
cell.backgroundColor = UIColor.white
}
else {
// DID SELECT
myHobbiesArraySelected.insert(item, at: 0)
cell.backgroundColor = UIColor.red
}
myHobbiesCV.deselectItem(at: indexPath, animated: true)
}
}
```
**cellForItem**
```
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == allHobbiesCV {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ALL", for: indexPath) as! AllHobbiesCell
cell.allHobbiesCellLabel.text = allHobbiesArray[indexPath.item]
let allHobbies = allHobbiesArray[indexPath.item]
if allHobbiesArraySelected.index(of: allHobbies) != nil {
cell.backgroundColor = UIColor.green
}
else {
cell.backgroundColor = UIColor.brown
}
return cell
}
else { // myHobbiesCV
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MY", for: indexPath) as! MyHobbiesCell
cell.myHobbiesCellLabel.text = myHobbiesArray[indexPath.item]
let myHobbies = myHobbiesArray[indexPath.item]
if myHobbiesArraySelected.index(of: myHobbies) != nil {
cell.backgroundColor = UIColor.red
}
else {
cell.backgroundColor = UIColor.white
}
return cell
}
}
```
**numberOfItemsInSection**
```
if collectionView == allHobbiesCV {
return allHobbiesArray.count
}
else {
return myHobbiesArray.count
}
```
**Delete button**
```
@IBAction func deleteHobbyButtonPressed(_ sender: UIButton) {
print("all Hobbies - \(allHobbiesCV.indexPathsForSelectedItems!)")
if let selectedItemPaths = myHobbiesCV.indexPathsForSelectedItems {
var allItemIndexPaths = [IndexPath]()
var tempSelectedItems = Array(allHobbiesArraySelected) // Need to use a temporary copy otherwise the element indexes will change
for itemPath in selectedItemPaths {
let removeItem = allHobbiesArraySelected[itemPath.item]
if let removeIndex = tempSelectedItems.index(of: removeItem) {
print("if let removeIndex")
tempSelectedItems.remove(at: removeIndex)
}
if let allItemsIndex = allHobbiesArray.index(of: removeItem) {
print("if let allItemsIndex")
allItemIndexPaths.append(IndexPath(item: allItemsIndex, section: 0))
}
}
allHobbiesArraySelected = tempSelectedItems // Selected items array without the removed items
myHobbiesCV.deleteItems(at:selectedItemPaths)
myHobbiesCV.reloadData()
allHobbiesCV.reloadItems(at: allItemIndexPaths) // Reload to update the selected status
}
}
```
The problem now is nothing is evaluating in the remove button. That first print statement always returns an empty array. And nothing prints in the if let check. Is there a way to use myHobbiesArraySelected instead of indexPathsForSelectedItems? (Since I'm saving the selected items in an array now) Along with the original intended functionality of deselecting the cell in allHobbiesCV if it was manually deleted in myHobbiesCV.
Thanks friends. | 2017/03/29 | [
"https://Stackoverflow.com/questions/43099851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220994/"
] | You can use Information\_schema or sys.columns
```
select * from information_schema.columns where table_name = 'card' and table_schema = 'schema1'
except
select * from information_schema.columns where table_name = 'card' and table_schema = 'schema2'
```
--With full join
```
select * from information_schema.columns t1
full join information_schema.columns t2
on t1.table_catalog=t2.table_catalog
and t1.column_name = t2.column_name
where
t1.table_name = 'card' and t2.table_name = 'card'
and t1.table_schema = 'schema1' and t2.table_schema = 'schema2'
and (t1.column_name is null or t2.column_name is null)
``` | I tried to add one column in my second schema and wrote following query adn I got the output what I want.
```
select * from information_schema.columns t1 where t1.table_name = 'card' and t1.table_schema = 'Custom' and
t1.column_name not in(select t2.column_name from information_schema.columns t2 where t2.table_name = 'card' and t2.table_schema = 'boston' )
``` |
10,848 | I'm building a MOC to scale with the [Saturn V set](https://rads.stackoverflow.com/amzn/click/B071G3QMS2) and am having trouble figuring out how tall the 1st stage engines are but the entire thing would be really helpful! Thanks! | 2019/01/12 | [
"https://bricks.stackexchange.com/questions/10848",
"https://bricks.stackexchange.com",
"https://bricks.stackexchange.com/users/11182/"
] | I've been contemplating this question for quite a while. In the [great tradition](https://bricks.stackexchange.com/a/1953/6174) of this site I felt this needed practical verification. I decided to make a ruler based on scaling up set [5005107, LEGO Buildable Ruler](https://brickset.com/sets/5005107-1/LEGO-Buildable-Ruler) to measure the Saturn V myself.
tl;dr
=====
```
| STAGE | Studs Tall | Bricks Tall |
|-------------------|------------|-------------|
| S-IC first stage | 52.2 studs | 43.8 bricks |
| S-II second stage | 33.8 studs | 28.3 bricks |
| S-IVB third stage | 50.5 studs | 42.1 bricks |
```
My conversions are not perfect based on [the calculator](http://studs.sariel.pl/), but they're close enough that I don't think I messed up anything.
Overall
=======
As we know, this is a huge set. I needed my ruler to be >32 studs tall to measure any of the stages. Here's my setup:

I've included pictures of the bottoms of the rockets since they nest somewhat so you can see how tall the rocket engine part ends up being versus the entire shell of the rocket.
S-IC first stage
================
The bottom:

The top:

I read that as 52.2 studs or 43.8 bricks tall.
S-II second stage
=================
The bottom:

The top:

I read that as 33.8 studs or 28.3 bricks high.
S-IVB third stage
=================
The bottom:

The top:

I read that as 50.5 studs or 42.1 bricks tall. | On the box the entire rocket is shown to be 100cm. I just measured the first stage, that is 40,7cm.
Else you can go to service.lego.com and download the instructions aand start counting/calculating (the studs face in different directions, so you can't just count). |
10,848 | I'm building a MOC to scale with the [Saturn V set](https://rads.stackoverflow.com/amzn/click/B071G3QMS2) and am having trouble figuring out how tall the 1st stage engines are but the entire thing would be really helpful! Thanks! | 2019/01/12 | [
"https://bricks.stackexchange.com/questions/10848",
"https://bricks.stackexchange.com",
"https://bricks.stackexchange.com/users/11182/"
] | Other answers seem to be focused on stage dimensions, rather than engines as asked in the question, so I'll address that.
Scaling is a pretty easy math. Stud is 8 mm and brick height is 9.6 mm. Given that the entire 100 cm (1000 mm) Saturn V rocket is 125 studs or 104 bricks and half plate high (104.166667).
The real Saturn V is 363.0 ft (110.6 m) tall. So given the height of a rocket of 1 meter scale is very easy to calculate as 1/110.6 or rounded to 1/111.
Now let's get to the size of Rocketdyne F-1 engines made from LEGO. The following image shows side engines are made of just 4 parts (height wise) and are 1+2+1/3+2=5 and 1/3 bricks tall (or 16 plates). Converting to studs we get 6.4 studs and in metric it is 51.2 mm.
[](https://i.stack.imgur.com/HaA08.jpg) | On the box the entire rocket is shown to be 100cm. I just measured the first stage, that is 40,7cm.
Else you can go to service.lego.com and download the instructions aand start counting/calculating (the studs face in different directions, so you can't just count). |
10,848 | I'm building a MOC to scale with the [Saturn V set](https://rads.stackoverflow.com/amzn/click/B071G3QMS2) and am having trouble figuring out how tall the 1st stage engines are but the entire thing would be really helpful! Thanks! | 2019/01/12 | [
"https://bricks.stackexchange.com/questions/10848",
"https://bricks.stackexchange.com",
"https://bricks.stackexchange.com/users/11182/"
] | I've been contemplating this question for quite a while. In the [great tradition](https://bricks.stackexchange.com/a/1953/6174) of this site I felt this needed practical verification. I decided to make a ruler based on scaling up set [5005107, LEGO Buildable Ruler](https://brickset.com/sets/5005107-1/LEGO-Buildable-Ruler) to measure the Saturn V myself.
tl;dr
=====
```
| STAGE | Studs Tall | Bricks Tall |
|-------------------|------------|-------------|
| S-IC first stage | 52.2 studs | 43.8 bricks |
| S-II second stage | 33.8 studs | 28.3 bricks |
| S-IVB third stage | 50.5 studs | 42.1 bricks |
```
My conversions are not perfect based on [the calculator](http://studs.sariel.pl/), but they're close enough that I don't think I messed up anything.
Overall
=======
As we know, this is a huge set. I needed my ruler to be >32 studs tall to measure any of the stages. Here's my setup:

I've included pictures of the bottoms of the rockets since they nest somewhat so you can see how tall the rocket engine part ends up being versus the entire shell of the rocket.
S-IC first stage
================
The bottom:

The top:

I read that as 52.2 studs or 43.8 bricks tall.
S-II second stage
=================
The bottom:

The top:

I read that as 33.8 studs or 28.3 bricks high.
S-IVB third stage
=================
The bottom:

The top:

I read that as 50.5 studs or 42.1 bricks tall. | Other answers seem to be focused on stage dimensions, rather than engines as asked in the question, so I'll address that.
Scaling is a pretty easy math. Stud is 8 mm and brick height is 9.6 mm. Given that the entire 100 cm (1000 mm) Saturn V rocket is 125 studs or 104 bricks and half plate high (104.166667).
The real Saturn V is 363.0 ft (110.6 m) tall. So given the height of a rocket of 1 meter scale is very easy to calculate as 1/110.6 or rounded to 1/111.
Now let's get to the size of Rocketdyne F-1 engines made from LEGO. The following image shows side engines are made of just 4 parts (height wise) and are 1+2+1/3+2=5 and 1/3 bricks tall (or 16 plates). Converting to studs we get 6.4 studs and in metric it is 51.2 mm.
[](https://i.stack.imgur.com/HaA08.jpg) |
36,346,597 | I want to use numpy for a program I have to run and I want to do it in the IDLE IDE. I have installed the numpy binary from online, but when I try running "import numpy" and then some numpy commands in my script, but the python shell returns an error saying
```
Traceback (most recent call last):
File "/Users/Admin/Desktop/NumpyTest.py", line 1, in <module>
import numpy as np
ImportError: No module named numpy
```
I have tried using pip to install numpy, but when I run `pip install numpy` in the bash shell, it says
```
Requirement already satisfied (use --upgrade to upgrade):
numpy in ./anaconda/lib/python2.7/site-packages
```
I have downloaded Anaconda, which I can use the numpy distribution in, but I would really like to do it in IDLE.
What should I do to get numpy working in IDLE? Do I have to save it somewhere?
p.s. I am running OsX 10.10.5 Yosemite | 2016/04/01 | [
"https://Stackoverflow.com/questions/36346597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6142712/"
] | The title is misleading in the following sense. You do not want to import a module to IDLE. You want to import it to the python that is running your code. When running IDLE, this currently is the same python running IDLE. To find which python is running, the following should work anywhere on any recent python, either directly or in an IDE:
```
import sys; print(sys.executable)
```
Running this in IDLE on my Windows machine, I get
```
C:\Programs\Python36\pythonw.exe
```
(The `w` suffix is a Windows-specific variant binary for running GUI programs *without* an empty console window popping up. It should be omitted in what follows.)
To import a module to a particular python, it must be installed for that particular python. The easiest way to do that is to run pip with that particular python in a console. For instance, given the executable above:
```
C:\Programs\Python36> python -m pip install numpy
```
On \*nix, one may have to first run, I believe, `python -m ensurepip` to install pip itself for that python.
About `import pip; pip.main`: pip is designed as a command line utility that initializes, performs one function, and exits. main() is an intentionally undocumented internal implementation detail. The author of pip discourages its use as it is designed for one call followed by program exit. Multiple calls will not work right when internal data get out of sync with installed files. | To install packages without affecting anaconda's configuration you can use [pip from within IDLE](https://stackoverflow.com/questions/12332975/installing-python-module-within-code):
```
import pip
pip.main(["install","numpy"])
```
In later versions this is no longer directly exposed, [since doing this in production code is bad.](https://pip.pypa.io/en/latest/user_guide/#using-pip-from-your-program) but you can still import the internals to install a module.
```
from pip._internal.main import main as pip_main
pip_main(["install","numpy"])
```
Although because IDLE can be a little slow with refresh rate (at least it is on my mac) it can be a great speed boost to hide the output until the end:
```
import sys
import pip
import io
stdout_real = sys.stdout
sys.stdout = io.StringIO()
try:
pip.main(["install","kfksnaf"])
finally:
stdout_real.write(sys.stdout.getvalue())
sys.stdout = stdout_real
```
note that this means that all standard output will be displayed after the error text which might be confusing if something goes wrong so do try it normally first and only do this if it lags badly.
On the other hand, it seems like anaconda has commandeered a lot of the functionalities of the python installed from python.org, to reduce it's impact on your machine you should take a look at [Use Default Python Rather than Anaconda Installation When Called from the Terminal](https://stackoverflow.com/questions/24664435/use-default-python-rather-than-anaconda-installation-when-called-from-the-termin) although this might then break functionalities of anaconda which may then in turn make it difficult to switch back if you want to do so. |
36,346,597 | I want to use numpy for a program I have to run and I want to do it in the IDLE IDE. I have installed the numpy binary from online, but when I try running "import numpy" and then some numpy commands in my script, but the python shell returns an error saying
```
Traceback (most recent call last):
File "/Users/Admin/Desktop/NumpyTest.py", line 1, in <module>
import numpy as np
ImportError: No module named numpy
```
I have tried using pip to install numpy, but when I run `pip install numpy` in the bash shell, it says
```
Requirement already satisfied (use --upgrade to upgrade):
numpy in ./anaconda/lib/python2.7/site-packages
```
I have downloaded Anaconda, which I can use the numpy distribution in, but I would really like to do it in IDLE.
What should I do to get numpy working in IDLE? Do I have to save it somewhere?
p.s. I am running OsX 10.10.5 Yosemite | 2016/04/01 | [
"https://Stackoverflow.com/questions/36346597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6142712/"
] | To install packages without affecting anaconda's configuration you can use [pip from within IDLE](https://stackoverflow.com/questions/12332975/installing-python-module-within-code):
```
import pip
pip.main(["install","numpy"])
```
In later versions this is no longer directly exposed, [since doing this in production code is bad.](https://pip.pypa.io/en/latest/user_guide/#using-pip-from-your-program) but you can still import the internals to install a module.
```
from pip._internal.main import main as pip_main
pip_main(["install","numpy"])
```
Although because IDLE can be a little slow with refresh rate (at least it is on my mac) it can be a great speed boost to hide the output until the end:
```
import sys
import pip
import io
stdout_real = sys.stdout
sys.stdout = io.StringIO()
try:
pip.main(["install","kfksnaf"])
finally:
stdout_real.write(sys.stdout.getvalue())
sys.stdout = stdout_real
```
note that this means that all standard output will be displayed after the error text which might be confusing if something goes wrong so do try it normally first and only do this if it lags badly.
On the other hand, it seems like anaconda has commandeered a lot of the functionalities of the python installed from python.org, to reduce it's impact on your machine you should take a look at [Use Default Python Rather than Anaconda Installation When Called from the Terminal](https://stackoverflow.com/questions/24664435/use-default-python-rather-than-anaconda-installation-when-called-from-the-termin) although this might then break functionalities of anaconda which may then in turn make it difficult to switch back if you want to do so. | I was getting error
>
>
> >
> >
> > >
> > > import numpy as npa
> > >
> > >
> > >
> >
> >
> >
>
>
>
Traceback (most recent call last):
File "", line 1, in
import numpy as np
ModuleNotFoundError: No module named 'numpy'
I went to below path from cmd (admin)
C:\Users\\AppData\Local\Programs\Python\Python38-32\Scripts
And then ran command :
pip install numpy
this solves my problem. You can also run below command in order to upgrade pip
python -m pip install --upgrade pip
After installing i can see "f2py.exe" under C:\Users\\AppData\Local\Programs\Python\Python38-32\Scripts |
36,346,597 | I want to use numpy for a program I have to run and I want to do it in the IDLE IDE. I have installed the numpy binary from online, but when I try running "import numpy" and then some numpy commands in my script, but the python shell returns an error saying
```
Traceback (most recent call last):
File "/Users/Admin/Desktop/NumpyTest.py", line 1, in <module>
import numpy as np
ImportError: No module named numpy
```
I have tried using pip to install numpy, but when I run `pip install numpy` in the bash shell, it says
```
Requirement already satisfied (use --upgrade to upgrade):
numpy in ./anaconda/lib/python2.7/site-packages
```
I have downloaded Anaconda, which I can use the numpy distribution in, but I would really like to do it in IDLE.
What should I do to get numpy working in IDLE? Do I have to save it somewhere?
p.s. I am running OsX 10.10.5 Yosemite | 2016/04/01 | [
"https://Stackoverflow.com/questions/36346597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6142712/"
] | The title is misleading in the following sense. You do not want to import a module to IDLE. You want to import it to the python that is running your code. When running IDLE, this currently is the same python running IDLE. To find which python is running, the following should work anywhere on any recent python, either directly or in an IDE:
```
import sys; print(sys.executable)
```
Running this in IDLE on my Windows machine, I get
```
C:\Programs\Python36\pythonw.exe
```
(The `w` suffix is a Windows-specific variant binary for running GUI programs *without* an empty console window popping up. It should be omitted in what follows.)
To import a module to a particular python, it must be installed for that particular python. The easiest way to do that is to run pip with that particular python in a console. For instance, given the executable above:
```
C:\Programs\Python36> python -m pip install numpy
```
On \*nix, one may have to first run, I believe, `python -m ensurepip` to install pip itself for that python.
About `import pip; pip.main`: pip is designed as a command line utility that initializes, performs one function, and exits. main() is an intentionally undocumented internal implementation detail. The author of pip discourages its use as it is designed for one call followed by program exit. Multiple calls will not work right when internal data get out of sync with installed files. | I was getting error
>
>
> >
> >
> > >
> > > import numpy as npa
> > >
> > >
> > >
> >
> >
> >
>
>
>
Traceback (most recent call last):
File "", line 1, in
import numpy as np
ModuleNotFoundError: No module named 'numpy'
I went to below path from cmd (admin)
C:\Users\\AppData\Local\Programs\Python\Python38-32\Scripts
And then ran command :
pip install numpy
this solves my problem. You can also run below command in order to upgrade pip
python -m pip install --upgrade pip
After installing i can see "f2py.exe" under C:\Users\\AppData\Local\Programs\Python\Python38-32\Scripts |
85,036 | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | Although not free I have had good experience using Red-Gates [SQL Compare tool](http://www.red-gate.com/products/SQL_Compare/index.htm). It worked for me in the past. They have a free trial available which may be good enough to solve your current issue. | There are several database compare tools out there. One that I've always like is SQLCompare by [Red Gate](http://www.red-gate.com).
You can also try using:
```
SELECT name
FROM sys.objects
WHERE modify_date > @cutoffdate
```
In SQL 2000 that wouldn't have always worked, because using ALTER didn't update the date correctly, but in 2005 I believe that problem is fixed.
I use a SQL compare tool myself though, so I can't vouch for that method 100% |
85,036 | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | you can also use the following code snipet
```
USE AdventureWorks2008;
GO
SELECT SprocName=name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
AND name = 'uspUpdateEmployeeHireInfo'
GO
``` | There are several database compare tools out there. One that I've always like is SQLCompare by [Red Gate](http://www.red-gate.com).
You can also try using:
```
SELECT name
FROM sys.objects
WHERE modify_date > @cutoffdate
```
In SQL 2000 that wouldn't have always worked, because using ALTER didn't update the date correctly, but in 2005 I believe that problem is fixed.
I use a SQL compare tool myself though, so I can't vouch for that method 100% |
85,036 | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | Although not free I have had good experience using Red-Gates [SQL Compare tool](http://www.red-gate.com/products/SQL_Compare/index.htm). It worked for me in the past. They have a free trial available which may be good enough to solve your current issue. | You can use following type of query to find modified stored procedures , you can use any number then 7 as per your needs
```
SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,modify_date, GETDATE()) < 7
``` |
85,036 | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | There are some special cases where scripts might not give optimal results.
One is deleting stored procedures or other objects in dev environment – you won’t catch this using system views because object won’t exist there any longer.
Also, I’m not really sure this approach can work on changes such as permissions and similar.
In such cases its best to use some third party tool just to double check nothing is missed.
I’ve successfully used [ApexSQL Diff](http://www.apexsql.com/sql_tools_diff.aspx) in the past for similar tasks and it worked really good on large databases with 1000+ objects but you can’t go wrong with SQL Compare that’s already mentioned here or basically any other tool that exists on the market.
Disclaimer: I’m not affiliated with any of the vendors I’m mentioning here but I do use both set of tools (Apex and RG) in the company I work for. | Although not free I have had good experience using Red-Gates [SQL Compare tool](http://www.red-gate.com/products/SQL_Compare/index.htm). It worked for me in the past. They have a free trial available which may be good enough to solve your current issue. |
85,036 | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | instead of using sysobjects which is not recommended anymore use sys.procedures
```
select name,create_date,modify_date
from sys.procedures
order by modify_date desc
```
you can do the where clause yourself but this will list it in order of modification date descending | There are some special cases where scripts might not give optimal results.
One is deleting stored procedures or other objects in dev environment – you won’t catch this using system views because object won’t exist there any longer.
Also, I’m not really sure this approach can work on changes such as permissions and similar.
In such cases its best to use some third party tool just to double check nothing is missed.
I’ve successfully used [ApexSQL Diff](http://www.apexsql.com/sql_tools_diff.aspx) in the past for similar tasks and it worked really good on large databases with 1000+ objects but you can’t go wrong with SQL Compare that’s already mentioned here or basically any other tool that exists on the market.
Disclaimer: I’m not affiliated with any of the vendors I’m mentioning here but I do use both set of tools (Apex and RG) in the company I work for. |
85,036 | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | instead of using sysobjects which is not recommended anymore use sys.procedures
```
select name,create_date,modify_date
from sys.procedures
order by modify_date desc
```
you can do the where clause yourself but this will list it in order of modification date descending | you can also use the following code snipet
```
USE AdventureWorks2008;
GO
SELECT SprocName=name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
AND name = 'uspUpdateEmployeeHireInfo'
GO
``` |
85,036 | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | You can execute this query to find all stored procedures modified in the last x number of days:
```
SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,modify_date, GETDATE()) < X
``` | You can use following type of query to find modified stored procedures , you can use any number then 7 as per your needs
```
SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,modify_date, GETDATE()) < 7
``` |
85,036 | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | There are some special cases where scripts might not give optimal results.
One is deleting stored procedures or other objects in dev environment – you won’t catch this using system views because object won’t exist there any longer.
Also, I’m not really sure this approach can work on changes such as permissions and similar.
In such cases its best to use some third party tool just to double check nothing is missed.
I’ve successfully used [ApexSQL Diff](http://www.apexsql.com/sql_tools_diff.aspx) in the past for similar tasks and it worked really good on large databases with 1000+ objects but you can’t go wrong with SQL Compare that’s already mentioned here or basically any other tool that exists on the market.
Disclaimer: I’m not affiliated with any of the vendors I’m mentioning here but I do use both set of tools (Apex and RG) in the company I work for. | There are several database compare tools out there. One that I've always like is SQLCompare by [Red Gate](http://www.red-gate.com).
You can also try using:
```
SELECT name
FROM sys.objects
WHERE modify_date > @cutoffdate
```
In SQL 2000 that wouldn't have always worked, because using ALTER didn't update the date correctly, but in 2005 I believe that problem is fixed.
I use a SQL compare tool myself though, so I can't vouch for that method 100% |
85,036 | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | You can execute this query to find all stored procedures modified in the last x number of days:
```
SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,modify_date, GETDATE()) < X
``` | Although not free I have had good experience using Red-Gates [SQL Compare tool](http://www.red-gate.com/products/SQL_Compare/index.htm). It worked for me in the past. They have a free trial available which may be good enough to solve your current issue. |
85,036 | I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?
I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. | 2008/09/17 | [
"https://Stackoverflow.com/questions/85036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137/"
] | There are some special cases where scripts might not give optimal results.
One is deleting stored procedures or other objects in dev environment – you won’t catch this using system views because object won’t exist there any longer.
Also, I’m not really sure this approach can work on changes such as permissions and similar.
In such cases its best to use some third party tool just to double check nothing is missed.
I’ve successfully used [ApexSQL Diff](http://www.apexsql.com/sql_tools_diff.aspx) in the past for similar tasks and it worked really good on large databases with 1000+ objects but you can’t go wrong with SQL Compare that’s already mentioned here or basically any other tool that exists on the market.
Disclaimer: I’m not affiliated with any of the vendors I’m mentioning here but I do use both set of tools (Apex and RG) in the company I work for. | You can use following type of query to find modified stored procedures , you can use any number then 7 as per your needs
```
SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,modify_date, GETDATE()) < 7
``` |
6,753,076 | I have a classlibrary project, then add a new empty report .rdlc, when compiled throw this error
>
> "The report definition is not valid. Details: the report definition has an invalid target namespace 'http://schemas.microsoft.sqlserver.reporting/2008/01/reportdefinition' which cannot be upgraded"
>
>
>
This cannot be the reportviewer because is a dll, what should do i for fix it?
the reportviewer 2010 is also installed | 2011/07/19 | [
"https://Stackoverflow.com/questions/6753076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852719/"
] | I had a similar issue today and I found solution [here](http://social.msdn.microsoft.com/Forums/en-US/vsreportcontrols/thread/47ecd315-6372-46cf-b319-df098334fc74). Thanks Jim Lafler.
My "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\ReportingServices\Microsoft.ReportingServices.targets" file had changed
In the top was:
```
<UsingTask TaskName="Microsoft.Reporting.RdlCompile" AssemblyName="Microsoft.ReportViewer.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
```
and it should have been:
```
<UsingTask TaskName="Microsoft.Reporting.RdlCompile" AssemblyName="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
``` | Try changing the namespace. Open your **.rdlc** file in text/xml editor and change the namespace to
```
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"
``` |
6,286,610 | I downloaded Firefox 4 today, and realized my site does not work as expected. As I looked for answers over the internet, I found solutions that called for adding the inline script by way of
`document.write('<script src="path/js/inlineScript.js" type="text/javascript"><\/script>')`.
I copied and pasted all of my inline code to an external file, and this is how I am adding the inline script now (working in all browsers, and partially in firefox 4): from comments inquiry regarding the markup, I here is the link: <http://filetaxes4free.com/temporary/index.php>
```
<script language="JavaScript">
document.write('
<script src="path/js/inlineScript.js"
type="text/javascript">
<\/script>'
);
</script>
```
I am using jQuery 1.6.1, jQuery tabs (in code you can see they are set to rotate and fadein/fadeout through opacity toggle) Some of the jQuery is working and some is not; the change of the file name when event mouseover and mouseout is not working, and the animation on when event mouseover and mouseout is not working either (this is the content of inlineScript.js file)
```
jQuery(document).ready( function() {
jQuery( "#tabs" ).tabs().tabs({
fx: { opacity: 'toggle', duration: 1000 }}
).tabs('rotate', 3500, false);
jQuery("ul#frontModule li a img").live('mouseover mouseout', function() {
var fileName = jQuery(this).attr('src').search("-active");
if (event.type == 'mouseover' && fileName == -1 ) {
jQuery(this).attr("src", jQuery(this).attr("src")
.replace(".png","-active.png"));
}
else {
jQuery(this).attr("src", jQuery(this).attr("src")
.replace("-active.png",".png"));
}
});
/* LOGO anitmated text*/
jQuery( "#logo" ).airport(
[ 'small business web design',
'online marketing',
'search engine optimization',
'websonalized-com']
);
//menu animation
jQuery('#rightBody .menu li a').live('mouseover mouseout', function(){
if ( event.type == 'mouseover' )
jQuery(this).animate({ marginLeft: "15px" }, 500 );
else
jQuery(this).animate({marginLeft: "0" }, 500 );
});
//css for IE css3pie.com
if (window.PIE) {
//jQuery('.rounded').each(function() {
//PIE.attach(this);
//});
jQuery('.roundRightEI').each(function() {
PIE.attach(this);
});
}//end IE scripts
});
```
What changes do I need to make to make for this script to work in Firefox 4 | 2011/06/08 | [
"https://Stackoverflow.com/questions/6286610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/552085/"
] | Handling (to me) means taking appropriate action to resume the flow of your application. If you rethrow the exception, then you haven't handled it. Logging would be one case where you might rethrow an exception.
An example of a exception that can be handled: you are running a service that notifies a particular user of an event. You try to use a web service to send a SMS message, this gives an exception (server down, account closed, whatever), so as a fallback you send an email message, that fails with another exception, so you fall back to trying to make a voice call. That succeeds and your customer gets notified of whatever he wanted to know.
An example of an exception that can sometimes be handled and other times not: you get an System Insufficient memory exception. Sometimes you know that you have a lock on something that is large but non-critical, which you could release and then retry, but typically everything that you have an active reference to is something that must have, in which case there's nothing you can really do to recover.
Note that quite frequently, handling means simply returning false for a function that was asked to do something and for which a success/failure is returned. This isn't as useless as it might at first appear, consider this scenario: you make a change to a file, and then tell the application to save the changes. The disk is full or unavailable for some reason. Either will cause an exception. When saving you have isDirty = savefile() , the exception happens inside savefile and is "handled" by savefile by setting the result to false. This allows the application to know (and to show to the user) that the file hasn't been saved. | Outside of the key framework exceptions which cannot be caught by the CLR (StackOverflow, OutOfMemory, etc) there are several exceptions that generally should not be caught as they represent developer errors that should be addressed during development. While logging the exceptions can be seen as a mechanism to "handle" the exception, it's only useful if the log files are reviewed for errors.
In general, exceptions like ArgumentNullException, ArgumentException, NullReferenceException, etc should not be caught by developers explicitly, and should be allowed to bubble up so that they can be identified and fixed. |
19,710 | How do I add a class to the comment submit button? The simplified function
`comment_form(array('id_submit'=>'buttonPro'));` obviously only changes the id and `class_submit` does not seem to exist.
I have read through both [Otto's](http://ottopress.com/2010/wordpress-3-0-theme-tip-the-comment-form/) and [Beau's](http://www.slideshare.net/beaulebens/hooking-into-comments-5047868) writeups but to no avail. | 2011/06/10 | [
"https://wordpress.stackexchange.com/questions/19710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1057/"
] | If you check out the source of the function `comment_form()`, you'll see it doesn't even print a class on the input;
```
<input name="submit" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" />
```
I'm guessing you need to add a class for styling? Why not modify your CSS to just;
```
input.submit, #buttonPro {
/* some awesome style */
}
```
Otherwise I guess the 'easiest' solution would be to simply copy the function to your `functions.php`, rename it, add in a class argument & print, and use that instead - which you can [find here](http://pastebin.com/PDwAbrQb) ;) | I was searching for the same solution and at last i found the solution, the below code worked perfectly for me, I wanted to add "btn btn-primary" class to the submit button in comment form.
```
ob_start();
comment_form( $args );
$form = ob_get_clean();
$form = str_replace('class="comment-form"','class="comment-form"', $form);
echo str_replace('id="submit"','class="btn btn-primary"', $form);
```
the $args i used are
```
$args = array(
'comment_field' => '<p class="comment-form-comment"><label for="comment">Comment</label> <textarea class="form-control" id="comment" name="comment" cols="35" rows="12" aria-required="true"></textarea></p>',
'fields' => array(
'author' => '<p class="comment-form-author"><label for="author">Name <span class="required">*</span></label> <input class="form-control input-comment-author" id="author" name="author" type="text" value="" size="30" aria-required="true"></p>',
'email' => '<p class="comment-form-email"><label for="email">Email <span class="required">*</span></label> <input class="form-control input-comment-email" id="email" name="email" type="text" value="" size="30" aria-required="true"></p>',
'url' => '<p class="comment-form-url"><label for="url">Website</label> <input class="form-control input-comment-url" id="url" name="url" type="text" value="" size="30"></p>',
),
'cancel_reply_link' => '<button class="btn btn-danger btn-xs">Cancel reply</button>',
'label_submit' => 'Post Comment',);
``` |
19,710 | How do I add a class to the comment submit button? The simplified function
`comment_form(array('id_submit'=>'buttonPro'));` obviously only changes the id and `class_submit` does not seem to exist.
I have read through both [Otto's](http://ottopress.com/2010/wordpress-3-0-theme-tip-the-comment-form/) and [Beau's](http://www.slideshare.net/beaulebens/hooking-into-comments-5047868) writeups but to no avail. | 2011/06/10 | [
"https://wordpress.stackexchange.com/questions/19710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1057/"
] | I'm working with the Foundation framework as well. I've found that the easiest way to add a class to a non-filterable element is to do it with jQuery.
```
jQuery(document).ready(function($) { //noconflict wrapper
$('input#submit').addClass('button');
});//end noconflict
``` | I suggest those who have this problem to set a style for "post-comment" id, like what i did:
```
#post-comment {
background: none repeat scroll 0 0 transparent;
border: 1px solid #FFFFFF;
padding: 8px 20px;
float: left;}
```
good luck! :) |
19,710 | How do I add a class to the comment submit button? The simplified function
`comment_form(array('id_submit'=>'buttonPro'));` obviously only changes the id and `class_submit` does not seem to exist.
I have read through both [Otto's](http://ottopress.com/2010/wordpress-3-0-theme-tip-the-comment-form/) and [Beau's](http://www.slideshare.net/beaulebens/hooking-into-comments-5047868) writeups but to no avail. | 2011/06/10 | [
"https://wordpress.stackexchange.com/questions/19710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1057/"
] | From WordPress Version 4.1 ([trac ticket #20446](https://core.trac.wordpress.org/ticket/20446)) it's now added to pass your own class as an argument of `comment_form($args)` using `'class_submit'` array key:
```
$args = array( 'class_submit' => 'btn btn-default' );
```
No need to do extra hard work. (Edited the Codex too) :) | Why do you need a class on the submit button? You can give it an ID, as you have discovered, and that's all you need for styling it.
```
comment_form(array('id_submit'=>'buttonPro'));
```
Then to style it:
```
input#buttonPro {...}
```
Simple. Or, if you prefer to use classes only for some reason:
```
.form-submit input {...}
```
There's no advantage I can see, from any angle, to putting a class on the comment form's submit button. |
19,710 | How do I add a class to the comment submit button? The simplified function
`comment_form(array('id_submit'=>'buttonPro'));` obviously only changes the id and `class_submit` does not seem to exist.
I have read through both [Otto's](http://ottopress.com/2010/wordpress-3-0-theme-tip-the-comment-form/) and [Beau's](http://www.slideshare.net/beaulebens/hooking-into-comments-5047868) writeups but to no avail. | 2011/06/10 | [
"https://wordpress.stackexchange.com/questions/19710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1057/"
] | Why do you need a class on the submit button? You can give it an ID, as you have discovered, and that's all you need for styling it.
```
comment_form(array('id_submit'=>'buttonPro'));
```
Then to style it:
```
input#buttonPro {...}
```
Simple. Or, if you prefer to use classes only for some reason:
```
.form-submit input {...}
```
There's no advantage I can see, from any angle, to putting a class on the comment form's submit button. | I'm going to reply (late) since I was looking for an answer to this and decided to tackle it myself.
First, to answer the question "why add a class?"... In my case, I chose to use a UI framework called [Foundation](http://foundation.zurb.com/) to design my most recent theme for my personal blog. I chose it precisely because I like its [style for buttons](http://foundation.zurb.com/docs/buttons.php). However, it requires the developer to add a class to an `<input>` button, and I didn't realize that couldn't be done in WP until I was almost completely done with the theme!
So, here's what I did. I had to edit the `/wp-includes/comment-template.php` file, so use at your own risk because it could be wiped out during a WP upgrade.
---
After line `1540` (as of version 3.2.1) add the following line:
```
'class_submit' => 'submit',
```
Then change line `1576` to the following:
```
<input name="submit" class="<?php echo esc_attr( $args['class_submit'] ); ?>" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" />
```
---
Now you have a new default value called `class_submit` that can be included in the `$args` array parameter on the `comment_form()` function:
```
<?php comment_form(
array(
'class_submit' => __('XXX'),
)
); ?>
```
Happy Wording! |
19,710 | How do I add a class to the comment submit button? The simplified function
`comment_form(array('id_submit'=>'buttonPro'));` obviously only changes the id and `class_submit` does not seem to exist.
I have read through both [Otto's](http://ottopress.com/2010/wordpress-3-0-theme-tip-the-comment-form/) and [Beau's](http://www.slideshare.net/beaulebens/hooking-into-comments-5047868) writeups but to no avail. | 2011/06/10 | [
"https://wordpress.stackexchange.com/questions/19710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1057/"
] | If you check out the source of the function `comment_form()`, you'll see it doesn't even print a class on the input;
```
<input name="submit" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" />
```
I'm guessing you need to add a class for styling? Why not modify your CSS to just;
```
input.submit, #buttonPro {
/* some awesome style */
}
```
Otherwise I guess the 'easiest' solution would be to simply copy the function to your `functions.php`, rename it, add in a class argument & print, and use that instead - which you can [find here](http://pastebin.com/PDwAbrQb) ;) | I suggest those who have this problem to set a style for "post-comment" id, like what i did:
```
#post-comment {
background: none repeat scroll 0 0 transparent;
border: 1px solid #FFFFFF;
padding: 8px 20px;
float: left;}
```
good luck! :) |
19,710 | How do I add a class to the comment submit button? The simplified function
`comment_form(array('id_submit'=>'buttonPro'));` obviously only changes the id and `class_submit` does not seem to exist.
I have read through both [Otto's](http://ottopress.com/2010/wordpress-3-0-theme-tip-the-comment-form/) and [Beau's](http://www.slideshare.net/beaulebens/hooking-into-comments-5047868) writeups but to no avail. | 2011/06/10 | [
"https://wordpress.stackexchange.com/questions/19710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1057/"
] | I suggest those who have this problem to set a style for "post-comment" id, like what i did:
```
#post-comment {
background: none repeat scroll 0 0 transparent;
border: 1px solid #FFFFFF;
padding: 8px 20px;
float: left;}
```
good luck! :) | I'm going to reply (late) since I was looking for an answer to this and decided to tackle it myself.
First, to answer the question "why add a class?"... In my case, I chose to use a UI framework called [Foundation](http://foundation.zurb.com/) to design my most recent theme for my personal blog. I chose it precisely because I like its [style for buttons](http://foundation.zurb.com/docs/buttons.php). However, it requires the developer to add a class to an `<input>` button, and I didn't realize that couldn't be done in WP until I was almost completely done with the theme!
So, here's what I did. I had to edit the `/wp-includes/comment-template.php` file, so use at your own risk because it could be wiped out during a WP upgrade.
---
After line `1540` (as of version 3.2.1) add the following line:
```
'class_submit' => 'submit',
```
Then change line `1576` to the following:
```
<input name="submit" class="<?php echo esc_attr( $args['class_submit'] ); ?>" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" />
```
---
Now you have a new default value called `class_submit` that can be included in the `$args` array parameter on the `comment_form()` function:
```
<?php comment_form(
array(
'class_submit' => __('XXX'),
)
); ?>
```
Happy Wording! |
19,710 | How do I add a class to the comment submit button? The simplified function
`comment_form(array('id_submit'=>'buttonPro'));` obviously only changes the id and `class_submit` does not seem to exist.
I have read through both [Otto's](http://ottopress.com/2010/wordpress-3-0-theme-tip-the-comment-form/) and [Beau's](http://www.slideshare.net/beaulebens/hooking-into-comments-5047868) writeups but to no avail. | 2011/06/10 | [
"https://wordpress.stackexchange.com/questions/19710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1057/"
] | I was searching for the same solution and at last i found the solution, the below code worked perfectly for me, I wanted to add "btn btn-primary" class to the submit button in comment form.
```
ob_start();
comment_form( $args );
$form = ob_get_clean();
$form = str_replace('class="comment-form"','class="comment-form"', $form);
echo str_replace('id="submit"','class="btn btn-primary"', $form);
```
the $args i used are
```
$args = array(
'comment_field' => '<p class="comment-form-comment"><label for="comment">Comment</label> <textarea class="form-control" id="comment" name="comment" cols="35" rows="12" aria-required="true"></textarea></p>',
'fields' => array(
'author' => '<p class="comment-form-author"><label for="author">Name <span class="required">*</span></label> <input class="form-control input-comment-author" id="author" name="author" type="text" value="" size="30" aria-required="true"></p>',
'email' => '<p class="comment-form-email"><label for="email">Email <span class="required">*</span></label> <input class="form-control input-comment-email" id="email" name="email" type="text" value="" size="30" aria-required="true"></p>',
'url' => '<p class="comment-form-url"><label for="url">Website</label> <input class="form-control input-comment-url" id="url" name="url" type="text" value="" size="30"></p>',
),
'cancel_reply_link' => '<button class="btn btn-danger btn-xs">Cancel reply</button>',
'label_submit' => 'Post Comment',);
``` | I suggest those who have this problem to set a style for "post-comment" id, like what i did:
```
#post-comment {
background: none repeat scroll 0 0 transparent;
border: 1px solid #FFFFFF;
padding: 8px 20px;
float: left;}
```
good luck! :) |
19,710 | How do I add a class to the comment submit button? The simplified function
`comment_form(array('id_submit'=>'buttonPro'));` obviously only changes the id and `class_submit` does not seem to exist.
I have read through both [Otto's](http://ottopress.com/2010/wordpress-3-0-theme-tip-the-comment-form/) and [Beau's](http://www.slideshare.net/beaulebens/hooking-into-comments-5047868) writeups but to no avail. | 2011/06/10 | [
"https://wordpress.stackexchange.com/questions/19710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1057/"
] | If you check out the source of the function `comment_form()`, you'll see it doesn't even print a class on the input;
```
<input name="submit" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" />
```
I'm guessing you need to add a class for styling? Why not modify your CSS to just;
```
input.submit, #buttonPro {
/* some awesome style */
}
```
Otherwise I guess the 'easiest' solution would be to simply copy the function to your `functions.php`, rename it, add in a class argument & print, and use that instead - which you can [find here](http://pastebin.com/PDwAbrQb) ;) | Why do you need a class on the submit button? You can give it an ID, as you have discovered, and that's all you need for styling it.
```
comment_form(array('id_submit'=>'buttonPro'));
```
Then to style it:
```
input#buttonPro {...}
```
Simple. Or, if you prefer to use classes only for some reason:
```
.form-submit input {...}
```
There's no advantage I can see, from any angle, to putting a class on the comment form's submit button. |
19,710 | How do I add a class to the comment submit button? The simplified function
`comment_form(array('id_submit'=>'buttonPro'));` obviously only changes the id and `class_submit` does not seem to exist.
I have read through both [Otto's](http://ottopress.com/2010/wordpress-3-0-theme-tip-the-comment-form/) and [Beau's](http://www.slideshare.net/beaulebens/hooking-into-comments-5047868) writeups but to no avail. | 2011/06/10 | [
"https://wordpress.stackexchange.com/questions/19710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1057/"
] | From WordPress Version 4.1 ([trac ticket #20446](https://core.trac.wordpress.org/ticket/20446)) it's now added to pass your own class as an argument of `comment_form($args)` using `'class_submit'` array key:
```
$args = array( 'class_submit' => 'btn btn-default' );
```
No need to do extra hard work. (Edited the Codex too) :) | I'm working with the Foundation framework as well. I've found that the easiest way to add a class to a non-filterable element is to do it with jQuery.
```
jQuery(document).ready(function($) { //noconflict wrapper
$('input#submit').addClass('button');
});//end noconflict
``` |
19,710 | How do I add a class to the comment submit button? The simplified function
`comment_form(array('id_submit'=>'buttonPro'));` obviously only changes the id and `class_submit` does not seem to exist.
I have read through both [Otto's](http://ottopress.com/2010/wordpress-3-0-theme-tip-the-comment-form/) and [Beau's](http://www.slideshare.net/beaulebens/hooking-into-comments-5047868) writeups but to no avail. | 2011/06/10 | [
"https://wordpress.stackexchange.com/questions/19710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1057/"
] | From WordPress Version 4.1 ([trac ticket #20446](https://core.trac.wordpress.org/ticket/20446)) it's now added to pass your own class as an argument of `comment_form($args)` using `'class_submit'` array key:
```
$args = array( 'class_submit' => 'btn btn-default' );
```
No need to do extra hard work. (Edited the Codex too) :) | I'm going to reply (late) since I was looking for an answer to this and decided to tackle it myself.
First, to answer the question "why add a class?"... In my case, I chose to use a UI framework called [Foundation](http://foundation.zurb.com/) to design my most recent theme for my personal blog. I chose it precisely because I like its [style for buttons](http://foundation.zurb.com/docs/buttons.php). However, it requires the developer to add a class to an `<input>` button, and I didn't realize that couldn't be done in WP until I was almost completely done with the theme!
So, here's what I did. I had to edit the `/wp-includes/comment-template.php` file, so use at your own risk because it could be wiped out during a WP upgrade.
---
After line `1540` (as of version 3.2.1) add the following line:
```
'class_submit' => 'submit',
```
Then change line `1576` to the following:
```
<input name="submit" class="<?php echo esc_attr( $args['class_submit'] ); ?>" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" />
```
---
Now you have a new default value called `class_submit` that can be included in the `$args` array parameter on the `comment_form()` function:
```
<?php comment_form(
array(
'class_submit' => __('XXX'),
)
); ?>
```
Happy Wording! |
57,160,129 | Is it possible to pass types as function aguments as in the below example?
```py
def test(*args):
'''decorator implementation with asserts'''
...
@test(str, int)
def fn1(ma_chaine, mon_entier):
return ma_chaine * mon_entier
@test(int, int)
def fn2(nb1, nb2):
return nb1 * nb2
```
or should I pass them as strings (eg `@test('str', 'int)`) and inside test function use them with `if` and `elif`? | 2019/07/23 | [
"https://Stackoverflow.com/questions/57160129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5539707/"
] | Does it work?
```
def test(obj, typ):
if isinstance(obj, typ):
print('Type Matches')
return True
return False
test('mystring', str)
"Type Matches"
```
Yes.
Should you do this?
[Probably not](https://stackoverflow.com/questions/19684434/best-way-to-check-function-arguments-in-python)
[And some more information of type checking](https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance) | Python function's argument doesn't care about its type.
You can pass the arguments of any type, and can check the type of arguments.
It is simple you can check the type of arguments what you get.
try
```
def fn1(ma_chaine, mon_entier):
if type(ma_chaine) == int && type(mon_entier) == int:
return ma_chaine * mon_entier
else:
raise TypeError("Arguments should be 'int' type. Got '{}' type and '{}' type.".format(type(ma_chaine), type(mon_entier))
``` |
208,124 | I've been searching and I cannot find an answer on any of these sites that will work. I want to copy all of the contents of [this folder](ftp://ftp.eso.org/pub/qfits/) to my server. Which Linux command should I use to do that? I don't want to manually run through all of the objects in that folder, one at a time per se. I've seen everything from scp to rsync, but can't get either to work.
Thanks, | 2015/06/07 | [
"https://unix.stackexchange.com/questions/208124",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/91274/"
] | you can use something like
```
cd directory-where-you-want-to-put-the-files
wget -r ftp://ftp.eso.org/pub/qfits/
``` | FTP?
```
#!/bin/sh
# ftp://ftp.eso.org/pub/qfits/
HOST='ftp.eso.org'
USER='anonymous'
PASSWD='<your.email.address>'
ftp -n $HOST <<EOF
quote USER $USER
quote PASS $PASSWD
prompt off
cd /pub/qfits
ls
mget *
quit
EOF
exit 0
``` |
64,631,230 | Is there a way to disable the SAS authorization scheme for a Logic App HTTP-trigger?
**In the documentation I read the following:**
"Inbound calls to a request endpoint can use only one authorization scheme, either SAS or Azure Active Directory Open Authentication. Although using one scheme doesn't disable the other scheme..." - Source: <https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-securing-a-logic-app>
**What I'm trying to do:**
I would like to disable the SAS authorization scheme. The logic app should not be triggered when the correct SAS parameter is provided. Or if SAS authorization can't be deactivated, than it should return an error in the case that SAS was used. Only OAuth authorization should give a valid result. Is this possible? | 2020/11/01 | [
"https://Stackoverflow.com/questions/64631230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14558025/"
] | We can't disable the SAS authorization in logic app and according to some research, it seems we can't have it return an error in the case that SAS was used. For your requirement of disable SAS, you can go to [feedback page](https://feedback.azure.com/forums/34192--general-feedback) and raise a post to suggest develop team add this feature. | The Logic App only accepts authorization through either SAS or OAuth and it returns an error when both a SAS-query-parameter and Authorization-header are provided. This means there are two scenario's:
* Authorization header is present, so authorization was acquired using OAuth
* Authorization header is missing, so authorization was acquired using SAS
By default the Logic App removes the Authorization header from the incoming request. You can by-pass this default behavior, by adding the **operationOption** to the Request trigger, see here:
<https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-workflow-actions-triggers#operation-options> |
9,700,360 | I've got liquid layout website that displays (8 x 240px) columns on 1920x1080px. There are no spaces between them. I added this to HEAD:
```
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=yes,width=960" >
<meta name="viewport" content="width=device-width; height=device-height;">
```
I tried different settings in above code but no matter what I do on iPhone 2G and 4S it always displays (4 x 240px) columns (480×320px and 960x640px resolutions).
I want it to display 3 or 2 columns because first column contain text and it's hardly readable now.
**I just want to divide width by two on iPhone. How can this be done?**
Furthermore, my website displays differently on iPhone (480x320px) and on desktop when I make browser 480x320px. Why is that? | 2012/03/14 | [
"https://Stackoverflow.com/questions/9700360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1074346/"
] | I haven´t used `meta viewport` before but it seems strange to set it twice and why use semicolon `;` in one and commas `,` in the other?
This seems more right to me but I haven´t tested it;
```
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1,maximum-scale=1,user-scalable=yes,width=960" />
```
Hope it helps! | The best way I've found is to use jquery to switch the viewport setting depending on screen size.
```
if($(window).width() >= 768) {
// Change viewport for smaller devices
$('meta[name=viewport]').attr('content','width=959');
}
``` |
22,597,229 | I need to make a kind of time line like [this one](http://www.vintagesynth.com/timeline/), the best I get is to vertically align the item:
**CSS**
```
ul {
list-style-type: none;
text-decoration: none;
color: #000;
background: none repeat scroll 0% 0% #EBEFF9;
border: 1px solid #D9E4FF;
border-radius: 4px;
display: block;
margin: 2px;
padding: 3px;
max-width:300px;
}
h3 {
color: #32ff12;
background: #000000;
max-width: 440px;
border-radius: 4px;
}
```
**HTML**
```
<h3>March</h3>
<ul>
<li>1 a 3 - Fronteira</li>
</ul>
<ul>
<li>10 a 13 -Belver</li>
</ul>
<h3>April</h3>
<ul>
<li>1 a 3 - Silves</li>
</ul>
<ul>
<li>10 a 13 -Porto</li>
</ul>
```
Any ideas of how to make this? | 2014/03/23 | [
"https://Stackoverflow.com/questions/22597229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can add a `div` "wrapper" to your `ul` ans set it to [`float: left;`](https://developer.mozilla.org/en-US/docs/Web/CSS/float). Something like [this](http://jsfiddle.net/sPp52/2/).
**HTML**
```
<div class="wrapper">
<h3>March</h3>
<!-- If you have to use a list, you can use it like this.
Each <li> is an item of the list <ul> -->
<ul>
<li>1 a 3 - Fronteira</li>
<li>10 a 13 -Belver</li>
</ul>
</div>
<div class="wrapper">
<h3>April</h3>
<ul>
<li>1 a 3 - Silves</li>
<li>10 a 13 -Porto</li>
</ul>
</div>
```
**CSS**
```
/* css reset */
* {
margin: 0;
padding: 0;
}
/* here you go */
.wrapper {
float: left;
margin-right: 12px;
width: 200px;
}
h3 {
color: #32ff12;
background: #000000;
border-radius: 4px;
padding-left: 4px;
}
li {
list-style-type: none;
text-decoration: none;
color: #000;
background: none repeat scroll 0% 0% #EBEFF9;
border: 1px solid #D9E4FF;
border-radius: 4px;
display: block;
width: 100%;
margin-top: 4px;
}
``` | Wrapping your elements in a floated div can get you there.
```
.box {float: left; margin-right: 5px;}
```
Full example: <http://jsfiddle.net/6hwAT/> |
22,597,229 | I need to make a kind of time line like [this one](http://www.vintagesynth.com/timeline/), the best I get is to vertically align the item:
**CSS**
```
ul {
list-style-type: none;
text-decoration: none;
color: #000;
background: none repeat scroll 0% 0% #EBEFF9;
border: 1px solid #D9E4FF;
border-radius: 4px;
display: block;
margin: 2px;
padding: 3px;
max-width:300px;
}
h3 {
color: #32ff12;
background: #000000;
max-width: 440px;
border-radius: 4px;
}
```
**HTML**
```
<h3>March</h3>
<ul>
<li>1 a 3 - Fronteira</li>
</ul>
<ul>
<li>10 a 13 -Belver</li>
</ul>
<h3>April</h3>
<ul>
<li>1 a 3 - Silves</li>
</ul>
<ul>
<li>10 a 13 -Porto</li>
</ul>
```
Any ideas of how to make this? | 2014/03/23 | [
"https://Stackoverflow.com/questions/22597229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can add a `div` "wrapper" to your `ul` ans set it to [`float: left;`](https://developer.mozilla.org/en-US/docs/Web/CSS/float). Something like [this](http://jsfiddle.net/sPp52/2/).
**HTML**
```
<div class="wrapper">
<h3>March</h3>
<!-- If you have to use a list, you can use it like this.
Each <li> is an item of the list <ul> -->
<ul>
<li>1 a 3 - Fronteira</li>
<li>10 a 13 -Belver</li>
</ul>
</div>
<div class="wrapper">
<h3>April</h3>
<ul>
<li>1 a 3 - Silves</li>
<li>10 a 13 -Porto</li>
</ul>
</div>
```
**CSS**
```
/* css reset */
* {
margin: 0;
padding: 0;
}
/* here you go */
.wrapper {
float: left;
margin-right: 12px;
width: 200px;
}
h3 {
color: #32ff12;
background: #000000;
border-radius: 4px;
padding-left: 4px;
}
li {
list-style-type: none;
text-decoration: none;
color: #000;
background: none repeat scroll 0% 0% #EBEFF9;
border: 1px solid #D9E4FF;
border-radius: 4px;
display: block;
width: 100%;
margin-top: 4px;
}
``` | You can right click on [that page](http://www.vintagesynth.com/timeline/) and select `View Page Source` menu (if you are using `Chrome`) or similar menus in other browsers. Then you could see the source code for CSS and Javascript internally provided by developer of that page. For example the css code for styling timeline is:
```
/* Timeline styling */#timeline { margin: 10px 0 8px 0; padding: 20px; overflow: auto; border: 2px solid #D9E4FF; font-size: 11px; cursor: move; background: url("images/vsewall.jpg") top right no-repeat;}.tl-events { width: 9600px; /*210 per column*/ list-style: none; padding: 0; margin: 0;}.tl-events li { float: left; width: 200px; margin-right: 10px;}.tl-events ul { list-style: none; margin: 0; padding: 0;}.tl-events ul li a { text-decoration: none; color: #000; background: #EBEFF9; border: 1px solid #D9E4FF; -moz-border-radius: 4px; border-radius: 4px; display: block; margin: 2px; padding: 3px;}.tl-events ul li a:hover,.tl-events ul li a:focus { outline: 0; background: #C2CCE4; border: 1px solid #B0BACF;}.tl-events ul li.highlight a { background-color: #FFFF99;}.tl-events li h3.next { background-color: #EBEFF9; font-size: 120%; padding: 3px 3px 3px 12px; margin-right: -20px; margin-left: 10px; background-image: url("images/arrow.png"); background-position: 103% 50%; background-repeat: no-repeat; overflow: hidden;
```
I copied and pasted this code from the link you mentioned. |
22,597,229 | I need to make a kind of time line like [this one](http://www.vintagesynth.com/timeline/), the best I get is to vertically align the item:
**CSS**
```
ul {
list-style-type: none;
text-decoration: none;
color: #000;
background: none repeat scroll 0% 0% #EBEFF9;
border: 1px solid #D9E4FF;
border-radius: 4px;
display: block;
margin: 2px;
padding: 3px;
max-width:300px;
}
h3 {
color: #32ff12;
background: #000000;
max-width: 440px;
border-radius: 4px;
}
```
**HTML**
```
<h3>March</h3>
<ul>
<li>1 a 3 - Fronteira</li>
</ul>
<ul>
<li>10 a 13 -Belver</li>
</ul>
<h3>April</h3>
<ul>
<li>1 a 3 - Silves</li>
</ul>
<ul>
<li>10 a 13 -Porto</li>
</ul>
```
Any ideas of how to make this? | 2014/03/23 | [
"https://Stackoverflow.com/questions/22597229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can add a `div` "wrapper" to your `ul` ans set it to [`float: left;`](https://developer.mozilla.org/en-US/docs/Web/CSS/float). Something like [this](http://jsfiddle.net/sPp52/2/).
**HTML**
```
<div class="wrapper">
<h3>March</h3>
<!-- If you have to use a list, you can use it like this.
Each <li> is an item of the list <ul> -->
<ul>
<li>1 a 3 - Fronteira</li>
<li>10 a 13 -Belver</li>
</ul>
</div>
<div class="wrapper">
<h3>April</h3>
<ul>
<li>1 a 3 - Silves</li>
<li>10 a 13 -Porto</li>
</ul>
</div>
```
**CSS**
```
/* css reset */
* {
margin: 0;
padding: 0;
}
/* here you go */
.wrapper {
float: left;
margin-right: 12px;
width: 200px;
}
h3 {
color: #32ff12;
background: #000000;
border-radius: 4px;
padding-left: 4px;
}
li {
list-style-type: none;
text-decoration: none;
color: #000;
background: none repeat scroll 0% 0% #EBEFF9;
border: 1px solid #D9E4FF;
border-radius: 4px;
display: block;
width: 100%;
margin-top: 4px;
}
``` | You should wrap your `UL`s with floated `DIV`s elements so that you will be able to enjoy from columns syle.
Take a look at my solution at jsFiddle: <http://jsfiddle.net/ynevet/cJDT9/>
**CSS:**
```
.float-left {
float: left;
margin-right: 12px;
}
ul {
list-style-type: none;
text-decoration: none;
color: #000;
background: none repeat scroll 0% 0% #EBEFF9;
border: 1px solid #D9E4FF;
border-radius: 4px;
display: block;
margin: 2px;
padding: 3px;
max-width:300px;
}
h3 {
color: #32ff12;
background: #000000;
max-width:440px;
border-radius: 4px;
}
```
**HTML:**
```
<div class="float-left">
<h3>March</h3>
<ul>
<li>1 a 3 - Fronteira</li>
</ul>
<ul>
<li>10 a 13 -Belver</li>
</ul>
</div>
<div class="float-left">
<h3>April</h3>
<ul>
<li>1 a 3 - Silves</li>
</ul>
<ul>
<li>10 a 13 -Porto</li>
</ul>
</div>
``` |
22,597,229 | I need to make a kind of time line like [this one](http://www.vintagesynth.com/timeline/), the best I get is to vertically align the item:
**CSS**
```
ul {
list-style-type: none;
text-decoration: none;
color: #000;
background: none repeat scroll 0% 0% #EBEFF9;
border: 1px solid #D9E4FF;
border-radius: 4px;
display: block;
margin: 2px;
padding: 3px;
max-width:300px;
}
h3 {
color: #32ff12;
background: #000000;
max-width: 440px;
border-radius: 4px;
}
```
**HTML**
```
<h3>March</h3>
<ul>
<li>1 a 3 - Fronteira</li>
</ul>
<ul>
<li>10 a 13 -Belver</li>
</ul>
<h3>April</h3>
<ul>
<li>1 a 3 - Silves</li>
</ul>
<ul>
<li>10 a 13 -Porto</li>
</ul>
```
Any ideas of how to make this? | 2014/03/23 | [
"https://Stackoverflow.com/questions/22597229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can add a `div` "wrapper" to your `ul` ans set it to [`float: left;`](https://developer.mozilla.org/en-US/docs/Web/CSS/float). Something like [this](http://jsfiddle.net/sPp52/2/).
**HTML**
```
<div class="wrapper">
<h3>March</h3>
<!-- If you have to use a list, you can use it like this.
Each <li> is an item of the list <ul> -->
<ul>
<li>1 a 3 - Fronteira</li>
<li>10 a 13 -Belver</li>
</ul>
</div>
<div class="wrapper">
<h3>April</h3>
<ul>
<li>1 a 3 - Silves</li>
<li>10 a 13 -Porto</li>
</ul>
</div>
```
**CSS**
```
/* css reset */
* {
margin: 0;
padding: 0;
}
/* here you go */
.wrapper {
float: left;
margin-right: 12px;
width: 200px;
}
h3 {
color: #32ff12;
background: #000000;
border-radius: 4px;
padding-left: 4px;
}
li {
list-style-type: none;
text-decoration: none;
color: #000;
background: none repeat scroll 0% 0% #EBEFF9;
border: 1px solid #D9E4FF;
border-radius: 4px;
display: block;
width: 100%;
margin-top: 4px;
}
``` | You need to wrap each month title and it's accompanying list within a container, apply a width to this container and float it to the left.
As the months can be considered a list as well, it would make sense semantically to have an ordered list, with each month as a list item (which would constitute the container) and then the unordered list nested within each ordered list item, e.g.:
```
<ol>
<li>
<h3>March</h3>
<ul>
<li>1 a 3 - Fronteira</li>
<li>10 a 13 -Belver</li>
</ul>
</li>
<li>
<h3>April</h3>
<ul>
<li>1 a 3 - Silves</li>
<li>10 a 13 -Porto</li>
</ul>
</li>
</ol>
```
Then the CSS:
```
ol > li {
float: left;
width: 300px;
list-style: none;
}
ul {
list-style-type: none;
text-decoration: none;
color: #000;
background: none repeat scroll 0% 0% #EBEFF9;
border: 1px solid #D9E4FF;
border-radius: 4px;
margin: 2px;
padding: 3px;
}
h3 {
color: #32ff12;
background: #000000;
border-radius: 4px;
}
```
See [jsfiddle](http://jsfiddle.net/redwar/p3N4Q/) |
32,461,736 | After migration website on wordpress to another server and another domain.
I have website root in the same directory. I heard that there is some config in database of this plugin POLYLANG but have no idea where.
I have an error like:
>
> Class 'PLL\_Links\_' not found in /wp-content/plugins/polylang/include/model.php on line 915
>
>
>
someone has an idea how to fix this problem ? | 2015/09/08 | [
"https://Stackoverflow.com/questions/32461736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2998059/"
] | This question can be still actual for some people.
I've spent tons of hours on it. And the trick that helped me is to fall back to v.0.9.8 from here - <https://wordpress.org/plugins/polylang/advanced/>.
Then get v.1.9.3 and unpack it to plugin folder. Then you are good to go with v.2+ | I got here because Polylang 2.3.1 was throwing a similar error after a database migration:
```
Class 'PLL_Links_' not found in /wp-content/plugins/polylang/include/model.php on line 560
```
If you look at the code in the model.php file referenced in the error, you can see that the plugin tries to retrieve a class name using the 'permalink\_structure' option set in the database. If the migration changes this option to something Polylang can't handle, it triggers the error.
To go around the fatal error, you either have to:
* (re)move or rename the Polylang plugin folder, so that it does not trigger the error
* Set the Permalinks setting to default in WordPress Admin via *Options > Permalinks*
* reinstall Polylang (or remove/rename it) and reactivate it in the *Plugins* overview.
or
* manually delete the value for 'permalink\_structure' in the `wp_options` table.
WordPress should run normally after this. I have not yet found out *why* it cannot handle certain permalink settings, but if I do, I'll update this answer. |
32,461,736 | After migration website on wordpress to another server and another domain.
I have website root in the same directory. I heard that there is some config in database of this plugin POLYLANG but have no idea where.
I have an error like:
>
> Class 'PLL\_Links\_' not found in /wp-content/plugins/polylang/include/model.php on line 915
>
>
>
someone has an idea how to fix this problem ? | 2015/09/08 | [
"https://Stackoverflow.com/questions/32461736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2998059/"
] | This question can be still actual for some people.
I've spent tons of hours on it. And the trick that helped me is to fall back to v.0.9.8 from here - <https://wordpress.org/plugins/polylang/advanced/>.
Then get v.1.9.3 and unpack it to plugin folder. Then you are good to go with v.2+ | I did a global domain replacement in the file when moving the database from local to live . The problem in the end was that the serialized array in wp\_option.option\_name = "polylang" is broken. You must change strings length in the domain array:
```
wp_option.option_name = ...."domains";a:1:
{s:2:"en";s:21:"http://example.local/";}....
```
on a local:
```
s:21:"http://example.local/";
```
after replacing in file:
```
s:21:"http://example.com/";
```
must be:
```
s:19:"http://example.com/";
``` |
32,461,736 | After migration website on wordpress to another server and another domain.
I have website root in the same directory. I heard that there is some config in database of this plugin POLYLANG but have no idea where.
I have an error like:
>
> Class 'PLL\_Links\_' not found in /wp-content/plugins/polylang/include/model.php on line 915
>
>
>
someone has an idea how to fix this problem ? | 2015/09/08 | [
"https://Stackoverflow.com/questions/32461736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2998059/"
] | I had the same error, prior to the error was an "Undefined index" notice.
It was caused by an empty `$this->options['force_lang']` var.
This var is loaded from the `wp_options` table, the `option_name` within this table is `polylang`. There should be a JSON encoded array of `polylang` options.
In my case the issue could be fixed by removing the domains from the JSON data, so it reads something like:
```
"domains";a:0:{}
``` | I got here because Polylang 2.3.1 was throwing a similar error after a database migration:
```
Class 'PLL_Links_' not found in /wp-content/plugins/polylang/include/model.php on line 560
```
If you look at the code in the model.php file referenced in the error, you can see that the plugin tries to retrieve a class name using the 'permalink\_structure' option set in the database. If the migration changes this option to something Polylang can't handle, it triggers the error.
To go around the fatal error, you either have to:
* (re)move or rename the Polylang plugin folder, so that it does not trigger the error
* Set the Permalinks setting to default in WordPress Admin via *Options > Permalinks*
* reinstall Polylang (or remove/rename it) and reactivate it in the *Plugins* overview.
or
* manually delete the value for 'permalink\_structure' in the `wp_options` table.
WordPress should run normally after this. I have not yet found out *why* it cannot handle certain permalink settings, but if I do, I'll update this answer. |
32,461,736 | After migration website on wordpress to another server and another domain.
I have website root in the same directory. I heard that there is some config in database of this plugin POLYLANG but have no idea where.
I have an error like:
>
> Class 'PLL\_Links\_' not found in /wp-content/plugins/polylang/include/model.php on line 915
>
>
>
someone has an idea how to fix this problem ? | 2015/09/08 | [
"https://Stackoverflow.com/questions/32461736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2998059/"
] | I had the same error, prior to the error was an "Undefined index" notice.
It was caused by an empty `$this->options['force_lang']` var.
This var is loaded from the `wp_options` table, the `option_name` within this table is `polylang`. There should be a JSON encoded array of `polylang` options.
In my case the issue could be fixed by removing the domains from the JSON data, so it reads something like:
```
"domains";a:0:{}
``` | I did a global domain replacement in the file when moving the database from local to live . The problem in the end was that the serialized array in wp\_option.option\_name = "polylang" is broken. You must change strings length in the domain array:
```
wp_option.option_name = ...."domains";a:1:
{s:2:"en";s:21:"http://example.local/";}....
```
on a local:
```
s:21:"http://example.local/";
```
after replacing in file:
```
s:21:"http://example.com/";
```
must be:
```
s:19:"http://example.com/";
``` |
53,643,238 | We are trying to Consume REST API, for message processor which has some operation which might take more than configured timeout.
Would like to know, if the timeout of Http call to API, will stop execution of API, or API will keep executing?
Idea is that, we can fire and forget API, we are not worried if API does not return 404 or 503. But would like to hear if API will continue to execute?
Any input or suggestion appreciated. | 2018/12/06 | [
"https://Stackoverflow.com/questions/53643238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1153316/"
] | Since you want to know how many times the if statement run (and you don’t use debugger), store those times in a variable.
```
//...
int timesRun = 0;
while( ){
if( ){
timesRun++;
}
}
System.out.println(“Debug: I’d statement run”+timesRun+” times”);
``` | if `MySQLAccess sql = new MySQLAccess()` throws, `m++` will not be reached. |
11,261,147 | I have an object that takes a long time to be initialized. Therefore I the capability to Start Initializing on application startup. Any subsequent calls to methods on the class we need to have a delay mechanism that waits for the class to finish initialization.
I have a couple of potential solutions however I am not entirely satisfied with either of them. The first uses Task.Delay in a while loop and the second uses SemaphoreSlim but involves some unnecessary blocking. I feel this must be a fairly common requirement, can anybody provide some advice on how to best manage this?
Oh btw, this is a Metro application so we have limited API's
Here is the pseudocode:
```
public class ExposeSomeInterestingItems
{
private InitialisationState _initialised;
private readonly SemaphoreSlim _waiter =
new SemaphoreSlim(0);
public async Task StartInitialize()
{
if (_initialised == InitialisationState.Initialised)
{
throw new InvalidOperationException(
"Attempted to initialise ActiveTrackDown" +
"loads when it is already initialized");
}
_initialised =
InitialisationState.StartedInitialisation;
new TaskFactory().StartNew(async () =>
{
// This takes some time to load
this._interestingItems =
InterestingItemsLoader.LoadItems();
_waiter.Release();
_initialised = InitialisationState.Initialised;
});
}
public InterestingItem GetItem(string id)
{
DelayUntilLoaded();
DelayUntilLoadedAlternative();
}
private async Task DelayUntilLoaded()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException("Error " +
"occurred attempting to access details on " +
"ActiveTrackDownloads before calling initialise");
}
while (true)
{
if (_initialised == InitialisationState.Initialised)
{
return;
}
await Task.Delay(300);
}
}
private async Task DelayUntilLoadedAlternative()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException(
"Error occurred attempting to access details " +
"on ActiveTrackDownloads before calling initialise");
}
try
{
await _waiter.WaitAsync();
}
finally
{
_waiter.Release();
}
}
}
``` | 2012/06/29 | [
"https://Stackoverflow.com/questions/11261147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125747/"
] | You can use the `Task<T>` for this. This will take care of all the synchronisation for you and allows you to block untill the value is available:
```
private static Task<HeavyObject> heavyObjectInitializer;
// Call this method during application initialization
public static void Bootstrap()
{
heavyObjectInitializer = new Task<HeavyObject>(() =>
{
// creation of heavy object here
return new HeavyObject();
});
// Start running the initialization right now on a
// background thread. We don't have to wait on this.
heavyObjectInitializer.Start();
}
// Call this method whenever you need to use the object.
public static HeavyObject GetHeavyObject()
{
// Get the initialized object, or block untill this
// instance gets available.
return heavyObjectInitializer.Result;
}
```
Optionally, you can also query to see if the object is available or not:
```
public static bool IsHeavyObjectAvailable
{
get { return heavyObjectInitializer.IsCompleted; }
}
``` | Put the method calls into a queue which you process when you finish initialising. Only put methods into the queue when you have not yet initialised. |
11,261,147 | I have an object that takes a long time to be initialized. Therefore I the capability to Start Initializing on application startup. Any subsequent calls to methods on the class we need to have a delay mechanism that waits for the class to finish initialization.
I have a couple of potential solutions however I am not entirely satisfied with either of them. The first uses Task.Delay in a while loop and the second uses SemaphoreSlim but involves some unnecessary blocking. I feel this must be a fairly common requirement, can anybody provide some advice on how to best manage this?
Oh btw, this is a Metro application so we have limited API's
Here is the pseudocode:
```
public class ExposeSomeInterestingItems
{
private InitialisationState _initialised;
private readonly SemaphoreSlim _waiter =
new SemaphoreSlim(0);
public async Task StartInitialize()
{
if (_initialised == InitialisationState.Initialised)
{
throw new InvalidOperationException(
"Attempted to initialise ActiveTrackDown" +
"loads when it is already initialized");
}
_initialised =
InitialisationState.StartedInitialisation;
new TaskFactory().StartNew(async () =>
{
// This takes some time to load
this._interestingItems =
InterestingItemsLoader.LoadItems();
_waiter.Release();
_initialised = InitialisationState.Initialised;
});
}
public InterestingItem GetItem(string id)
{
DelayUntilLoaded();
DelayUntilLoadedAlternative();
}
private async Task DelayUntilLoaded()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException("Error " +
"occurred attempting to access details on " +
"ActiveTrackDownloads before calling initialise");
}
while (true)
{
if (_initialised == InitialisationState.Initialised)
{
return;
}
await Task.Delay(300);
}
}
private async Task DelayUntilLoadedAlternative()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException(
"Error occurred attempting to access details " +
"on ActiveTrackDownloads before calling initialise");
}
try
{
await _waiter.WaitAsync();
}
finally
{
_waiter.Release();
}
}
}
``` | 2012/06/29 | [
"https://Stackoverflow.com/questions/11261147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125747/"
] | You can use the `Task<T>` for this. This will take care of all the synchronisation for you and allows you to block untill the value is available:
```
private static Task<HeavyObject> heavyObjectInitializer;
// Call this method during application initialization
public static void Bootstrap()
{
heavyObjectInitializer = new Task<HeavyObject>(() =>
{
// creation of heavy object here
return new HeavyObject();
});
// Start running the initialization right now on a
// background thread. We don't have to wait on this.
heavyObjectInitializer.Start();
}
// Call this method whenever you need to use the object.
public static HeavyObject GetHeavyObject()
{
// Get the initialized object, or block untill this
// instance gets available.
return heavyObjectInitializer.Result;
}
```
Optionally, you can also query to see if the object is available or not:
```
public static bool IsHeavyObjectAvailable
{
get { return heavyObjectInitializer.IsCompleted; }
}
``` | You could move to a an event driven architecture where you application is in different states.
Initially the application moves into the **Starting** state. In this state `HeavyObject` is created using a background task. When the initialization is complete an event is fired. (You don't have to use an actual .NET `event`. You can use callbacks or something similar and frameworks like Reactive Extensions allows you to compose sequences of events.)
When all initialization events have fired you move into the **Started** state of your application. For an UI application this could modify the UI to enable some previously disabled operations. |
11,261,147 | I have an object that takes a long time to be initialized. Therefore I the capability to Start Initializing on application startup. Any subsequent calls to methods on the class we need to have a delay mechanism that waits for the class to finish initialization.
I have a couple of potential solutions however I am not entirely satisfied with either of them. The first uses Task.Delay in a while loop and the second uses SemaphoreSlim but involves some unnecessary blocking. I feel this must be a fairly common requirement, can anybody provide some advice on how to best manage this?
Oh btw, this is a Metro application so we have limited API's
Here is the pseudocode:
```
public class ExposeSomeInterestingItems
{
private InitialisationState _initialised;
private readonly SemaphoreSlim _waiter =
new SemaphoreSlim(0);
public async Task StartInitialize()
{
if (_initialised == InitialisationState.Initialised)
{
throw new InvalidOperationException(
"Attempted to initialise ActiveTrackDown" +
"loads when it is already initialized");
}
_initialised =
InitialisationState.StartedInitialisation;
new TaskFactory().StartNew(async () =>
{
// This takes some time to load
this._interestingItems =
InterestingItemsLoader.LoadItems();
_waiter.Release();
_initialised = InitialisationState.Initialised;
});
}
public InterestingItem GetItem(string id)
{
DelayUntilLoaded();
DelayUntilLoadedAlternative();
}
private async Task DelayUntilLoaded()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException("Error " +
"occurred attempting to access details on " +
"ActiveTrackDownloads before calling initialise");
}
while (true)
{
if (_initialised == InitialisationState.Initialised)
{
return;
}
await Task.Delay(300);
}
}
private async Task DelayUntilLoadedAlternative()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException(
"Error occurred attempting to access details " +
"on ActiveTrackDownloads before calling initialise");
}
try
{
await _waiter.WaitAsync();
}
finally
{
_waiter.Release();
}
}
}
``` | 2012/06/29 | [
"https://Stackoverflow.com/questions/11261147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125747/"
] | You can use the `Task<T>` for this. This will take care of all the synchronisation for you and allows you to block untill the value is available:
```
private static Task<HeavyObject> heavyObjectInitializer;
// Call this method during application initialization
public static void Bootstrap()
{
heavyObjectInitializer = new Task<HeavyObject>(() =>
{
// creation of heavy object here
return new HeavyObject();
});
// Start running the initialization right now on a
// background thread. We don't have to wait on this.
heavyObjectInitializer.Start();
}
// Call this method whenever you need to use the object.
public static HeavyObject GetHeavyObject()
{
// Get the initialized object, or block untill this
// instance gets available.
return heavyObjectInitializer.Result;
}
```
Optionally, you can also query to see if the object is available or not:
```
public static bool IsHeavyObjectAvailable
{
get { return heavyObjectInitializer.IsCompleted; }
}
``` | Check this [Prototype Pattern](http://en.wikipedia.org/wiki/Prototype_pattern). Maybe it can help you
You only need to create your object once and clone it when you need another one. |
11,261,147 | I have an object that takes a long time to be initialized. Therefore I the capability to Start Initializing on application startup. Any subsequent calls to methods on the class we need to have a delay mechanism that waits for the class to finish initialization.
I have a couple of potential solutions however I am not entirely satisfied with either of them. The first uses Task.Delay in a while loop and the second uses SemaphoreSlim but involves some unnecessary blocking. I feel this must be a fairly common requirement, can anybody provide some advice on how to best manage this?
Oh btw, this is a Metro application so we have limited API's
Here is the pseudocode:
```
public class ExposeSomeInterestingItems
{
private InitialisationState _initialised;
private readonly SemaphoreSlim _waiter =
new SemaphoreSlim(0);
public async Task StartInitialize()
{
if (_initialised == InitialisationState.Initialised)
{
throw new InvalidOperationException(
"Attempted to initialise ActiveTrackDown" +
"loads when it is already initialized");
}
_initialised =
InitialisationState.StartedInitialisation;
new TaskFactory().StartNew(async () =>
{
// This takes some time to load
this._interestingItems =
InterestingItemsLoader.LoadItems();
_waiter.Release();
_initialised = InitialisationState.Initialised;
});
}
public InterestingItem GetItem(string id)
{
DelayUntilLoaded();
DelayUntilLoadedAlternative();
}
private async Task DelayUntilLoaded()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException("Error " +
"occurred attempting to access details on " +
"ActiveTrackDownloads before calling initialise");
}
while (true)
{
if (_initialised == InitialisationState.Initialised)
{
return;
}
await Task.Delay(300);
}
}
private async Task DelayUntilLoadedAlternative()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException(
"Error occurred attempting to access details " +
"on ActiveTrackDownloads before calling initialise");
}
try
{
await _waiter.WaitAsync();
}
finally
{
_waiter.Release();
}
}
}
``` | 2012/06/29 | [
"https://Stackoverflow.com/questions/11261147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125747/"
] | I think that a better design would be an asynchronous factory, where the *calling* code `await`s the object creation and then receives a regular object instance.
Stealing liberally [from Stephen Toub](http://blogs.msdn.com/b/pfxteam/archive/2011/01/15/10116210.aspx):
```
public class AsyncLazy<T> : Lazy<Task<T>>
{
public AsyncLazy(Func<T> valueFactory) :
base(() => Task.Run(valueFactory)) { }
public AsyncLazy(Func<Task<T>> taskFactory) :
base(() => Task.Run(taskFactory)) { }
public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); }
}
public static class ExposeSomeInterestingItemsFactory
{
public static AsyncLazy<ExposeSomeInterestingItems> Instance
{
get { return _instance; }
}
private static readonly AsyncLazy<ExposeSomeInterestingItems> _instance =
new AsyncLazy<ExposeSomeInterestingItems>(() => new ExposeSomeInterestingItems());
public static void StartInitialization()
{
var unused = Instance.Value;
}
}
public class ExposeSomeInterestingItems
{
public ExposeSomeInterestingItems()
{
// This takes some time to load
this._interestingItems = InterestingItemsLoader.LoadItems();
}
public InterestingItem GetItem(string id)
{
// Regular logic. No "delays".
}
}
...
var exposeSomeInterestingItems = await ExposeSomeInterestingItemsFactory.Instance;
var item = exposeSomeInterestingItems.GetItem("id");
```
That way, you keep the Single Responsibility Principle nicely:
* `AsyncLazy<T>` combines `Task<T>` with `Lazy<T>` (so the instance is created asynchronously only when needed).
* `ExposeSomeInterestingItemsFactory` contains construction logic.
* `ExposeSomeInterestingItems` is only concerned with exposing interesting items, rather than having to pollute all its members with asynchronous delays.
Also, this solution is asynchronous throughout (no blocking), which is good (particularly for Metro apps).
**Update, 2012-09-14:** I've taken this code and cleaned it up and commented it [on my blog](http://nitoprograms.blogspot.com/2012/08/asynchronous-lazy-initialization.html). | You can use the `Task<T>` for this. This will take care of all the synchronisation for you and allows you to block untill the value is available:
```
private static Task<HeavyObject> heavyObjectInitializer;
// Call this method during application initialization
public static void Bootstrap()
{
heavyObjectInitializer = new Task<HeavyObject>(() =>
{
// creation of heavy object here
return new HeavyObject();
});
// Start running the initialization right now on a
// background thread. We don't have to wait on this.
heavyObjectInitializer.Start();
}
// Call this method whenever you need to use the object.
public static HeavyObject GetHeavyObject()
{
// Get the initialized object, or block untill this
// instance gets available.
return heavyObjectInitializer.Result;
}
```
Optionally, you can also query to see if the object is available or not:
```
public static bool IsHeavyObjectAvailable
{
get { return heavyObjectInitializer.IsCompleted; }
}
``` |
11,261,147 | I have an object that takes a long time to be initialized. Therefore I the capability to Start Initializing on application startup. Any subsequent calls to methods on the class we need to have a delay mechanism that waits for the class to finish initialization.
I have a couple of potential solutions however I am not entirely satisfied with either of them. The first uses Task.Delay in a while loop and the second uses SemaphoreSlim but involves some unnecessary blocking. I feel this must be a fairly common requirement, can anybody provide some advice on how to best manage this?
Oh btw, this is a Metro application so we have limited API's
Here is the pseudocode:
```
public class ExposeSomeInterestingItems
{
private InitialisationState _initialised;
private readonly SemaphoreSlim _waiter =
new SemaphoreSlim(0);
public async Task StartInitialize()
{
if (_initialised == InitialisationState.Initialised)
{
throw new InvalidOperationException(
"Attempted to initialise ActiveTrackDown" +
"loads when it is already initialized");
}
_initialised =
InitialisationState.StartedInitialisation;
new TaskFactory().StartNew(async () =>
{
// This takes some time to load
this._interestingItems =
InterestingItemsLoader.LoadItems();
_waiter.Release();
_initialised = InitialisationState.Initialised;
});
}
public InterestingItem GetItem(string id)
{
DelayUntilLoaded();
DelayUntilLoadedAlternative();
}
private async Task DelayUntilLoaded()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException("Error " +
"occurred attempting to access details on " +
"ActiveTrackDownloads before calling initialise");
}
while (true)
{
if (_initialised == InitialisationState.Initialised)
{
return;
}
await Task.Delay(300);
}
}
private async Task DelayUntilLoadedAlternative()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException(
"Error occurred attempting to access details " +
"on ActiveTrackDownloads before calling initialise");
}
try
{
await _waiter.WaitAsync();
}
finally
{
_waiter.Release();
}
}
}
``` | 2012/06/29 | [
"https://Stackoverflow.com/questions/11261147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125747/"
] | I think that a better design would be an asynchronous factory, where the *calling* code `await`s the object creation and then receives a regular object instance.
Stealing liberally [from Stephen Toub](http://blogs.msdn.com/b/pfxteam/archive/2011/01/15/10116210.aspx):
```
public class AsyncLazy<T> : Lazy<Task<T>>
{
public AsyncLazy(Func<T> valueFactory) :
base(() => Task.Run(valueFactory)) { }
public AsyncLazy(Func<Task<T>> taskFactory) :
base(() => Task.Run(taskFactory)) { }
public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); }
}
public static class ExposeSomeInterestingItemsFactory
{
public static AsyncLazy<ExposeSomeInterestingItems> Instance
{
get { return _instance; }
}
private static readonly AsyncLazy<ExposeSomeInterestingItems> _instance =
new AsyncLazy<ExposeSomeInterestingItems>(() => new ExposeSomeInterestingItems());
public static void StartInitialization()
{
var unused = Instance.Value;
}
}
public class ExposeSomeInterestingItems
{
public ExposeSomeInterestingItems()
{
// This takes some time to load
this._interestingItems = InterestingItemsLoader.LoadItems();
}
public InterestingItem GetItem(string id)
{
// Regular logic. No "delays".
}
}
...
var exposeSomeInterestingItems = await ExposeSomeInterestingItemsFactory.Instance;
var item = exposeSomeInterestingItems.GetItem("id");
```
That way, you keep the Single Responsibility Principle nicely:
* `AsyncLazy<T>` combines `Task<T>` with `Lazy<T>` (so the instance is created asynchronously only when needed).
* `ExposeSomeInterestingItemsFactory` contains construction logic.
* `ExposeSomeInterestingItems` is only concerned with exposing interesting items, rather than having to pollute all its members with asynchronous delays.
Also, this solution is asynchronous throughout (no blocking), which is good (particularly for Metro apps).
**Update, 2012-09-14:** I've taken this code and cleaned it up and commented it [on my blog](http://nitoprograms.blogspot.com/2012/08/asynchronous-lazy-initialization.html). | Put the method calls into a queue which you process when you finish initialising. Only put methods into the queue when you have not yet initialised. |
11,261,147 | I have an object that takes a long time to be initialized. Therefore I the capability to Start Initializing on application startup. Any subsequent calls to methods on the class we need to have a delay mechanism that waits for the class to finish initialization.
I have a couple of potential solutions however I am not entirely satisfied with either of them. The first uses Task.Delay in a while loop and the second uses SemaphoreSlim but involves some unnecessary blocking. I feel this must be a fairly common requirement, can anybody provide some advice on how to best manage this?
Oh btw, this is a Metro application so we have limited API's
Here is the pseudocode:
```
public class ExposeSomeInterestingItems
{
private InitialisationState _initialised;
private readonly SemaphoreSlim _waiter =
new SemaphoreSlim(0);
public async Task StartInitialize()
{
if (_initialised == InitialisationState.Initialised)
{
throw new InvalidOperationException(
"Attempted to initialise ActiveTrackDown" +
"loads when it is already initialized");
}
_initialised =
InitialisationState.StartedInitialisation;
new TaskFactory().StartNew(async () =>
{
// This takes some time to load
this._interestingItems =
InterestingItemsLoader.LoadItems();
_waiter.Release();
_initialised = InitialisationState.Initialised;
});
}
public InterestingItem GetItem(string id)
{
DelayUntilLoaded();
DelayUntilLoadedAlternative();
}
private async Task DelayUntilLoaded()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException("Error " +
"occurred attempting to access details on " +
"ActiveTrackDownloads before calling initialise");
}
while (true)
{
if (_initialised == InitialisationState.Initialised)
{
return;
}
await Task.Delay(300);
}
}
private async Task DelayUntilLoadedAlternative()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException(
"Error occurred attempting to access details " +
"on ActiveTrackDownloads before calling initialise");
}
try
{
await _waiter.WaitAsync();
}
finally
{
_waiter.Release();
}
}
}
``` | 2012/06/29 | [
"https://Stackoverflow.com/questions/11261147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125747/"
] | I think that a better design would be an asynchronous factory, where the *calling* code `await`s the object creation and then receives a regular object instance.
Stealing liberally [from Stephen Toub](http://blogs.msdn.com/b/pfxteam/archive/2011/01/15/10116210.aspx):
```
public class AsyncLazy<T> : Lazy<Task<T>>
{
public AsyncLazy(Func<T> valueFactory) :
base(() => Task.Run(valueFactory)) { }
public AsyncLazy(Func<Task<T>> taskFactory) :
base(() => Task.Run(taskFactory)) { }
public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); }
}
public static class ExposeSomeInterestingItemsFactory
{
public static AsyncLazy<ExposeSomeInterestingItems> Instance
{
get { return _instance; }
}
private static readonly AsyncLazy<ExposeSomeInterestingItems> _instance =
new AsyncLazy<ExposeSomeInterestingItems>(() => new ExposeSomeInterestingItems());
public static void StartInitialization()
{
var unused = Instance.Value;
}
}
public class ExposeSomeInterestingItems
{
public ExposeSomeInterestingItems()
{
// This takes some time to load
this._interestingItems = InterestingItemsLoader.LoadItems();
}
public InterestingItem GetItem(string id)
{
// Regular logic. No "delays".
}
}
...
var exposeSomeInterestingItems = await ExposeSomeInterestingItemsFactory.Instance;
var item = exposeSomeInterestingItems.GetItem("id");
```
That way, you keep the Single Responsibility Principle nicely:
* `AsyncLazy<T>` combines `Task<T>` with `Lazy<T>` (so the instance is created asynchronously only when needed).
* `ExposeSomeInterestingItemsFactory` contains construction logic.
* `ExposeSomeInterestingItems` is only concerned with exposing interesting items, rather than having to pollute all its members with asynchronous delays.
Also, this solution is asynchronous throughout (no blocking), which is good (particularly for Metro apps).
**Update, 2012-09-14:** I've taken this code and cleaned it up and commented it [on my blog](http://nitoprograms.blogspot.com/2012/08/asynchronous-lazy-initialization.html). | You could move to a an event driven architecture where you application is in different states.
Initially the application moves into the **Starting** state. In this state `HeavyObject` is created using a background task. When the initialization is complete an event is fired. (You don't have to use an actual .NET `event`. You can use callbacks or something similar and frameworks like Reactive Extensions allows you to compose sequences of events.)
When all initialization events have fired you move into the **Started** state of your application. For an UI application this could modify the UI to enable some previously disabled operations. |
11,261,147 | I have an object that takes a long time to be initialized. Therefore I the capability to Start Initializing on application startup. Any subsequent calls to methods on the class we need to have a delay mechanism that waits for the class to finish initialization.
I have a couple of potential solutions however I am not entirely satisfied with either of them. The first uses Task.Delay in a while loop and the second uses SemaphoreSlim but involves some unnecessary blocking. I feel this must be a fairly common requirement, can anybody provide some advice on how to best manage this?
Oh btw, this is a Metro application so we have limited API's
Here is the pseudocode:
```
public class ExposeSomeInterestingItems
{
private InitialisationState _initialised;
private readonly SemaphoreSlim _waiter =
new SemaphoreSlim(0);
public async Task StartInitialize()
{
if (_initialised == InitialisationState.Initialised)
{
throw new InvalidOperationException(
"Attempted to initialise ActiveTrackDown" +
"loads when it is already initialized");
}
_initialised =
InitialisationState.StartedInitialisation;
new TaskFactory().StartNew(async () =>
{
// This takes some time to load
this._interestingItems =
InterestingItemsLoader.LoadItems();
_waiter.Release();
_initialised = InitialisationState.Initialised;
});
}
public InterestingItem GetItem(string id)
{
DelayUntilLoaded();
DelayUntilLoadedAlternative();
}
private async Task DelayUntilLoaded()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException("Error " +
"occurred attempting to access details on " +
"ActiveTrackDownloads before calling initialise");
}
while (true)
{
if (_initialised == InitialisationState.Initialised)
{
return;
}
await Task.Delay(300);
}
}
private async Task DelayUntilLoadedAlternative()
{
if (_initialised == InitialisationState.NotInitialised)
{
throw new InvalidOperationException(
"Error occurred attempting to access details " +
"on ActiveTrackDownloads before calling initialise");
}
try
{
await _waiter.WaitAsync();
}
finally
{
_waiter.Release();
}
}
}
``` | 2012/06/29 | [
"https://Stackoverflow.com/questions/11261147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125747/"
] | I think that a better design would be an asynchronous factory, where the *calling* code `await`s the object creation and then receives a regular object instance.
Stealing liberally [from Stephen Toub](http://blogs.msdn.com/b/pfxteam/archive/2011/01/15/10116210.aspx):
```
public class AsyncLazy<T> : Lazy<Task<T>>
{
public AsyncLazy(Func<T> valueFactory) :
base(() => Task.Run(valueFactory)) { }
public AsyncLazy(Func<Task<T>> taskFactory) :
base(() => Task.Run(taskFactory)) { }
public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); }
}
public static class ExposeSomeInterestingItemsFactory
{
public static AsyncLazy<ExposeSomeInterestingItems> Instance
{
get { return _instance; }
}
private static readonly AsyncLazy<ExposeSomeInterestingItems> _instance =
new AsyncLazy<ExposeSomeInterestingItems>(() => new ExposeSomeInterestingItems());
public static void StartInitialization()
{
var unused = Instance.Value;
}
}
public class ExposeSomeInterestingItems
{
public ExposeSomeInterestingItems()
{
// This takes some time to load
this._interestingItems = InterestingItemsLoader.LoadItems();
}
public InterestingItem GetItem(string id)
{
// Regular logic. No "delays".
}
}
...
var exposeSomeInterestingItems = await ExposeSomeInterestingItemsFactory.Instance;
var item = exposeSomeInterestingItems.GetItem("id");
```
That way, you keep the Single Responsibility Principle nicely:
* `AsyncLazy<T>` combines `Task<T>` with `Lazy<T>` (so the instance is created asynchronously only when needed).
* `ExposeSomeInterestingItemsFactory` contains construction logic.
* `ExposeSomeInterestingItems` is only concerned with exposing interesting items, rather than having to pollute all its members with asynchronous delays.
Also, this solution is asynchronous throughout (no blocking), which is good (particularly for Metro apps).
**Update, 2012-09-14:** I've taken this code and cleaned it up and commented it [on my blog](http://nitoprograms.blogspot.com/2012/08/asynchronous-lazy-initialization.html). | Check this [Prototype Pattern](http://en.wikipedia.org/wiki/Prototype_pattern). Maybe it can help you
You only need to create your object once and clone it when you need another one. |
17,453,339 | 
`JSON.stringify(null)` returns the string `null`.
`JSON.stringify(undefined)` returns the value `undefined`. Shouldn't it return the *string* `undefined`?
Parsing the value `undefined` or the string `undefined` gives a `SyntaxError`.
Could someone explain why JSON chokes on `undefined` and how to get around it when stringifying / parsing values? | 2013/07/03 | [
"https://Stackoverflow.com/questions/17453339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/552067/"
] | `undefined` is not valid JSON, so the function is working properly.
<http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example> | ```
if(JSON.stringify(input) === undefined) {
// error handle
}
```
or
```
if(input === undefined) {
// error handle
}
else {
JSON.stringify(input);
}
```
Sorry. Life is hard sometimes. This is pretty much what you have to do. |
17,453,339 | 
`JSON.stringify(null)` returns the string `null`.
`JSON.stringify(undefined)` returns the value `undefined`. Shouldn't it return the *string* `undefined`?
Parsing the value `undefined` or the string `undefined` gives a `SyntaxError`.
Could someone explain why JSON chokes on `undefined` and how to get around it when stringifying / parsing values? | 2013/07/03 | [
"https://Stackoverflow.com/questions/17453339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/552067/"
] | `undefined` is not valid JSON, so the function is working properly.
<http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example> | The reason for this is that `null` is caused by a variable that doesn't have a value, so when converted to JSON it gives you JSON that doesn't have a value, undefined means it doesn't exist at all, so you can't create a JSON object of something that doesn't exist. Just check
```
if(typeof myvar === 'undefined')
```
before you run it and handle the error gracefully in the code.
Generally try to avoid `undefined` in your JS they can to weird things all over the place, and are NOT the same as `null` and are usually handled differently. |
25,511,984 | In **DOM** (Document Object Model) specification, interface Node has a method:
```
Node GetChild();
```
It states that if **Node** has no child then a return value is **NULL**.
What is the right way to implement this approach in **C++** without returning a pointer to a child Node. (Better to prevent from memory leaks)
Suggestion:
Have an attribute
```
bool is_null_;
```
and overload *operator bool()* to return this value.
```
Node child = node.GetChild();
if (child) { ... }
``` | 2014/08/26 | [
"https://Stackoverflow.com/questions/25511984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1920999/"
] | Waiting a bit now, but the Library Fundamentals TS will be providing [`std::experimental::optional`](http://en.cppreference.com/w/cpp/experimental/optional).
Elsewise if you can use [`boost::optional`](http://www.boost.org/doc/libs/1_56_0/libs/optional/doc/html/index.html), which has similar semantics.
You can use it like:
```
using std::experimental::optional;
optional<Node> GetChild();
auto child = node.GetChild();
if (child) {
const Node& childNode = child.value();
} else {
std::cerr << "parent had no child" << std::endl;
}
``` | Such thing as `boost::optional` will help you:
<http://www.boost.org/doc/libs/1_56_0/libs/optional/doc/html/index.html> |
73,612,276 | I am using the google\_maps\_flutter: ^2.1.3 package in my Flutter project that I am currently developing and I want to show active regions on the map in the application. I tried to show the active regions on the map using polygons, but I couldn't paint the part outside of these regions a different color. Actually, exactly what I want on the map, everywhere will be gray (to be clear that it is not active), but some areas will be white (to be clear that it is active) surrounded by borders. You can understand exactly what I want by looking at the image below. In this way, there will be more than one active region on the map.
[](https://i.stack.imgur.com/0g9KB.jpg)
Note: As I mentioned before, I can get this image using polygons, but I cannot make the outside of the polygons gray. | 2022/09/05 | [
"https://Stackoverflow.com/questions/73612276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606266/"
] | Based on Matt's answer, I came up with the exact solution. First, I couldn't draw a polygon that would cover the entire world, and instead I increased the polygon count to 2. I drew 2 polygons covering the whole world, from 0 to east and from 0 to west. I set the strokeWidth values to 0 so that these polygons do not draw lines from the north pole to the south pole. Later, I showed the active areas in holes, but because my strokeWidth value was 0, the border line did not occur. To avoid this event, I created a new polygon with the fillColor value Colors.transparent and the same coordinates, and set the strokeWidth value to 2.
My sample codes are as follows:
```
polygon.add(
Polygon(
fillColor: Colors.black.withOpacity(0.5),
polygonId: const PolygonId('test'),
holes: [if (pointsFromService.length != 0) pointsFromService],
points: const [
LatLng(-89, 0),
LatLng(89, 0),
LatLng(89, 179.999),
LatLng(-89, 179.999),
],
visible: true,
geodesic: false,
strokeWidth: 0,
),
);
polygon.add(
Polygon(
fillColor: Colors.black.withOpacity(0.5),
polygonId: const PolygonId('test2'),
points: const [
LatLng(-89.9, 0),
LatLng(89.9, 0),
LatLng(89.9, -179.999),
LatLng(-89.9, -179.999),
],
visible: true,
geodesic: false,
strokeWidth: 0,
),
);
if (pointsFromService.length != 0) {
polygon.add(
Polygon(
fillColor: Colors.transparent,
strokeColor: primaryColor,
polygonId: const PolygonId('test3'),
points: pointsFromService,
visible: true,
geodesic: false,
strokeWidth: 2,
),
);
}
}
```
The result is as follows:
(Note that the gray area covers the whole world)
[](https://i.stack.imgur.com/bQsyy.jpg) | `Polygon` has a `holes` parameter which accepts a list of `List<LatLng>`. What you want to do is create one big polygon that covers the world (or viewport) and set that to be the background color. Then put your actual polygon(s) that you want to draw in the `holes` section to create a cutout:
```
Polygon maskedArea = new Polygon(
fillColor: Colors.black.withOpacity(0.5),
polygonId: new PolygonId('test'),
holes: [<LatLng>[new LatLng(10, 10), new LatLng(40, 10), new LatLng(40, 40), new LatLng(10, 40)]],
points: <LatLng>[new LatLng(0, 0), new LatLng(50, 0), new LatLng(50, 50), new LatLng(0, 50)]
);
```
If you're open to using plugins, there is also [syncfusion\_flutter\_maps](https://pub.dev/packages/syncfusion_flutter_maps) which seems to use a custom vector drawing solution to achieve a more robust result through the [`MapPolygonLayer.inverted`](https://help.syncfusion.com/flutter/maps/vector-layers/polygon-layer#inverted-polygon) constructor (I have not used this plugin myself but have used others from the developer and would anticipate no issues here).
[](https://i.stack.imgur.com/R4STi.png) |
1,437,662 | I have to factorise- $$x^6+5x^3+8$$Answer is $$(x^2−x+2)(x^4+x^3−x^2+2x+4)$$.I have also used factor theorem.Please help me.Thanks in advance. | 2015/09/16 | [
"https://math.stackexchange.com/questions/1437662",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242402/"
] | Break the equation $x^6+5x^3+8$ into $x^6+8-x^3+6x^3$. It then comes into the form $a^3+b^3+c^3-3abc$. Factorise it using the formula $a^3+b^3+c^3-3abc=(a+b+c)(a^2+b^2+c^2-ab-bc-ca)$. | It can be factored with help of following identities (applied twice below, marked by a '\*')
$$u^3 \pm v^3 = (u \pm v)(u^2 \pm uv + v^2)$$
Let $u = x^2 + 2$, we have
$$\begin{align}
x^6 + 5x^3 + 8
&= (x^2)^3 + 2^3 + 5x^3\tag{1}\\
&\stackrel{\*}{=} (x^2+2)(x^4 - 2x^2 + 4) + 5x^3\\
&= u(u^2 - 6x^2) + 5x^3\tag{2}\\
&= (u^3 - x^3) - 6x^2(u-x)\\
&\stackrel{\*}{=} (u-x)(u^2 + ux + x^2 - 6x^2)\\
&= (x^2 - x + 2)((x^2 + 2)^2 + x(x^2+2) - 5x^2)\\
&= (x^2 - x + 2)(x^4 + x^3 - x^2 + 2x + 4)
\end{align}
$$
**Rationale behind the steps**
* The motivation for step 1 is the non-zero coefficients of $x^k$ are symmetric
around $k = 3$ term. i.e
$$x^6 + 5x^3 + 8 = x^3 \left(x^3 + 5 + \left(\frac{2}{x}\right)^3\right)$$
I try to express everything in terms of $x + \frac{2}{x}$ and looks for simplification.
* Some where in the process, I notice the $1, -6, 5$ pattern in some
expression equivalent to $(2)$. This implies the existence of a factor $u - x$
in the original expression. The rest is more or less following the nose. |
63,874,613 | I'm using a Windows 10 computer and I have a file that I want to use in a Java application. Let's call the file example.xml.gz. I want to convert it to an XML file so I can view the data in Eclipse, but I can't figure out how to extract the data. Do I unzip it, if so how? | 2020/09/13 | [
"https://Stackoverflow.com/questions/63874613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11444939/"
] | Open gitbash and in the dir where the xml.gz file is located use:
gunzip example.xml.gz
then the XML file will be extracted and you can open the xml file. | You can gunzip a file in Java with this simple method:
```
public static void gunzip(Path fin, Path fout) throws IOException {
System.out.println("GUNZIP "+fin+" -> "+fout);
try(final OutputStream out = Files.newOutputStream(fout);
final InputStream in = new GZIPInputStream(Files.newInputStream(fin))) {
in.transferTo(out);
}
}
``` |
59,233,856 | I'm trying to get highest price of a product. I'm able to store the prices in an object.
I want to know how to get the maximum value from that object. Below is my code!
```
public class amazon {
static WebDriver driver;
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C://Selenium/chromedriver.exe");
driver = new ChromeDriver();
driver.get("xyzzz.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
amazon az = new amazon();
az.run();
}
public void run() throws Exception {
List<Object> obj = new ArrayList<Object>();
List<WebElement> tag = driver.findElements(By.xpath("//span[@class='a-price-whole']"));
int i;
for(i=0; i<tag.size(); i++) {
obj.add(tag.get(i).getText());
}
System.out.println(obj);
driver.close();
}
```
Output i have..
```
[64,900, 99,900, 1,23,900, 64,900, 64,900, 69,900, 64,900, 64,900, 1,23,900, 52,900]
``` | 2019/12/08 | [
"https://Stackoverflow.com/questions/59233856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11517146/"
] | Map the strings to ints (or longs, or some type of currency), then you can get the max using a Comparator
```
int max = driver.findElements(By.xpath("//span[@class='a-price-whole']")).stream()
.map(WebElement::getText)
.map(s -> s.replace(",", ""))
.map(Integer::parseInt)
.max(Integer::compare)
.get();
``` | create an int and call it max (=0), run on each element of the list using a loop (for loop recommended), on each element, check if its bigger than max, if yes, put the value in max,
here is a little code, in case the list is called "list", change it to whatever you want
```
int max=0;
for (int i : list){
if (i >max)
max=i;
}
System.out.println(max) //print the maximum value of the array
``` |
59,233,856 | I'm trying to get highest price of a product. I'm able to store the prices in an object.
I want to know how to get the maximum value from that object. Below is my code!
```
public class amazon {
static WebDriver driver;
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C://Selenium/chromedriver.exe");
driver = new ChromeDriver();
driver.get("xyzzz.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
amazon az = new amazon();
az.run();
}
public void run() throws Exception {
List<Object> obj = new ArrayList<Object>();
List<WebElement> tag = driver.findElements(By.xpath("//span[@class='a-price-whole']"));
int i;
for(i=0; i<tag.size(); i++) {
obj.add(tag.get(i).getText());
}
System.out.println(obj);
driver.close();
}
```
Output i have..
```
[64,900, 99,900, 1,23,900, 64,900, 64,900, 69,900, 64,900, 64,900, 1,23,900, 52,900]
``` | 2019/12/08 | [
"https://Stackoverflow.com/questions/59233856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11517146/"
] | You first need to convert the numbers to int, and than you can use `Collections.max` on the list
```
List<Integer> prices = new ArrayList<>();
List<WebElement> tags = driver.findElements(By.xpath("//span[@class='a-price-whole']"));
for (WebElement tag: tags) {
prices.add(Integer.parseInt(tag.getText().replace(",", "")));
}
System.out.print(Collections.max(prices)); // 123900
``` | create an int and call it max (=0), run on each element of the list using a loop (for loop recommended), on each element, check if its bigger than max, if yes, put the value in max,
here is a little code, in case the list is called "list", change it to whatever you want
```
int max=0;
for (int i : list){
if (i >max)
max=i;
}
System.out.println(max) //print the maximum value of the array
``` |
59,233,856 | I'm trying to get highest price of a product. I'm able to store the prices in an object.
I want to know how to get the maximum value from that object. Below is my code!
```
public class amazon {
static WebDriver driver;
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C://Selenium/chromedriver.exe");
driver = new ChromeDriver();
driver.get("xyzzz.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
amazon az = new amazon();
az.run();
}
public void run() throws Exception {
List<Object> obj = new ArrayList<Object>();
List<WebElement> tag = driver.findElements(By.xpath("//span[@class='a-price-whole']"));
int i;
for(i=0; i<tag.size(); i++) {
obj.add(tag.get(i).getText());
}
System.out.println(obj);
driver.close();
}
```
Output i have..
```
[64,900, 99,900, 1,23,900, 64,900, 64,900, 69,900, 64,900, 64,900, 1,23,900, 52,900]
``` | 2019/12/08 | [
"https://Stackoverflow.com/questions/59233856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11517146/"
] | You first need to convert the numbers to int, and than you can use `Collections.max` on the list
```
List<Integer> prices = new ArrayList<>();
List<WebElement> tags = driver.findElements(By.xpath("//span[@class='a-price-whole']"));
for (WebElement tag: tags) {
prices.add(Integer.parseInt(tag.getText().replace(",", "")));
}
System.out.print(Collections.max(prices)); // 123900
``` | Map the strings to ints (or longs, or some type of currency), then you can get the max using a Comparator
```
int max = driver.findElements(By.xpath("//span[@class='a-price-whole']")).stream()
.map(WebElement::getText)
.map(s -> s.replace(",", ""))
.map(Integer::parseInt)
.max(Integer::compare)
.get();
``` |
2,260,393 | I found this on MSE : [Prove $\int\_{B(x,r)}|\nabla u|^2\leq \frac{C}{r^2}\int\_{B(x,2r)}|u|^2$ if $-\Delta u(x)+f(x)u(x)=0.$](https://math.stackexchange.com/questions/2087724/prove-int-bx-r-nabla-u2-leq-fraccr2-int-bx-2ru2-if-del)
And I was wondering why in the proof of @xpaul we can choose $\xi$ as $|\nabla \xi|\leq \frac{C}{r}$ ? I'm studing partition of unity, but I don't see such a result. | 2017/05/01 | [
"https://math.stackexchange.com/questions/2260393",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/386627/"
] | Choose $\xi \in C\_c^\infty$ such that $0 \le \xi \le 1$, $\xi \equiv 1$ on $B(0,1)$, $\xi \equiv 0$ outside $B(0,2)$. Then $|\nabla \xi|$ is bounded by some constant $C$ (this constant can be taken arbitrarily close to $1$, but this is not important here).
Now let $\xi\_r(x) = \xi(x/r)$. This function satisfies: $0 \le \xi\_r \le 1$, $\xi\_r \equiv 1$ on $B(0,r)$, $\xi\_r \equiv 0$ outside $B(0,2r)$, moreover $|\nabla \xi\_r| \le C/r$ (with $C$ as above).
The right phrase to search would be "cut-off function". | One way to see the general idea is that if a smooth function $\xi$ has to go from taking the value $1$ at a point $x\_1$ to taking the value $0$ at another point $x\_0$ with $|x\_0 - x\_1| = r$, then $|\nabla \xi|$ will need to be at least $r^{-1}$ somewhere between $x\_1$ and $x\_0$. If this were not the case, then you could use the fundamental theorem of calculus along the line from $x\_0$ to $x\_1$ to get a contradiction.
The flip side is that you really can construct a smooth function that does this interpolation and satisfies $|\nabla \xi| \leq 2r^{-1}$. |
18,673,860 | I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the `HTML` code below to a container element with some values.
Where can I put this HTML to re-use in a smart way?
```
<a href="#" class="list-group-item">
<div class="image">
<img src="" />
</div>
<p class="list-group-item-text"></p>
</a>
```
JQuery
```
$('.search').keyup(function() {
$('.list-items').html(null);
$.each(items, function(index) {
// APPENDING CODE HERE
});
});
``` | 2013/09/07 | [
"https://Stackoverflow.com/questions/18673860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1358522/"
] | Add somewhere in body
```
<div class="hide">
<a href="#" class="list-group-item">
<table>
<tr>
<td><img src=""></td>
<td><p class="list-group-item-text"></p></td>
</tr>
</table>
</a>
</div>
```
then create css
```
.hide { display: none; }
```
and add to your js
```
$('#output').append( $('.hide').html() );
``` | Very good [answer](https://stackoverflow.com/a/46699845/4814971) from [DevWL](https://stackoverflow.com/users/2179965/devwl) about using the native HTML5 [template](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) element.
To contribute to this good question from the OP I would like to add on how to use this `template` element using jQuery, for example:
```
$($('template').html()).insertAfter( $('#somewhere_else') );
```
The content of the `template` is not html, but just treated as data, so you need to wrap the content into a jQuery object to then access jQuery's methods. |
18,673,860 | I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the `HTML` code below to a container element with some values.
Where can I put this HTML to re-use in a smart way?
```
<a href="#" class="list-group-item">
<div class="image">
<img src="" />
</div>
<p class="list-group-item-text"></p>
</a>
```
JQuery
```
$('.search').keyup(function() {
$('.list-items').html(null);
$.each(items, function(index) {
// APPENDING CODE HERE
});
});
``` | 2013/09/07 | [
"https://Stackoverflow.com/questions/18673860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1358522/"
] | Use HTML template instead!
==========================
Since the accepted answer would represent overloading script method, I would like to suggest another which is, in my opinion, much cleaner and more secure due to XSS risks which come with overloading scripts.
I made a [demo](https://codepen.io/DevWL/pen/YrjyWm?editors=1010) to show you how to use it in an action and how to inject one template into another, edit and then add to the document DOM.
### example html
```
<template id="mytemplate">
<style>
.image{
width: 100%;
height: auto;
}
</style>
<a href="#" class="list-group-item">
<div class="image">
<img src="" />
</div>
<p class="list-group-item-text"></p>
</a>
</template>
```
### example js
```
// select
var t = document.querySelector('#mytemplate');
// set
t.content.querySelector('img').src = 'demo.png';
t.content.querySelector('p').textContent= 'demo text';
// add to document DOM
var clone = document.importNode(t.content, true); // where true means deep copy
document.body.appendChild(clone);
```
HTML <template>
=================
* +Its content is effectively inert until activated. Essentially, your
markup is hidden DOM and does not render.
* +Any content within a template won't have side effects. Scripts don't run, images don't load, audio doesn't play ...until the template is used.
* +Content is considered not to be in the document. Using `document.getElementById()` or `querySelector()` in the main page won't return child nodes of a template.
* +Templates can be placed anywhere inside of `<head>`, `<body>`, or `<frameset>` and can contain any type of content which is allowed in those elements. Note that "anywhere" means that `<template>` can safely be used in places that the HTML parser disallows.
Fall back
=========
Browser support should not be an issue but if you want to cover all possibilities you can make an easy check:
>
> To feature detect `<template>`, create the DOM element and check that
> the .content property exists:
>
>
>
```
function supportsTemplate() {
return 'content' in document.createElement('template');
}
if (supportsTemplate()) {
// Good to go!
} else {
// Use old templating techniques or libraries.
}
```
Some insights about Overloading script method
=============================================
* +Nothing is rendered - the browser doesn't render this block because the `<script>` tag has `display:none` by default.
* +Inert - the browser doesn't parse the script content as JS because its type is set to something other than `"text/javascript"`.
* -Security issues - encourages the use of `.innerHTML`. Run-time string parsing of user-supplied data can easily lead to XSS vulnerabilities.
Full article: <https://www.html5rocks.com/en/tutorials/webcomponents/template/#toc-old>
Useful reference:
<https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode>
<http://caniuse.com/#feat=queryselector>
**CREATING WEB COMPONENTS** Creating custom web components tutorial using HTML templates by Trawersy Media:
<https://youtu.be/PCWaFLy3VUo> | Add somewhere in body
```
<div class="hide">
<a href="#" class="list-group-item">
<table>
<tr>
<td><img src=""></td>
<td><p class="list-group-item-text"></p></td>
</tr>
</table>
</a>
</div>
```
then create css
```
.hide { display: none; }
```
and add to your js
```
$('#output').append( $('.hide').html() );
``` |
18,673,860 | I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the `HTML` code below to a container element with some values.
Where can I put this HTML to re-use in a smart way?
```
<a href="#" class="list-group-item">
<div class="image">
<img src="" />
</div>
<p class="list-group-item-text"></p>
</a>
```
JQuery
```
$('.search').keyup(function() {
$('.list-items').html(null);
$.each(items, function(index) {
// APPENDING CODE HERE
});
});
``` | 2013/09/07 | [
"https://Stackoverflow.com/questions/18673860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1358522/"
] | You could decide to make use of a templating engine in your project, such as:
* [mustache](http://mustache.github.io/)
* [underscore.js](http://underscorejs.org/)
* [handlebars](http://handlebarsjs.com/)
If you don't want to include another library, John Resig offers a [jQuery solution](http://ejohn.org/blog/javascript-micro-templating/), similar to the one below.
---
Browsers and screen readers ignore unrecognized script types:
```
<script id="hidden-template" type="text/x-custom-template">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
</script>
```
Using jQuery, adding rows based on the template would resemble:
```
var template = $('#hidden-template').html();
$('button.addRow').click(function() {
$('#targetTable').append(template);
});
``` | Add somewhere in body
```
<div class="hide">
<a href="#" class="list-group-item">
<table>
<tr>
<td><img src=""></td>
<td><p class="list-group-item-text"></p></td>
</tr>
</table>
</a>
</div>
```
then create css
```
.hide { display: none; }
```
and add to your js
```
$('#output').append( $('.hide').html() );
``` |
18,673,860 | I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the `HTML` code below to a container element with some values.
Where can I put this HTML to re-use in a smart way?
```
<a href="#" class="list-group-item">
<div class="image">
<img src="" />
</div>
<p class="list-group-item-text"></p>
</a>
```
JQuery
```
$('.search').keyup(function() {
$('.list-items').html(null);
$.each(items, function(index) {
// APPENDING CODE HERE
});
});
``` | 2013/09/07 | [
"https://Stackoverflow.com/questions/18673860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1358522/"
] | Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.
While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (`<% for`), conditionals (`<% if`) and transforms (`<%= myString | uppercase %>`) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).
Templates Inside HTML
=====================
One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing `<script>` `type`, e.g. `<script type="text/template">`. For your case:
```
<script type="text/template" data-template="listitem">
<a href="${url}" class="list-group-item">
<table>
<tr>
<td><img src="${img}"></td>
<td><p class="list-group-item-text">${title}</p></td>
</tr>
</table>
</a>
</script>
```
On document load, read your template and tokenize it using a simple `String#split`
```
var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g);
```
Notice that with our token, you get it in the alternating `[text, property, text, property]` format. This lets us nicely map it using an `Array#map`, with a mapping function:
```
function render(props) {
return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}
```
Where `props` could look like `{ url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }`.
Putting it all together assuming you've parsed and loaded your `itemTpl` as above, and you have an `items` array in-scope:
```
$('.search').keyup(function () {
$('.list-items').append(items.map(function (item) {
return itemTpl.map(render(item)).join('');
}));
});
```
This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with `document.querySelector` and `.innerHTML`.
[jsfiddle](https://jsfiddle.net/jkoudys/5hcjo31u/)
Templates inside JS
===================
A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.
In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the `$.fn.html` method above.
```
const Item = ({ url, img, title }) => `
<a href="${url}" class="list-group-item">
<div class="image">
<img src="${img}" />
</div>
<p class="list-group-item-text">${title}</p>
</a>
`;
```
Then you could easily render it, even mapped from an array, like so:
```
$('.list-items').html([
{ url: '/foo', img: 'foo.png', title: 'Foo item' },
{ url: '/bar', img: 'bar.png', title: 'Bar item' },
].map(Item).join(''));
```
Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page. | Here's how to use the `<template>` element and jQuery a little more efficiently, since the other jQuery answers as of the time of writing use `.html()` which forces the HTML to be serialized and re-parsed.
First, the template to serve as an example:
```html
<template id="example"><div class="item">
<h1 class="title"></h1>
<p class="description"></p>
</div></template>
```
Note that there is no space between the `<template>` tag and its content, nor between the end of the content and `</template>`. If you put space in there, it will be copied too.
Now, the JS:
```js
// example data
const items = [
{name: "Some item", description: "Some description"},
// ...
];
const template = $("template#example").contents();
const templateTitle = template.find("h1.title");
const templateDescription = template.find("p.description");
const target = $("body");
for (const item of items) {
// fill in the placeholders
templateTitle.text(item.name);
templateDescription.text(item.description);
// copy the template and add it to the page
target.append(template.clone());
}
```
This will add a copy of the template, with placeholders replaced, for every item in the items array. Note that several elements, like `template` and `target`, are only retrieved once. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.