id
stringlengths 3
6
| prompt
stringlengths 100
55.1k
| response_j
stringlengths 30
18.4k
|
---|---|---|
213358 | I received an email today from a Stack Exchange Community Manager:
>
> As another year draws to a close, we wanted to do something fun and lighthearted with our communities, as a way of celebrating the many amazing people who make the sites awesome. So, we’re announcing **Winter Bash 2014!**
>
>
>
The Gist of it
==============
Thep Winter Bash is an annual event, where users earn “hats” for their
gravatars by completing certain tasks (analogous to badges). Certain
actions trigger the user receiving a hat, which their gravatar can
“wear”.
**At the end of the event (Jan 4), all hats will go back into storage.**
Individual users who don’t want to participate, don’t want to see
hats, and/or are generally anti-hat will have an *“I hate hats”*
option available. The only visual change to the Stack Exchange sites
themselves will be the presence of the hats and the *“I hate hats”*
button in the footer.
What we need from you
=====================
*Your opinion!*
Participation is optional, so if we happen to be heavily opposed to
head-wear we just have to say so.
Thus, please vote on whether you'd like us to take part, and to see a slightly more cheerful Emacs.SE for about a month.
When do we need to know?
========================
The default behavior is that we **opt in** as of December 1. So: if you're just not into hats and don't think Emacs.SE should be either, cast your straw ballot before the end of November so we can tell the powers that be.
*Update: it looks like a hat landslide!*
========================================
Given the strong opinion as of late-November (31-2), it looks like there's a strong mandate for holiday cheer. We've gone ahead and let the good folks at Stack Exchange know that we're on board for the hats.
Here's a little more info (*TL;DR: it starts on December 15, and if you'd like to opt out of the hats, click on the "I hate hats" button in the footer*):
>
> This event will run from 15 December 2014 to 4 January 2015. Users will be
> able to see their entire hat collection on winterbash2014.stackexchange.com.
> That site will also have a landing page, explaining the rules and other
> details of the event.
>
>
> Individual users who don’t want to participate, don’t want to see hats,
> and/or are generally anti-hat will have an “I hate hats” option available.
> And just like last time, at the end of the event, all hats will go back
> into storage.
>
>
> The only visual change to the Stack Exchange sites themselves will be the
> presence of the hats and the “I hate hats” button in the footer.
>
>
> | t
=
```
(when (hatp)
(wear-fun-hats))
``` |
213699 | [Composition root](http://blog.ploeh.dk/2011/07/28/CompositionRoot/) looks very strange pattern. We have a single very large God object that knows everything about anything.
What's the correct way to split up a Composition Root to some modules that will encapsulate initialization of its own part of the object graph?
What about [hierarchical dependency injection](https://angular.io/guide/hierarchical-dependency-injection)? | I don't agree with the premise that a Composition Root is a [God Object](https://en.wikipedia.org/wiki/God_object). While, conceptually, a Composition Root may contain many lines of code, it has only a [single responsibility](https://en.wikipedia.org/wiki/Single_responsibility_principle): compose an object graph.
A Composition Root can contain much data, and itself be coupled to the entire application, but it'd conceptually have only *one* method. It has only one reason to change, and that is if you want to change the way your application is composed.
Also, while the Composition Root is coupled to the rest of the application, the application code knows nothing of the Composition Root. Thus, the coupling goes in only one direction, as it should, according to the [Dependency Inversion Principle](https://en.wikipedia.org/wiki/Dependency_inversion_principle).
A way to put it is that a God object violates all five [SOLID principles](https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)), while a Composition Root at the very least follows both SRP, ISP, and DIP. I don't think the [OCP](https://en.wikipedia.org/wiki/Open/closed_principle) or [LSP](https://en.wikipedia.org/wiki/Liskov_substitution_principle) apply here.
All that said, if a Composition Root composes a big application, it could still contain much code. If you find that it becomes unmanageable, then how should you break it down into smaller chunks of code?
The same way you decompose any other code. It Depends™.
I hope I never wrote or said that a Composition Root can only be a singe class. If I did, I'd like to retract that. When writing Composition Roots, I routinely split its responsibilities over more than a single class (although rarely more than a handful). You can apply any design pattern or other OOD technique you'd like in order to achieve that goal. The Composition Root then becomes a [Facade](https://en.wikipedia.org/wiki/Facade_pattern) over your implementation.
I can't give much more guidance than that, because it depends on the application architecture. If you do vertical slicing, you'd most likely need to structure the Composition Root differently than if you do horizontal layering, and so on.
That said, as a general rule I *do not* find it useful to attempt to decompose a dependency graph into sub-trees. First of all because a dependency graph is a *graph*, and not a tree, but also because you often need to interleave multiple independent concerns. You could, for example, have sub-graphs that are responsible for various sub-parts of your application, but then you'd need to interleave the same logging mechanism, or the same caching mechanism, or the same security mechanism, etc. throughout the entire graph. You can't easily do that if you try to separate them. |
213875 | A SEO question if someone would be kind enough to help.
A friend has an existing website with plenty of issues and I decided to rebuild it from scratch. Reasons?
* Many URL's don't match the actual title of the post + different languages have the same url almost, except "eng-" in front. What the f\*\*\* ? :)
* No H1 tags, no proper title/alt attributes on links/images
* Very slow loading, JS/CSS not compressed/optimised, huge images, no caching; generally designed pretty bad
* plenty of other things approached in a bad way
The question I am having is about this new page now: what exactly happens when the new page will be uploaded and will replace the old one?
I wrote down most of the 301 redirects (for each post and archive pages etc.) in htaccess.
If I understand correctly, 301 redirects will help keep the SEO rank somewhat; but, can it get better after a change so big?
Furthermore, what are the proposed steps to take when rebuilding the page from scratch if you keep in mind that most of the content will stay, but URLs will all change (some new content will be added too) ? I read somewhere that it's a good idea to get a new sitemap.xml and send it to google via webmaster tools ?
Is doing 301 redirects the right approach and if so, is that all?
Also, I have concerns about keeping the current SEO rank, since it's probably really bad (because of all the things I mentioned above) - would be lovely if I could somehow start anew for this domain; but that's probably not possible? So how to get Google to "forget" about the old page and just index the new without loosing SEO rank (and improving it even!).
Any push in the right direction appreciated! | Nofollow *is* what you are looking for. It doesn't pass any link juice and google wont open or save them.
>
> In general, we don't follow them. This means that Google does not
> transfer PageRank or anchor text across these links. Essentially,
> using nofollow causes us to drop the target links from our overall
> graph of the web. However, the target pages may still appear in our
> index if other sites link to them without using nofollow, or if the
> URLs are submitted to Google in a Sitemap.
>
>
>
[Source](https://support.google.com/webmasters/answer/96569?hl=en)
Googles crawlers runs javascript and renders the page as close to what a web browser as it can. It will even [post form submits](https://webmasters.googleblog.com/2008/04/crawling-through-html-forms.html).
I guess you could hide it behind a captcha since the whole idea of a captcha is that a robot should be able to access it. |
214125 | I have a `scala.collection.immutable.HashSet` that I want to randomly select an element from.
I could solve the problem with an extension method like this:
```
implicit class HashSetExtensions[T](h: HashSet[T]) {
def nextRandomElement (): Option[T] = {
val list = h.toList
list match {
case null | Nil => None
case _ => Some (list (Random.nextInt (list.length)))
}
}
}
```
...but converting to a list will be slow. What would be the most efficient solution? | **WARNING** This answer is for experimental use only. For real project you probably should use your own collection types.
So i did some research in the [HashSet source](https://github.com/scala/scala/blob/v2.11.6/src/library/scala/collection/immutable/HashSet.scala#L1) and i think there is little opportunity to someway extract the inner structure of most valuable [`class HashTrieSet`](https://github.com/scala/scala/blob/v2.11.6/src/library/scala/collection/immutable/HashSet.scala#L1) without package violation.
I did come up with this code, which is extended [Ben Reich's solution](https://stackoverflow.com/a/29802897/210905):
```
package scala.collection
import scala.collection.immutable.HashSet
import scala.util.Random
package object random {
implicit class HashSetRandom[T](set: HashSet[T]) {
def randomElem: Option[T] = set match {
case trie: HashSet.HashTrieSet[T] => {
trie.elems(Random.nextInt(trie.elems.length)).randomElem
}
case _ => Some(set.size) collect {
case size if size > 0 => set.iterator.drop(Random.nextInt(size)).next
}
}
}
}
```
file should be created somewhere in the `src/scala/collection/random` folder
note the `scala.collection` package - this thing makes the `elems` part of `HashTrieSet` visible. This is only solution i could think, which could run better than `O(n)`. Current version should have complexity `O(ln(n))` as any of `immutable.HashSet`'s operation s.
Another warning - private structure of `HashSet` is not part of scala's standard library API, so it could change any version making this code erroneous (though it's didn't changed since 2.8) |
214340 | Let's say I have a dataset (`sim_data`) with 16 variables, including psychological data (15 items from a questionnaire), and the first column is a categorical variable (country).
I can easily get means/sd **by group** using:
```
sim_data.groupby("country").describe()
```
However, I would like to apply a function (Cronbach's alpha) from a specific package `(pip install pingouin`) and (`import pingouin as pg`) with this data and get the results **by group** (as I did previously). The following code is not working.
```
pg.cronbach_alpha(sim_data.groupby("country"))
```
Neither this one
```
sim_data.groupby('country').apply(lambda grp: pg.cronbach_alpha())
```
Important notes:
I'm adapting the code from [here](https://stackoverflow.com/questions/15374597/apply-function-to-pandas-groupby)
That's my routine and dataset if you want to reproduce
```
import pandas as pd
import numpy as np
import pingouin as pg
from numpy import nan
sim_data = pd.DataFrame.from_dict({'country': {33003: 'Vietnam',
12172: 'Macedonia',
5192: 'Ghana',
32511: 'Vietnam',
7813: 'Ghana',
21440: 'Armenia',
32912: 'Vietnam',
20609: 'Georgia',
7751: 'Ghana',
31228: 'Laos',
36230: 'Serbia',
32025: 'Laos',
21758: 'Armenia',
35730: 'Serbia',
8444: 'Kenya',
19946: 'Georgia',
37532: 'Serbia',
22926: 'Armenia',
27204: 'Sri_Lanka',
31959: 'Laos',
24535: 'Sri_Lanka',
19433: 'Georgia',
17137: 'Ukraine',
26103: 'Sri_Lanka',
33878: 'Vietnam',
39053: 'Philippines',
33799: 'Vietnam',
37183: 'Serbia',
3606: 'Colombia',
2561: 'Colombia',
29960: 'Laos',
32397: 'Vietnam',
39539: 'Philippines',
431: 'Bolivia',
36842: 'Serbia',
16926: 'Ukraine',
9287: 'Kenya',
34246: 'Vietnam',
16277: 'Ukraine',
34105: 'Vietnam',
11032: 'Kenya',
41457: 'Philippines',
34380: 'Vietnam',
19482: 'Georgia',
1844: 'Bolivia',
9552: 'Kenya',
35437: 'Vietnam',
29555: 'Laos',
29993: 'Laos',
28114: 'Yunnan',
15: 'Bolivia',
27712: 'Yunnan',
12313: 'Macedonia',
11631: 'Kenya'},
'step_bfi1_ab_cor': {33003: 1.8333332538604736,
12172: 1.5,
5192: nan,
32511: 1.4166666269302368,
7813: nan,
21440: 2.4166665077209473,
32912: 1.0,
20609: 4.0,
7751: 0.5,
31228: 2.25,
36230: 2.9375,
32025: 1.875,
21758: 3.9166665077209473,
35730: 2.25,
8444: 3.5833334922790527,
19946: 2.3333334922790527,
37532: 4.0625,
22926: 3.5,
27204: 4.083333492279053,
31959: 3.0,
24535: 3.5,
19433: 2.0833334922790527,
17137: 3.25,
26103: 1.1666666269302368,
33878: 1.6666667461395264,
39053: 1.75,
33799: 0.75,
37183: 3.375,
3606: 4.25,
2561: 2.8333334922790527,
29960: 4.25,
32397: 3.8333332538604736,
39539: 2.5625,
431: 3.25,
36842: 3.8125,
16926: 1.9166667461395264,
9287: 2.3333334922790527,
34246: 1.0,
16277: 2.9166667461395264,
34105: 1.5833333730697632,
11032: 1.75,
41457: 3.75,
34380: 1.5833332538604736,
19482: 0.9166666269302368,
1844: 3.6666667461395264,
9552: 2.25,
35437: 1.0833332538604736,
29555: 2.25,
29993: 4.25,
28114: 3.6666665077209473,
15: 3.0,
27712: 3.25,
12313: 2.0833334922790527,
11631: 2.5833334922790527},
'step_bfi3_ab_cor': {33003: 3.8333332538604736,
12172: 3.5,
5192: nan,
32511: 3.4166665077209473,
7813: nan,
21440: 3.4166665077209473,
32912: 3.0,
20609: 4.0,
7751: 2.5,
31228: 4.25,
36230: 3.6875,
32025: 3.875,
21758: 3.9166665077209473,
35730: 2.25,
8444: 4.583333492279053,
19946: 2.3333334922790527,
37532: 2.5625,
22926: 2.5,
27204: 3.0833334922790527,
31959: 4.0,
24535: 2.5,
19433: 3.0833334922790527,
17137: 3.25,
26103: 3.1666665077209473,
33878: 3.6666667461395264,
39053: 2.5,
33799: 3.75,
37183: 3.375,
3606: 4.25,
2561: 2.8333334922790527,
29960: 3.25,
32397: 2.8333332538604736,
39539: 2.5625,
431: 3.25,
36842: 3.0625,
16926: 3.9166667461395264,
9287: 3.3333334922790527,
34246: 4.0,
16277: 1.9166667461395264,
34105: 3.5833334922790527,
11032: 3.75,
41457: 2.25,
34380: 2.5833332538604736,
19482: 3.9166665077209473,
1844: 2.6666667461395264,
9552: 3.25,
35437: 3.0833332538604736,
29555: 2.25,
29993: 2.25,
28114: 3.6666665077209473,
15: 3.0,
27712: 2.25,
12313: 4.083333492279053,
11631: 3.5833334922790527},
'step_bfi5_ab_cor': {33003: 0.8333332538604736,
12172: 0.5,
5192: nan,
32511: 2.4166665077209473,
7813: nan,
21440: 2.4166665077209473,
32912: 2.0,
20609: 2.0,
7751: 0.5,
31228: 3.25,
36230: 3.6875,
32025: 1.875,
21758: 3.9166665077209473,
35730: 2.25,
8444: 1.5833333730697632,
19946: 1.3333333730697632,
37532: 1.8125,
22926: 1.5,
27204: 2.0833334922790527,
31959: 3.0,
24535: 1.5,
19433: 1.0833333730697632,
17137: 2.25,
26103: 4.166666507720947,
33878: 1.6666667461395264,
39053: 1.75,
33799: 1.75,
37183: 3.375,
3606: 2.25,
2561: 1.8333333730697632,
29960: 3.25,
32397: 1.8333332538604736,
39539: 2.5625,
431: 1.25,
36842: 3.8125,
16926: 1.9166667461395264,
9287: 1.3333333730697632,
34246: 3.0,
16277: 1.9166667461395264,
34105: 1.5833333730697632,
11032: 2.75,
41457: 2.25,
34380: 2.5833332538604736,
19482: 1.9166666269302368,
1844: 3.6666667461395264,
9552: 1.25,
35437: 1.0833332538604736,
29555: 1.25,
29993: 3.25,
28114: 2.6666665077209473,
15: 2.0,
27712: 3.25,
12313: 1.0833333730697632,
11631: 3.5833334922790527},
'step_bfi6_ab_cor': {33003: 4.1666669845581055,
12172: 1.5,
5192: nan,
32511: 1.5833333730697632,
7813: nan,
21440: 2.5833334922790527,
32912: 4.0,
20609: 3.0,
7751: 1.5,
31228: 2.75,
36230: 2.8125,
32025: 4.125,
21758: 4.083333492279053,
35730: 1.25,
8444: 3.4166665077209473,
19946: 2.6666665077209473,
37532: 3.9375,
22926: 2.5,
27204: 2.9166665077209473,
31959: 2.0,
24535: 2.5,
19433: 2.9166665077209473,
17137: 2.75,
26103: 0.8333333730697632,
33878: 4.3333330154418945,
39053: 2.5,
33799: 4.25,
37183: 3.125,
3606: 2.75,
2561: 3.1666665077209473,
29960: 3.75,
32397: 1.1666667461395264,
39539: 3.9375,
431: 1.75,
36842: 2.6875,
16926: 2.0833332538604736,
9287: 2.6666665077209473,
34246: 3.0,
16277: 2.0833332538604736,
34105: 2.4166665077209473,
11032: 3.25,
41457: 4.25,
34380: 2.4166667461395264,
19482: 4.083333492279053,
1844: 3.3333332538604736,
9552: 2.75,
35437: 2.9166667461395264,
29555: 1.75,
29993: 2.75,
28114: 3.3333334922790527,
15: 2.0,
27712: 1.75,
12313: 2.9166665077209473,
11631: 3.4166665077209473},
'step_bfi7_ab_cor': {33003: 1.8333332538604736,
12172: 1.5,
5192: nan,
32511: 1.4166666269302368,
7813: nan,
21440: 2.4166665077209473,
32912: 3.0,
20609: 2.0,
7751: 1.5,
31228: 3.25,
36230: 3.6875,
32025: 1.875,
21758: 3.9166665077209473,
35730: 3.75,
8444: 2.5833334922790527,
19946: 1.3333333730697632,
37532: 4.0625,
22926: 2.5,
27204: 3.0833334922790527,
31959: 1.0,
24535: 1.5,
19433: 2.0833334922790527,
17137: 2.25,
26103: 2.1666665077209473,
33878: 2.6666667461395264,
39053: 3.25,
33799: 0.75,
37183: 3.375,
3606: 2.25,
2561: 1.8333333730697632,
29960: 2.25,
32397: 3.8333332538604736,
39539: 4.0625,
431: 3.25,
36842: 3.8125,
16926: 1.9166667461395264,
9287: 2.3333334922790527,
34246: 2.0,
16277: 2.9166667461395264,
34105: 1.5833333730697632,
11032: 1.75,
41457: 3.75,
34380: 2.5833332538604736,
19482: 2.9166665077209473,
1844: 1.6666667461395264,
9552: 2.25,
35437: 2.0833332538604736,
29555: 2.25,
29993: 2.25,
28114: 3.6666665077209473,
15: 3.0,
27712: 1.25,
12313: 4.083333492279053,
11631: 3.5833334922790527},
'step_bfi10_ab_cor': {33003: 3.8333332538604736,
12172: 3.5,
5192: nan,
32511: 3.4166665077209473,
7813: nan,
21440: 3.4166665077209473,
32912: 3.0,
20609: 4.0,
7751: 3.5,
31228: 3.25,
36230: 3.6875,
32025: 1.875,
21758: 3.9166665077209473,
35730: 2.25,
8444: 2.5833334922790527,
19946: 4.333333492279053,
37532: 2.5625,
22926: 2.5,
27204: 4.083333492279053,
31959: 2.0,
24535: 0.4999999403953552,
19433: 3.0833334922790527,
17137: 3.25,
26103: 3.1666665077209473,
33878: 2.6666667461395264,
39053: 3.25,
33799: 1.75,
37183: 3.375,
3606: 2.25,
2561: 2.8333334922790527,
29960: 2.25,
32397: 1.8333332538604736,
39539: 4.0625,
431: 3.25,
36842: 3.0625,
16926: 3.9166667461395264,
9287: 2.3333334922790527,
34246: 4.0,
16277: 2.9166667461395264,
34105: 2.5833334922790527,
11032: 3.75,
41457: 2.25,
34380: 3.5833332538604736,
19482: 3.9166665077209473,
1844: 3.6666667461395264,
9552: 3.25,
35437: 3.0833332538604736,
29555: 2.25,
29993: 2.25,
28114: 3.6666665077209473,
15: 3.0,
27712: 3.25,
12313: 2.0833334922790527,
11631: 4.583333492279053},
'step_bfi17_ab_cor': {33003: 2.8333332538604736,
12172: 1.5,
5192: nan,
32511: 3.4166665077209473,
7813: nan,
21440: 1.4166666269302368,
32912: 2.0,
20609: 1.0,
7751: 3.5,
31228: 3.25,
36230: 2.1875,
32025: nan,
21758: 3.9166665077209473,
35730: 3.75,
8444: 3.5833334922790527,
19946: 2.3333334922790527,
37532: 2.5625,
22926: 2.5,
27204: 3.0833334922790527,
31959: 3.0,
24535: 2.5,
19433: 4.083333492279053,
17137: 2.25,
26103: 2.1666665077209473,
33878: 2.6666667461395264,
39053: 1.75,
33799: 2.75,
37183: 3.375,
3606: 4.25,
2561: 0.8333333730697632,
29960: 3.25,
32397: 1.8333332538604736,
39539: 2.5625,
431: 1.25,
36842: 2.3125,
16926: 2.9166667461395264,
9287: 3.3333334922790527,
34246: 2.0,
16277: 2.9166667461395264,
34105: 3.5833334922790527,
11032: 2.75,
41457: 3.75,
34380: 2.5833332538604736,
19482: 3.9166665077209473,
1844: 3.6666667461395264,
9552: 3.25,
35437: 2.0833332538604736,
29555: 2.25,
29993: 2.25,
28114: 3.6666665077209473,
15: 3.0,
27712: 2.25,
12313: 3.0833334922790527,
11631: 3.5833334922790527},
'step_bfi19_ab_cor': {33003: 3.1666667461395264,
12172: 1.5,
5192: nan,
32511: 1.5833333730697632,
7813: nan,
21440: 2.5833334922790527,
32912: 2.0,
20609: 1.0,
7751: 1.5,
31228: 2.75,
36230: 2.0625,
32025: 2.125,
21758: 1.0833333730697632,
35730: 4.25,
8444: 3.4166665077209473,
19946: 3.6666665077209473,
37532: 0.9375,
22926: 2.5,
27204: 2.9166665077209473,
31959: 3.0,
24535: 1.5,
19433: 2.9166665077209473,
17137: 2.75,
26103: 1.8333333730697632,
33878: 3.3333332538604736,
39053: 3.25,
33799: 3.25,
37183: 3.125,
3606: 2.75,
2561: 3.1666665077209473,
29960: 1.75,
32397: 3.1666667461395264,
39539: 2.4375,
431: 1.75,
36842: 2.6875,
16926: 3.0833332538604736,
9287: 4.666666507720947,
34246: 3.0,
16277: 2.0833332538604736,
34105: 3.4166665077209473,
11032: 3.25,
41457: 2.75,
34380: 2.4166667461395264,
19482: 3.0833334922790527,
1844: 4.3333330154418945,
9552: 2.75,
35437: 2.9166667461395264,
29555: 1.75,
29993: 1.75,
28114: 3.3333334922790527,
15: 2.0,
27712: 2.75,
12313: 0.9166666269302368,
11631: 2.4166665077209473},
'step_bfi23_ab_cor': {33003: 1.1666667461395264,
12172: 3.5,
5192: nan,
32511: 4.583333492279053,
7813: nan,
21440: 3.5833334922790527,
32912: 2.0,
20609: 4.0,
7751: 4.5,
31228: 2.75,
36230: 3.5625,
32025: nan,
21758: 4.083333492279053,
35730: 4.25,
8444: 3.4166665077209473,
19946: 3.6666665077209473,
37532: 3.9375,
22926: 3.5,
27204: 2.9166665077209473,
31959: 3.0,
24535: 2.5,
19433: 2.9166665077209473,
17137: 2.75,
26103: 3.8333334922790527,
33878: 1.3333332538604736,
39053: 1.75,
33799: 2.25,
37183: 4.625,
3606: 2.75,
2561: 3.1666665077209473,
29960: 2.75,
32397: 3.1666667461395264,
39539: 2.4375,
431: 3.75,
36842: 3.4375,
16926: 3.0833332538604736,
9287: 1.6666666269302368,
34246: 3.0,
16277: 3.0833332538604736,
34105: 1.4166666269302368,
11032: 4.25,
41457: 2.75,
34380: 2.4166667461395264,
19482: 4.083333492279053,
1844: 3.3333332538604736,
9552: 3.75,
35437: 1.9166667461395264,
29555: 2.75,
29993: 2.75,
28114: 3.3333334922790527,
15: 4.0,
27712: 2.75,
12313: 2.9166665077209473,
11631: 3.4166665077209473},
'step_bfi30_ab_cor': {33003: 1.8333332538604736,
12172: 3.5,
5192: nan,
32511: 2.4166665077209473,
7813: nan,
21440: 3.4166665077209473,
32912: 4.0,
20609: 4.0,
7751: 3.5,
31228: 3.25,
36230: 3.6875,
32025: 1.875,
21758: 3.9166665077209473,
35730: 2.25,
8444: 2.5833334922790527,
19946: 4.333333492279053,
37532: 4.0625,
22926: 3.5,
27204: 4.083333492279053,
31959: 4.0,
24535: 3.5,
19433: 4.083333492279053,
17137: 3.25,
26103: 3.1666665077209473,
33878: 3.6666667461395264,
39053: 1.0,
33799: 0.75,
37183: 3.375,
3606: 4.25,
2561: 2.8333334922790527,
29960: 3.25,
32397: 2.8333332538604736,
39539: 4.0625,
431: 3.25,
36842: 3.8125,
16926: 2.9166667461395264,
9287: 2.3333334922790527,
34246: 3.0,
16277: 2.9166667461395264,
34105: 2.5833334922790527,
11032: 3.75,
41457: 3.75,
34380: 3.5833332538604736,
19482: 3.9166665077209473,
1844: 3.6666667461395264,
9552: 2.25,
35437: 3.0833332538604736,
29555: 2.25,
29993: 3.25,
28114: 3.6666665077209473,
15: 1.0,
27712: 3.25,
12313: 4.083333492279053,
11631: 4.583333492279053},
'step_bfi32_ab_cor': {33003: 3.8333332538604736,
12172: 1.5,
5192: nan,
32511: 3.4166665077209473,
7813: nan,
21440: 3.4166665077209473,
32912: 4.0,
20609: 4.0,
7751: 3.5,
31228: 3.25,
36230: 2.9375,
32025: 2.875,
21758: 3.9166665077209473,
35730: 2.25,
8444: 3.5833334922790527,
19946: 4.333333492279053,
37532: 3.3125,
22926: 3.5,
27204: 4.083333492279053,
31959: 3.0,
24535: 2.5,
19433: 4.083333492279053,
17137: 3.25,
26103: 3.1666665077209473,
33878: 3.6666667461395264,
39053: 1.75,
33799: 3.75,
37183: 1.875,
3606: 4.25,
2561: 2.8333334922790527,
29960: 3.25,
32397: 2.8333332538604736,
39539: 2.5625,
431: 3.25,
36842: 3.0625,
16926: 2.9166667461395264,
9287: 2.3333334922790527,
34246: 4.0,
16277: 2.9166667461395264,
34105: 3.5833334922790527,
11032: 3.75,
41457: 2.25,
34380: 2.5833332538604736,
19482: 3.9166665077209473,
1844: 3.6666667461395264,
9552: 3.25,
35437: 3.0833332538604736,
29555: 3.25,
29993: 3.25,
28114: 3.6666665077209473,
15: 3.0,
27712: 2.25,
12313: 3.0833334922790527,
11631: 3.5833334922790527},
'step_bfi33_ab_cor': {33003: 1.8333332538604736,
12172: 3.5,
5192: nan,
32511: 3.4166665077209473,
7813: nan,
21440: 2.4166665077209473,
32912: 4.0,
20609: 2.0,
7751: 3.5,
31228: 3.25,
36230: 2.9375,
32025: 3.875,
21758: 3.9166665077209473,
35730: 3.75,
8444: 3.5833334922790527,
19946: 4.333333492279053,
37532: 4.0625,
22926: 2.5,
27204: 3.0833334922790527,
31959: 2.0,
24535: 1.5,
19433: 2.0833334922790527,
17137: 1.25,
26103: 3.1666665077209473,
33878: 3.6666667461395264,
39053: 2.5,
33799: 3.75,
37183: 3.375,
3606: 2.25,
2561: 2.8333334922790527,
29960: 3.25,
32397: 2.8333332538604736,
39539: 3.3125,
431: 2.25,
36842: 3.0625,
16926: 2.9166667461395264,
9287: 3.3333334922790527,
34246: 3.0,
16277: 2.9166667461395264,
34105: 3.5833334922790527,
11032: 3.75,
41457: 3.75,
34380: 3.5833332538604736,
19482: 3.9166665077209473,
1844: 3.6666667461395264,
9552: 2.25,
35437: 3.0833332538604736,
29555: 3.25,
29993: 2.25,
28114: 3.6666665077209473,
15: 3.0,
27712: 1.25,
12313: 3.0833334922790527,
11631: 3.5833334922790527},
'step_bfi34_ab_cor': {33003: 3.8333332538604736,
12172: 1.5,
5192: nan,
32511: 3.4166665077209473,
7813: nan,
21440: 3.4166665077209473,
32912: 3.0,
20609: 1.0,
7751: 3.5,
31228: 2.25,
36230: 2.9375,
32025: nan,
21758: 3.9166665077209473,
35730: 3.75,
8444: 2.5833334922790527,
19946: 3.3333334922790527,
37532: 2.5625,
22926: 2.5,
27204: 2.0833334922790527,
31959: 2.0,
24535: 1.5,
19433: 3.0833334922790527,
17137: 3.25,
26103: 2.1666665077209473,
33878: 2.6666667461395264,
39053: 2.5,
33799: 3.75,
37183: 3.375,
3606: 1.25,
2561: 3.8333334922790527,
29960: 2.25,
32397: 1.8333332538604736,
39539: 2.5625,
431: 2.25,
36842: 2.3125,
16926: 2.9166667461395264,
9287: 3.3333334922790527,
34246: 4.0,
16277: 2.9166667461395264,
34105: 1.5833333730697632,
11032: 3.75,
41457: 2.25,
34380: 1.5833332538604736,
19482: 3.9166665077209473,
1844: 3.6666667461395264,
9552: 3.25,
35437: 3.0833332538604736,
29555: 2.25,
29993: 2.25,
28114: 2.6666665077209473,
15: 3.0,
27712: 2.25,
12313: 1.0833333730697632,
11631: 2.5833334922790527},
'step_bfi36_ab_cor': {33003: 2.8333332538604736,
12172: 3.5,
5192: nan,
32511: 3.4166665077209473,
7813: nan,
21440: 2.4166665077209473,
32912: 3.0,
20609: 4.0,
7751: 2.5,
31228: 3.25,
36230: 3.6875,
32025: 1.875,
21758: 1.9166666269302368,
35730: 2.25,
8444: 3.5833334922790527,
19946: 4.333333492279053,
37532: 3.3125,
22926: 3.5,
27204: 3.0833334922790527,
31959: 3.0,
24535: 2.5,
19433: 4.083333492279053,
17137: 2.25,
26103: 2.1666665077209473,
33878: 3.6666667461395264,
39053: 3.25,
33799: 3.75,
37183: 3.375,
3606: 4.25,
2561: 2.8333334922790527,
29960: 3.25,
32397: 1.8333332538604736,
39539: 2.5625,
431: 2.25,
36842: 3.0625,
16926: 1.9166667461395264,
9287: 0.3333333730697632,
34246: 2.0,
16277: 2.9166667461395264,
34105: 3.5833334922790527,
11032: 3.75,
41457: 3.75,
34380: 3.5833332538604736,
19482: 3.9166665077209473,
1844: 3.6666667461395264,
9552: 3.25,
35437: 3.0833332538604736,
29555: 1.25,
29993: 2.25,
28114: 3.6666665077209473,
15: 3.0,
27712: 3.25,
12313: 4.083333492279053,
11631: 3.5833334922790527},
'step_bfi39_ab_cor': {33003: 4.1666669845581055,
12172: 3.5,
5192: nan,
32511: 4.583333492279053,
7813: nan,
21440: 2.5833334922790527,
32912: 3.0,
20609: 1.0,
7751: 2.5,
31228: 3.75,
36230: 4.3125,
32025: 1.125,
21758: 4.083333492279053,
35730: 2.75,
8444: 3.4166665077209473,
19946: 3.6666665077209473,
37532: 2.4375,
22926: 2.5,
27204: 2.9166665077209473,
31959: 3.0,
24535: 1.5,
19433: 2.9166665077209473,
17137: 2.75,
26103: 2.8333334922790527,
33878: 3.3333332538604736,
39053: 3.25,
33799: 3.25,
37183: 1.625,
3606: 3.75,
2561: 3.1666665077209473,
29960: 3.75,
32397: 3.1666667461395264,
39539: 0.9375,
431: 2.75,
36842: 2.6875,
16926: 3.0833332538604736,
9287: 2.6666665077209473,
34246: 3.0,
16277: 4.0833330154418945,
34105: 4.416666507720947,
11032: 2.25,
41457: 1.25,
34380: 2.4166667461395264,
19482: 1.0833333730697632,
1844: 3.3333332538604736,
9552: 1.75,
35437: 3.9166667461395264,
29555: 2.75,
29993: 2.75,
28114: 3.3333334922790527,
15: 4.0,
27712: 2.75,
12313: 2.9166665077209473,
11631: 2.4166665077209473}})
```
I'm a heavy R user and and I'm translating the following code to python
```
sim_data %>%
select('step_bfi1_ab_cor':'step_bfi39_ab_cor', "country") %>%
nest(-country) %>%
mutate(result=map(data, ~psych::alpha(.)$total)) %>%
select(country,result) %>%
unnest()
```
Suggestions are welcome. Please let me know if there's another way (more elegant) to solve my problem.
Thank you | Usually, base R (not tidy R) is easier to translate to Python Pandas. What your R code appears to be doing is subsetting the dataframe by *country* column and running each subset into `psych::alpha()`. Then extracted statistics are returned into a data frame with country indicator.
You can do the exact same with base R's `by` which can translate into Pandas' `groupby` in a list comprehension. It looks like `psych::alpha` returns more statistics than `pingouin.cronbach_alpha`. Adjust fields and return values below as needed in untested code.
**Base R** *(using [docs](https://www.rdocumentation.org/packages/psych/versions/2.0.7/topics/alpha))*
```
# DEFINE METHOD
run_cronbach_alpha <- function(sub) {
results <- psych::alpha(sub)$total # RETURNS LIST
data.frame(country = sub$country[1],
raw_alpha = results$raw_alpha,
std.alpha = results$std.alpha,
G6 = results$G6,
average_r = results$average_r,
median_r = results$median,
mean = results$mean,
sd = results$sd)
}
# FILTER COLUMNS IN DATA FRAME
sim_short <- sim_data[c("step_bfi1_ab_cor", ..., "step_bfi39_ab_cor", "country")]
# RUN METHOD BY COUNTRY SUBSETS TO RETURN DF LIST
results_df_list <- by(sim_short, sim_short$country, run_cronbach_alpha)
# ROW BIND ALL DFs TO SINGLE FINAL DATA FRAME
results_df <- do.call(rbind.data.frame, results_df_list)
```
**Python Pandas** *(using [docs](https://pingouin-stats.org/generated/pingouin.cronbach_alpha.html))*
```
# DEFINE METHOD
def run_cronbach_alpha(c, sub):
results = pg.cronbach_alpha(sub.drop(["country"], axis="columns")) # RETURNS TUPLE
return pd.DataFrame({'country': c, 'cronbach_alpha': results[0], index=[0]})
# FILTER COLUMNS IN DATA FRAME
sim_short = sim_data.reindex(["step_bfi1_ab_cor", ..., "step_bfi39_ab_cor", "country"],
axis='columns')
# RUN METHOD BY COUNTRY SUBSETS TO RETURN DF LIST
results_df_list = [run_cronbach_alpha(i, df) for i,df in sim_short.groupby("country")]
# CONCATENATE ALL DFs TO SINGLE FINAL DATA FRAME
results_df = pd.concat(results_df_list)
``` |
214822 | First, I'm sorry for my english, it's not my native language. I try to do my best
I have some problems with my display. I've a java.util.List of Panel with some elements already inside. I'd like to insert them into a JPanel at the creation of my JDialog.
There are two JButton in my JDialog, 'add' and 'delete', wich, respectively add a new JPanel at the bottom of the JPanels and the other which delete the last JPanel added.
My problem is that there is a large gap between two JPanel, regardless of the number of JPanel added and I don't know why...
Two demonstrations pics :
---
![my JDialog with 3 JPanel](https://i.stack.imgur.com/BUB4g.png)
my JDialog with more than 3 JPanel
----------------------------------
My layouts are GridBagLayout and I'm using WindowBuilder with Eclipse Indigo. Here is now my code. I think the problem come from the value that I assign to anchor in the GridBagConstraints...
listChamps is the List of JPanel that I want to insert
panelListFile is the JPanel where listChamps' elements are inserted
```
for (int i = 0; i < listChamps.size (); ++i) {
GridBagConstraints gbc_pan = new GridBagConstraints ();
gbc_pan.gridwidth = 1;
gbc_pan.fill = GridBagConstraints.HORIZONTAL;
gbc_pan.anchor = GridBagConstraints.NORTH;
gbc_pan.gridx = 0;
gbc_pan.gridy = i;
panelListFiles.add (listChamps.get (i), gbc_pan);
}
```
Thanks you. | I using two ways and in both cases should be added a [JPanel](http://docs.oracle.com/javase/tutorial/uiswing/components/panel.html) nested [JComponent](http://docs.oracle.com/javase/tutorial/uiswing/components/index.html)s,
* [JPanel with JComponents to the JTable](https://stackoverflow.com/a/6355910/714968)
* [JPanel with JComponents to the another Container](https://stackoverflow.com/a/7224745/714968) |
214994 | $ npx react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 864 file(s) to forward-jetify. Using 4 workers...
info Starting JS server...
info Launching emulator...
error Failed to launch the emulator. Reason: Could not start an emulator within 30 seconds.
warn Please launch an emulator manually or connect a device. Otherwise, the app may fail to launch.
info Installing the app...
FAILURE: Build failed with an exception.
* What went wrong:
Could not initialize class org.codehaus.groovy.runtime.InvokerHelper
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at <https://help.gradle.org>
BUILD FAILED in 1m 23s
error Failed to install the app. Make sure you have the Android development environment set up: <https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment>. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
FAILURE: Build failed with an exception.
* What went wrong:
Could not initialize class org.codehaus.groovy.runtime.InvokerHelper
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at <https://help.gradle.org>
BUILD FAILED in 1m 23s
```
at checkExecSyncError (child_process.js:629:11)
at execFileSync (child_process.js:647:13)
at runOnAllDevices (E:\work\react-native\AwesomeProject1\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:39)
``` | In the `React Native` version **0.62.x** even the initialized application is not ready for a development build.
I change the **Gradle** version to the latest and I could to have a clean build, so change this file:
```
// this file => /android/gradle/wrapper/gradle-wrapper.properties
```
from:
```
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-all.zip
```
to:
```
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
```
**Pay Attention**: *The latest version of the Gradle for my time is **6.5**. when you are reading this answer please check [this link](https://gradle.org/releases/) to see the latest version number of the Gradle.*
### Update Aug 15, 2022
7.5.1
===== |
215163 | Let $X$ be an uncountable set with the discrete topology. Prove that the one point compactification $Y$ of $X$ cannot be imbedded into the plane $\mathbb{R}^{2}$.
I'm assuming that there exists an imbedding $f: Y \rightarrow f(Y)$ of $Y$ into $\mathbb{R}^{2}$ and trying to get a contradiction. If $f$ exists, it is a continuous, bijective open/closed map. My thought was that somehow I could obtain a contradiction using that $f$ has to be an open map. We know that the open sets of $Y$ are all of the open sets of $X$ (so every subset of $X$ as it has the discrete topology) and all sets of the form $Y-C$ where $C$ is a compact subspace of $X$; that is, all sets of the form $Y-C$ where $C$ is a finite subset of $X$ since a subset of $X$ is compact iff it is finite. I am stuck. | You can look at cardinalities of the sets, in the first topological space you have the cardinality of the power set of the Real numbers, in the second you can use the fact that the real numbers have a countable base therefore there can be at most the cardinality of the power set of N of open sets. |
215278 | ```
public class XPBN extends Activity{
private Map _map;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
final Map data = (Map)getLastNonConfigurationInstance();
if (data == null) {
Toast.makeText(this, "New Map", Toast.LENGTH_SHORT).show();
_map = new Map(this);
} else {
Toast.makeText(this, "Old Map", Toast.LENGTH_SHORT).show();
_map = (Map)data;
}
setContentView(_map);
}
@Override
public Object onRetainNonConfigurationInstance() {
Toast.makeText(this, "Saving Configuration...", Toast.LENGTH_LONG).show();
return _map;
}
}
```
I am going to suppose that the title I gave this forum-thread states the problem I am experiencing pretty thoroughly. I have also edited the code to try to save a string object and then recover the string object through the getLastNonConfigurationInstance(), just to see to what extent I could get it to work for me, but it still seemed to return null. I have not tried calling it from onStart() or onRestart() or onResume(), but from what I have read, it is usually only called from onCreate(Bundle) anyways. This has got me really confused... :/
I figured it may be of some help to know a little about my Map class object, so here's (some of) the code from it:
```
public class Map extends SurfaceView implements SurfaceHolder.Callback{
private MapThread _mapThread;
private int _terrain[][];
private ArrayList<Player> playerList;
private Bitmap _blueback;
private Bitmap _bluefront;
private Bitmap _blueleft;
private Bitmap _blueright;
private Bitmap _greenback;
private Bitmap _greenfront;
private Bitmap _greenleft;
private Bitmap _greenright;
private Bitmap _redfront;
private Bitmap _redback;
private Bitmap _redleft;
private Bitmap _redright;
private Bitmap _robot1;
private Bitmap _forest;
private Bitmap _grass;
private Bitmap _mountain;
private Bitmap _tree;
@SuppressWarnings("unused")
private boolean _mapLoaded = false;
private int _viewX = 0;
private int _viewY = 0;
Map(Context context){
super(context);
getHolder().addCallback(this);
_mapThread = new MapThread(this);
setFocusable(true);
_terrain = new int[100][100];
playerList = new ArrayList<Player>();
addPlayer(0, 0, 0);
_blueback = BitmapFactory.decodeResource(context.getResources(), R.drawable.blueback);
_bluefront = BitmapFactory.decodeResource(context.getResources(), R.drawable.bluefront);
_blueleft = BitmapFactory.decodeResource(context.getResources(), R.drawable.blueleft);
_blueright = BitmapFactory.decodeResource(context.getResources(), R.drawable.blueright);
_greenback = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenback);
_greenfront = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenfront);
_greenleft = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenleft);
_greenright = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenright);
_redback = BitmapFactory.decodeResource(context.getResources(), R.drawable.redback);
_redfront = BitmapFactory.decodeResource(context.getResources(), R.drawable.redfront);
_redleft = BitmapFactory.decodeResource(context.getResources(), R.drawable.redleft);
_redright = BitmapFactory.decodeResource(context.getResources(), R.drawable.redright);
_robot1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.robot1);
_forest = BitmapFactory.decodeResource(context.getResources(), R.drawable.forest);
_grass = BitmapFactory.decodeResource(context.getResources(), R.drawable.grass);
_mountain = BitmapFactory.decodeResource(context.getResources(), R.drawable.mountain);
_tree = BitmapFactory.decodeResource(context.getResources(), R.drawable.tree);
TouchScreenHandler handler = new TouchScreenHandler(); // This includes 2 other nested-class threads
this.setOnTouchListener(handler);
}
```
Perhaps there lies something in the complexity of the Object returned by onRetainNonConfigurationInstance() that might be contributing to my problems?
Or lastly is there something (like a Activity or Application property) in my Manifest.xml file that is the problem?
If any further information is required, please let me know, as I will be checking back on this post frequently until I can get past this little bump in the road.
PS: I have this problem with both ADB and my device.
PSS: most importantly, a big THANKS to this community for the help and support, as it is greatly appreciated! :D | Have you confirmed that `onRetainNonConfigurationInstance()` is actually being called? I see you have a toast being displayed in it, but you don't actually say it is being shown. (And why a toast instead of just a `Log.i()`?)
As the documentation says, "this function is called purely as an optimization, and you must not rely on it being called." You can't rely on this actually happening. The *only* time it will happen in fact is when a configuration change happens while your activity is in the foreground, in which case the framework will in one feel swoop call `onRetainNonConfigurationInstance()` and destroy the current instance and immediately create a new instance with the retained object available to it. There should be pretty much nothing you can do that would prevent the object you return from appearing in the new instance... though I guess if you call `finish()` or such on the old one, that might do it. |
215634 | I'm developing an ERP using Spring MVC and JPA/Hibernate frameworks.
My problem is that the bean `construireBilanImpl` in the service layer can't be instantiated because the `opmanimpl` field can't be autowired and return `NullPointerException`
**com.ensi.erp.metier.CreerBilanImpl:**
```
@Transactional
@Component
public class ConstruireBilanImpl implements ConstruireBilan {
@Autowired(required=true)
private OperationManager opmanimpl ;
private float immobilisations_corporelles=sommeComptes(1266,1322);
public ConstruireBilanImpl(){};
public void setOpmanimpl(OperationManagerImpl x){opmanimpl=x;}
public float sommeComptes(int... doubles){
if (this.opmanimpl==null){System.out.println("BAAAAAAAAAAAAAADDDDDDDDDD");}
return opmanimpl.sommeComptes(doubles);
}
```
**com.ensi.dao.OperationMnagerImpl:**
```
@Component
public class OperationManagerImpl implements OperationManager {
@PersistenceContext(unitName="ERP")
private EntityManager em;
public OperationManagerImpl(){};
public void setEm(EntityManager emm){em=emm;}
public void creerOperation(opération op) {
if (em!=null){System.out.print(" manager de bean initialisé");}
em.persist(op);
System.out.println("dou5oul---------2");}
public opération rechercherOperation(int clé){
opération oper=em.find(opération.class,clé);
return oper;
}
public void supprimerOperation(int clé)
{
opération oper=em.find(opération.class,clé);
em.remove(oper);
}
public void modifierId(int clé,int nv){
opération oper=em.find(opération.class,clé);
oper.setIdop(nv);
em.flush();
}
public void modifierJournal(int clé,char j){
opération oper=em.find(opération.class,clé);
oper.setJournal(j);
em.flush();
}
public void modifierCompte(int clé,int nvc){
opération oper=em.find(opération.class,clé);
oper.setCompte(nvc);
em.flush();
}
public void modifierLibellé(int clé,String nvl ){
opération oper=em.find(opération.class,clé);
oper.setLibellé(nvl);
em.flush();
}
public void modifierDate(int clé,Date nvd){
opération oper=em.find(opération.class,clé);
oper.setDateop(nvd);
em.flush();
}
public void modifierDr(int clé,float nvdr){
opération oper=em.find(opération.class,clé);
oper.setDr(nvdr);
em.flush();
}
public void modifierCr(int clé,float nvcr){
opération oper=em.find(opération.class,clé);
oper.setCr(nvcr);
em.flush();
}
public List<opération> listeOpération() {
String ss="select op from opération op";
Query req= em.createQuery(ss);
return req.getResultList();
}
public void SupprimerOpération(int ref){
opération op=em.find(opération.class, ref);
em.remove(op);
}
public float sommeComptes(int... doubles) {
String liste= new String();
String x;
for (int d : doubles) {
x=Integer.toString(d);
x=x.concat(",");
liste=liste.concat(x);
}
liste=liste.substring(0, liste.length()-1);
String cc =" select sum(op.cr) from opération op ";
System.out.println(cc);
Query req= em.createQuery(cc);
Number somme=(Number)req.getSingleResult();
return somme.floatValue();
}
}
```
**Stacktrace:**
```
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Mon Jun 23 20:01:45 CEST 2014]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from URL [file:/C:/Users/housseminfo/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ERP_PCD/WEB-INF/classes/root-context.xml]
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5168781e: defining beans [datasource,persistenceUnitManager,entityManagerFactory,transactionManager,operationmanager,opser,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,operationController,operationManagerImpl,homeController,construireBilanImpl,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5168781e: defining beans [datasource,persistenceUnitManager,entityManagerFactory,transactionManager,operationmanager,opser,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,operationController,operationManagerImpl,homeController,construireBilanImpl,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'operationController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.metier.ConstruireBilan com.ensi.erp.controllers.OperationController.bil; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'construireBilanImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.dao.OperationManager com.ensi.erp.metier.ConstruireBilanImpl.opmanimpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ensi.erp.dao.OperationManager] is defined: expected single matching bean but found 2: [operationmanager, operationManagerImpl]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4961)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5455)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.metier.ConstruireBilan com.ensi.erp.controllers.OperationController.bil; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'construireBilanImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.dao.OperationManager com.ensi.erp.metier.ConstruireBilanImpl.opmanimpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ensi.erp.dao.OperationManager] is defined: expected single matching bean but found 2: [operationmanager, operationManagerImpl]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 23 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'construireBilanImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.dao.OperationManager com.ensi.erp.metier.ConstruireBilanImpl.opmanimpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ensi.erp.dao.OperationManager] is defined: expected single matching bean but found 2: [operationmanager, operationManagerImpl]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:873)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:815)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.dao.OperationManager com.ensi.erp.metier.ConstruireBilanImpl.opmanimpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ensi.erp.dao.OperationManager] is defined: expected single matching bean but found 2: [operationmanager, operationManagerImpl]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 36 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ensi.erp.dao.OperationManager] is defined: expected single matching bean but found 2: [operationmanager, operationManagerImpl]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:825)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 38 more
juin 23, 2014 8:01:47 PM org.apache.catalina.core.StandardContext listenerStart
Grave: Exception lors de l'envoi de l'évènement contexte initialisé (context initialized) à l'instance de classe d'écoute (listener) org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'operationController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.metier.ConstruireBilan com.ensi.erp.controllers.OperationController.bil; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'construireBilanImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.dao.OperationManager com.ensi.erp.metier.ConstruireBilanImpl.opmanimpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ensi.erp.dao.OperationManager] is defined: expected single matching bean but found 2: [operationmanager, operationManagerImpl]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4961)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5455)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.metier.ConstruireBilan com.ensi.erp.controllers.OperationController.bil; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'construireBilanImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.dao.OperationManager com.ensi.erp.metier.ConstruireBilanImpl.opmanimpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ensi.erp.dao.OperationManager] is defined: expected single matching bean but found 2: [operationmanager, operationManagerImpl]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 23 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'construireBilanImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.dao.OperationManager com.ensi.erp.metier.ConstruireBilanImpl.opmanimpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ensi.erp.dao.OperationManager] is defined: expected single matching bean but found 2: [operationmanager, operationManagerImpl]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:873)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:815)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ensi.erp.dao.OperationManager com.ensi.erp.metier.ConstruireBilanImpl.opmanimpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ensi.erp.dao.OperationManager] is defined: expected single matching bean but found 2: [operationmanager, operationManagerImpl]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 36 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ensi.erp.dao.OperationManager] is defined: expected single matching bean but found 2: [operationmanager, operationManagerImpl]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:825)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 38 more
``` | The interface `OperationManager` might have other implementation classes also. Hence Spring would not be able to figure out which implementation has to be created. If that is the case, then the below should help. Also the interface need not be marked as a `Component`.
`@Autowired(required=true)
@Qualifier("operationManagerImpl")
private OperationManager opmanimpl ;` |
215715 | I'm trying to get the balance to change in the account after a withdraw but it just stays at 10.00. I don't know how to properly apply a method in SavingsAccount that will change it. I tried but had no success.
```
import java.util.Date;
public class Account {
private int id;
private double balance;
private double annualInterestRate;
private Date dateCreated;
private double monthlyInterestRate;
public Account() {
id = 0;
balance = 0;
annualInterestRate = 0;
}
public Account(int iD, double balancE) {
id = iD;
balance = balancE;
}
public void setID(int iD) {
id = iD;
}
public int getID() {
return (id);
}
public void setBalance(double balancE) {
balance = balancE;
}
public double getBalance() {
return (balance);
}
public void setAnnualInterestRate(double AIR) {
annualInterestRate = AIR;
}
public double getAnnualInterestRate() {
return (annualInterestRate);
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public double getMonthlyInterestRate() {
return ((annualInterestRate / 100) / 12);
}
public double getMonthlyInterest() {
return (balance * monthlyInterestRate);
}
public void withdraw(double ammount) {
balance = balance - ammount;
}
public void deposit(double ammount) {
balance = balance + ammount;
}
}
public class SavingsAccount extends Account {
public SavingsAccount(int iD, double balancE) {
super(iD, balancE);
}
@Override
public void withdraw(double amount) {
if (amount > getBalance()) {
System.out.println("Current Balance: " + getBalance()
+ "\nThe withdrawal cannot be made due to insufficient funds.");
}
}
}
public class Test extends Account {
public static void main(String[] args) {
SavingsAccount a1 = new SavingsAccount(1122, 10.00);
a1.withdraw(5.00);
a1.deposit(00.00);
a1.setAnnualInterestRate(4.5);
Date dat = new Date();
System.out.println("Balance: " + a1.getBalance() +
"\nMonthly Interest: " + a1.getMonthlyInterest() +
"\nDate Created: " + dat);
}
}
``` | try:
```
public void deposit(double ammount) {
balance = balance + ammount;
setBalance(balance);
}
```
You should call setBalance at the end of withdraw and balance, passing in the new balance amount. |
215901 | I am making a program in c that reads line by line and does some operation on the elements of every line. I am calling my read\_row function like this.
```
while(filePointer!=NULL)
{
int result=readRow(filePointer,headerRow,lineRow);
printf("The value of row is |%d|\n",result);
}
```
Inside my read\_row function I am using get c to traverse through the line.
```
cc=getc(fp);
while((cc!='\n') && (cc!= EOF))
{
*line=cc;
line++;
if(cc==',')
{
counterr++;
}
cc=getc(fp);
}
if(cc==EOF)
{
fp=NULL;
}
```
I am trying traverse through all the lines. However, this loop is infinite as file pointer never goes to null. I have tried to set the file pointer to null if the cc equals to EOF. However, this did not help at all. Therefore, please explain how should I properly terminate that loop. I believe that '\n' is coming before the EOF.Therefore, the file pointer is not getting to null. I have to do it using the file Pointer, as I have already made a very big program based on that logic. Moreover, I could only find examples that used methods like fgets() to traverse. | When you pass a pointer to the function and then change it, you are actually changing the copy of that pointer, not the pointer itself. You need to pass a pointer to pointer for this to work, here's a small example:
```
int a = 2;
int b = 5;
//note the pointer to pointer:
void foo(int **ptr)
{
*ptr = &b;
}
int main() {
int * ptr = &a;
foo(&ptr);
printf("%d", *ptr); // prints 5
}
```
So in your case the `readRow` should accept `FILE**`, and you should call it as `readRow(&filePointer...` |
216163 | I am running Eclipse CDT in Redhat Enterprise, the default version of gcc compiler is 4.4.6. The support team added gcc 4.6.3 recently, I am wondering how can I set up Eclipse in such a way that I can choose to compile the application with either gcc 4.4.6 or 4.6.3.
Thanks. | If you really want both gcc 4.6 and 4.4 in your eclipse, you will have to adjust your build configurations (as far I know there is no "easy" way to do this by default).
>
> Project -> Properties -> C/C+++ Build -> Manage Configurations -> create new
>
>
>
Once this is created (& selected) you set it just like other configurations in tree (Debug / Release).
>
> new\_configuration > Discovery -> Compiler invocation command --> set path to gcc 4.6
>
>
>
I believe you have to do this per each project, Eclipse is sloppy in this area. |
216341 | I am getting this error when transtioning from a fragment to an activity as shown below:
```
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference at android.content.ComponentName.<init>(ComponentName.java:130) at android.content.Intent.<init>(Intent.java:6108)
```
Below is my code for going to the next activity, The error occurs on the first line of the code below.
```
Intent mainIntent = new Intent (getContext(), MainActivity.class);
mainIntent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity (mainIntent);
```
I don't see any solution so far online. | It seems that you're getting a wrong context that raises this `NullPointerException`
Try to replace the below line:
```
Intent mainIntent = new Intent (getContext(), MainActivity.class);
```
With: >> if you're within an activity
```
Intent mainIntent = new Intent (this, MainActivity.class);
```
with: >> if you're within a callback listener within the activity
```
Intent mainIntent = new Intent (MyActivityName.this, MainActivity.class);
```
With: >> if you're within a fragment
```
Intent mainIntent = new Intent (requireActivity(), MainActivity.class);
``` |
216673 | I have a subroutine that looks like this. It has two parameters.
```
Sub Advance(ByRef listR() As String, rCount)
...code
End Sub
```
When I try to call this:
```
Advance listR:=theList, theCount
```
It gives me a compile error:
>
> Expected: named parameter
>
>
>
Why is this? It works fine like...
```
Sub Advance(rCount)
...code
End Sub
```
And called via:
```
Advance theCount
```
Or also works with just the array parameter. | I believe that you can call your sub any of the following ways, but you can't name the first parameter and not name the second one:
```
Advance listR:=theList, rCount:=theCount
Advance rCount:=theCount, listR:=theList
Advance theList, rCount:=theCount
Advance theList, theCount
Call Advance(listR:=theList, rCount:=theCount)
Call Advance(rCount:=theCount, listR:=theList)
Call Advance(theList, rCount:=theCount)
Call Advance(theList, theCount)
``` |
216688 | I am trying to write my first Laravel program that uses Vue components. I am using Laravel 8.x and Vue 2.x and running on Windows 10. I'm imitating a [video](https://www.youtube.com/watch?v=hbq2CAHNRZM&t=2131s) that shows how to do it. Unfortunately, not everything he's doing works for me. Some people here were very helpful to me yesterday in solving the problem I was having then but now I've got a new one that I can't figure out.
He is doing a get request with Axios to read data previously put into a MySQL table in the Vue component. Axios returns a response that includes the data and then assigns it to an initialized empty array in the data() area of the component. He defines the empty array as follows:
```
todos: '',
```
The method that executes the Axios get looks like this:
```
getToDos() {
debugger;
axios.get('/todo')
.then(function (res) {
if (res.data.length == 0) console.log("Table is empty");
else {
this.todos = res.data
}
})
.catch(function (error) {
console.log(error);
})
},
```
As you can see, he is simply assigning all of res.data, which appears to be an array of objects, to the todos array in the data() area. When he executes the code, it works fine but he is using Laravel 7.x while I am using 8.x. When I try to execute this code, I get an error in the Chrome Debugger:
```
TypeError: this is undefined
```
which highlights the assignment statement (this.todos = res.data). I'm still new to Javascript and I'm not fluent with the idioms yet but it looks to me as if todos is being defined as an empty string and getting assigned an array of objects so I really expected that to fail when he executed it but it didn't. Maybe this has something to do with him using Laravel 7.x??
Anyway, I did some researching and I tried a bunch of variations in this code but I always get the same error message when I'm assigning something to the todos variable, even if I define it as
```
todos: []
```
or
```
todos: new Array()
```
I've tried writing a for loop and pushing each Object from res.data into todos. Nothing works. Can someone kindly enlighten me on why his code works and why it doesn't work for me? I simply want to put res.data where I can access it in my template so that I can display the relevant data.
Edit: Here is the entire component.
```
<template>
<div class="container">
<form @submit.prevent="addTask">
<div class="input-group mb-3 w-100">
<input type="text" v-model="form.todo" class="form-control" placeholder="Enter new task" aria-label="Enter new task" aria-describedby="button-addon2">
<div class="input-group-append">
<button class="btn btn-success" type="submit" id="button-addon2">Add new task</button>
</div>
</div>
</form>
<div class="w-25">
<h1 class="text-white">...</h1>
<div v-for="todo in todos" :key="todo.id" class="w-100 text-white">
{{ todo.title }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
todos: '',
form: new Form({
title: '',
})
}
},
methods: {
getToDos() {
debugger;
axios.get('/todo')
.then(function (res) {
if (res.data.length == 0) console.log("Table is empty");
else {
this.todos = res.data
// var id = 0;
// var title = '';
// var completed = false;
// for (var ix=0; ix<res.data.length; ix++) {
// id = res.data[ix].id;
// title = res.data[ix].title;
// completed = res.data[ix].completed;
// var oneToDo = new Object(res.data[ix]);
// this.todos.push(oneToDo);
// }
}
})
.catch(function (error) {
console.log(error);
})
},
addTask() {
let data = new FormData();
data.append('todo', this.form.todo);
axios.post('/todo', data)
.then(function (response) {
console.log(response);
this.form.reset;
this.getToDos();
})
.catch(function (error) {
console.log(error);
})
}
},
mounted() {
console.log('ToDoComponent mounted.');
this.getToDos();
}
}
</script>
<style lang="scss" scoped>
.container {
padding-top: 5em;
}
</style>
``` | The closure of `this` in function(){ //code } is the function itself. If you want to access the `this` of the object which you defined the function you will need to use arrow function as follow.
```
var obj = {
getToDos() {
// this here refer to obj
axios.get('/todo')
.then( res => {
this.todos = res.data
})
}
}
```
More information about closure in js:
<https://www.w3schools.com/js/js_function_closures.asp>
<https://medium.com/@vmarchesin/javascript-arrow-functions-and-closures-4e53aa30b774> |
216934 | I have a program that uses boost asio to connect to 3 TCP sockets asynchronously using a `deadline_timer` as a connect timeout. On windows everything works as expected. The connection times out after 5 seconds. However, on Unix(Ubuntu on WSL, Linux Mint VM, macOS) the connectDeadline never fires. The async\_connect operation just runs on forever. Why does this not work and how can I make this work on Unix as well?
Code:
Note: connect is called from the main thread (which is also a GUI thread).
```
#include "NetManager.h"
NetManager::NetManager(NetManagerListener& listener) : listener(listener),
connectDeadline(io),
socket1(io),
socket2(io),
socket3(io),
asioThread(&NetManager::handleAsioOperations, this){
}
NetManager::~NetManager() {
running = false;
io.stop();
asioThread.join();
}
void NetManager::connect(){
connectCounter = 0;
hasHandledConnectError = false;
socket1.async_connect(
tcp::endpoint(boost::asio::ip::address::from_string(IP_STRING), PORT_1),
boost::bind(&NetManager::handleConnect, this, _1));
socket2.async_connect(
tcp::endpoint(boost::asio::ip::address::from_string(IP_STRING), PORT_2),
boost::bind(&NetManager::handleConnect, this, _1));
socket3.async_connect(
tcp::endpoint(boost::asio::ip::address::from_string(IP_STRING), PORT_3),
boost::bind(&NetManager::handleConnect, this, _1));
connectDeadline.expires_from_now(boost::posix_time::seconds(CONNECT_TIMEOUT));
connectDeadline.async_wait(boost::bind(&NetManager::handleConnectTimeout, this, _1));
}
void NetManager::disconnect(){
//NOTE: Close also cancels incomplete async operations
socket1.close();
socket2.close();
socket3.close();
}
////////////////////////////////////////////////////////////////////////
/// ASIO Handlers
////////////////////////////////////////////////////////////////////////
void NetManager::handleAsioOperations(){
while(running){
io.run(); // Run any async operations
}
}
void NetManager::handleConnect(const boost::system::error_code &ec){
// When connections are canceled the handler is called with operation_aborted. No need to respond to that.
if(ec && ec != boost::asio::error::operation_aborted && !hasHandledConnectError){
hasHandledConnectError = true; // Likely to be 3 repeated errors. Make sure to only handle the first one
cerr << "Connect Failed: " << ec.message() << endl;
connectDeadline.cancel(); // Don't fire the timeout
disconnect(); // Disconnect any already connected sockets
connectedToRobot = false;
listener.onConnect(false);
}else if (!ec){
connectCounter++;
}
if(connectCounter == 3){
cout << "Successful connect" << endl;
connectDeadline.cancel(); // Don't fire the timeout
connectedToRobot = true;
listener.onConnect(true);
}
}
void NetManager::handleConnectTimeout(const boost::system::error_code &ec){
if(ec != boost::asio::error::operation_aborted){
cerr << "Connect timed out." << endl;
disconnect(); // Disconnect any already connected sockets
connectedToRobot = false;
listener.onConnect(false);
}
}
```
EDIT:
Confusingly, this works fine on Unix OSes:
```
#include <boost/asio.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <iostream>
#include <thread>
using namespace boost::asio;
using namespace boost::asio::ip;
int main(){
io_service io;
deadline_timer timer1(io);
tcp::socket sock(io);
timer1.expires_from_now(boost::posix_time::seconds(3));
sock.async_connect(tcp::endpoint(boost::asio::ip::address::from_string("10.50.30.1"), 8090), [](const boost::system::error_code &ec){
std::cout << "SocketError: " << ec.message() << std::endl;
});
timer1.async_wait([&](const boost::system::error_code &ec){
std::cout << "First timer" << std::endl;
sock.close();
});
std::thread worker([&](){
while(true){
io.run();
}
});
worker.detach();
while(true){} // Simulate the unavailable main (GUI) thread
}
```
Output:
```
First timer
SocketError: Operation canceled
``` | To use the `var` keyword with **JDK 10** in NetBeans:
* Ensure that you are [running the latest version of Apache NetBeans](https://netbeans.apache.org/download/index.html).
* In NetBeans add **JDK 10** as a Java platform (**Tools > Java Platforms > Add Plaform...**). It is not necessary to make **JDK 10** the default.
* Create a simple Java application (**File > New Project... > Java > Java Application**) and declare a **var** variable (e.g. `var v = 7;`) within the `main()` method.
* Select the project node in the **Projects** pane, right click and select **Properties**.
* In the **Project Properties** window ensure that **Libraries > Java Platform** is set to **JDK 10**
* In the **Project Properties** window ensure that **Sources > Source/Binary Format** is set to **JDK 10**
* In the **Files** pane open the file **project.properties** (under the **nbproject** folder) and navigate to the lines for `javac.source` and `javac.target`. Verify that they both contain the value `10`.
* Press **Shift-F11** to clean and build the project.
If there is still a *"cannot find symbol"* error for the `var` declaration then there is something fundamentally wrong with the NetBeans installation, so update the OP with:
* The content of the **Output** window after doing the **Clean and Build**.
* The source being compiled.
* The settings for `javac.source` and `javac.target` in **project.properties**.
* The version information shown in the **Help > About** window. |
217153 | I am currently trying to copy a file from one folder to another specified folder using Excel VBA Macro,my data is on Sheet 1 on Excel, I've set my file name to be on cell B5, the source folder is on B6, and the destination folder is on cell B7. This is my code below :
```
'In this Example I am Copying the File From one loaction to another location
'as per the details specified in the Worksheet.
Sub sbCopyingAFileReadFromSheet()
'Declaration
Dim FSO
Dim sFile As String
Dim sSFolder As String
Dim sDFolder As String
sFile = Sheets("Sheet1").Range("B5")
sSFolder = Sheets("Sheet1").Range("B6")
sDFolder = Sheets("Sheet1").Range("B7")
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FileExists(sSFolder & sFile) Then
MsgBox "Specified File Not Found in Source Folder", vbInformation, "Not Found"
ElseIf Not FSO.FileExists(sDFolder & sFile) Then
FSO.CopyFile (sSFolder & sFile), sDFolder, True
MsgBox "Specified File Copied to Destination Folder Successfully", vbInformation, "Done!"
Else
MsgBox "Specified File Already Exists In The Destination Folder", vbExclamation, "File Already Exists"
End If
End Sub
```
but a "Specified File Not Found in Source Folder" error message keeps on popping up even though the file is in the source folder. Please assist | when using `sSFolder & sFile` make sure you have a "\" between the 2 variables, like this
```
sSFolder & "\" & sFile
``` |
217772 | Has anyone been able to successfully integrate `Realm` with `SwiftUI`, especially deleting records/rows from a `SwiftUI List`? I have tried a few different methods but no matter what I do I get the same error. After reading some related threads I found out that other people have the same issue.
The following code successfully presents all of the items from `Realm` in a `SwiftUI List`, I can create new ones and they show up in the List as expected, my issues is when I try to delete records from the List by either manually pressing a button or by left-swiping to delete the selected row, I get an Index is out of bounds error.
Any idea what could be causing the error?
Here is my code:
Realm Model
-----------
```
class Dog: Object {
@objc dynamic var name = ""
@objc dynamic var age = 0
@objc dynamic var createdAt = NSDate()
@objc dynamic var userID = UUID().uuidString
override static func primaryKey() -> String? {
return "userID"
}
}
```
SwiftUI Code
------------
```
class BindableResults<Element>: ObservableObject where Element: RealmSwift.RealmCollectionValue {
var results: Results<Element>
private var token: NotificationToken!
init(results: Results<Element>) {
self.results = results
lateInit()
}
func lateInit() {
token = results.observe { [weak self] _ in
self?.objectWillChange.send()
}
}
deinit {
token.invalidate()
}
}
struct DogRow: View {
var dog = Dog()
var body: some View {
HStack {
Text(dog.name)
Text("\(dog.age)")
}
}
}
struct ContentView : View {
@ObservedObject var dogs = BindableResults(results: try! Realm().objects(Dog.self))
var body: some View {
VStack{
List{
ForEach(dogs.results, id: \.name) { dog in
DogRow(dog: dog)
}.onDelete(perform: deleteRow )
}
Button(action: {
try! realm.write {
realm.delete(self.dogs.results[0])
}
}){
Text("Delete User")
}
}
}
private func deleteRow(with indexSet: IndexSet){
indexSet.forEach ({ index in
try! realm.write {
realm.delete(self.dogs.results[index])
}
})
}
}
```
Error
-----
>
> Terminating app due to uncaught exception ‘RLMException’, reason: ‘Index 23 is out of bounds (must be less than 23).’
>
>
>
Of course, the 23 changes depending on how many items are in the Realm database, in this case, I had 24 records when I swiped and tapped the delete button.
FYI - The error points to the AppDelegate file with a `Thread 1: signal SIGABRT`. | Here is an example of how i do this. This is without realm operations but i hope u get the idea where you can put the realm stuff. (I also almost never use the realm objects directly but instead convert them to structs or classes.)
```
import Foundation
import Realm
import Combine
import SwiftUI
struct dogs: Hashable {
let name: String
}
class RealmObserverModel: ObservableObject {
var didChange = PassthroughSubject<Void, Never>()
@Published var dogsList: [dogs] = [dogs(name: "Dog 1"), dogs(name: "Dog 2")]
// get your realm objects here and set it to
// the @Publsished var
func getDogs() {
let count = dogsList.count + 1
dogsList.append(dogs(name: "Dog \(count)"))
}
// get your realm objects here and set it to
// the @Publsished var
func deletetDogs() {
_ = dogsList.popLast()
}
}
/// Master View
struct DogView: View {
@EnvironmentObject var observer: RealmObserverModel
var body: some View {
VStack{
DogsListView(dogsList: $observer.dogsList)
HStack{
Button(action: {
self.observer.getDogs()
}) {
Text("Get more dogs")
}
Button(action: {
self.observer.deletetDogs()
}) {
Text("Delete dogs")
}
}
}
}
}
// List Subview wiht Binding
struct DogsListView: View {
@Binding var dogsList: [dogs]
var body: some View {
VStack{
List{
ForEach(dogsList, id:\.self) { dog in
Text("\(dog.name)")
}
}
}
}
}
struct DogView_Previews: PreviewProvider {
static var previews: some View {
DogView().environmentObject(RealmObserverModel())
}
}
``` |
217860 | I am trying to convert this code into a while loop or a do while loop. I don't quite grasp the best understanding of the subject. Can anyone help?
This is the project I am trying to create a loop for. I'm not sure what the loop would be used for:
The Barking Lot is a dog boarding facility. It provides boarding for any number of days and
additional services such as grooming and walking. The Barking Lot currently has three
employees, a list of 40 dog clients, and room to board eight dogs at any one time. One required
program must be able to estimate profits for a day. The facility can board eight dogs at a time; it
charges $25 a day for dogs that weigh more than 50 pounds and $20 a day for smaller dogs. The
facility’s expenses include $2 per day per dog for food (no matter the size of the dog), and $30
per day for utilities. Develop the logic for a program, and implement the program that allows a
user to enter the number of large dogs boarded; assume that the rest are small dogs and that the
facility is full. Output is the total revenue collected for the day, total expenses, and the
difference. Allow the user to request an unlimited number of profit estimates at a time
This is my code:
```
import java.util.Scanner;
public class Bark {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int x = 20;
int y = 25;
int Small = 0;
int Large = 0;
System.out.println("Enter number of small dogs: ");
Small = Scanner.nextInt();
System.out.println("Enter number of large dogs: ");
Large = Scanner.nextInt();
int Revenue = ((Small * x) + (Large * y));
int Food = ((Small + Large) * (2));
int Facility = 30;
int Expenses = (Food + Facility);
int Difference = (Revenue - Expenses);
if ((Small + Large) <= 8) {
System.out.println("Revenue is " + ((Small * x) + (Large * y)));
System.out.println("Expenses = " + (Food + Facility));
System.out.println("Difference = " + (Revenue - Expenses));
} else
System.out.println("The number of dogs has exceeded the facility limit.");
}
}
``` | Don't know exactly what part of your code you would like to loop (I mean the result you want to achieve). So I will leave a coding style recommendation, that might help you in the near future! ;-)
```
// Comment your code. You are going to need it and avoid some people
// swearing at your code. :-)
// Always use first letter lowercase and other words in upper when
// programming in Java (variables, methods). Upper for classes.
int variableName = 0;
public class Bark { ... }
int final MY_CONSTANT = 0;
public void myMethod() { ... }
// Not good to use variables like "x". You will easily loose track of
// what they mean.
int valueOfSomething = 20;
```
If what you want is reprocessing (like run the code again after it is done), here's what you could do.
```
public class Bark {
public static void main(String[] args) {
// Declare variables
Scanner scanner = new Scanner(System.in);
int valueSmall = 20;
int valueLarge = 25;
int small = 0;
int large = 0;
int quit = 0;
while (quit == 0) {
// Ask for user input
System.out.println("Enter number of small dogs: ");
small = scanner.nextInt();
System.out.println("Enter number of large dogs: ");
large = scanner.nextInt();
// Perform accountability
int revenue = ((small * valueSmall) + (large * valueLarge));
int food = ((small + large) * (2));
int facility = 30;
int expenses = (food + facility);
int difference = (revenue - expenses);
if ((small + large) <= 8) {
System.out.println("Revenue is " + revenue);
System.out.println("Expenses = " + expenses);
System.out.println("Difference = " + difference);
} else {
System.out.println("The number of dogs has exceeded the facility limit.");
}
// Ask if user wants to quit (No input validation!)
System.out.println("Quit? Enter 0 for NO or 1 for YES:");
quit = scanner.nextInt();
}
System.out.println("Goodbye");
}
}
```
Another way to accumulate the number of Dogs until it reaches the limit.
```
public class Bark {
public static void main(String[] args) {
// Declare variables
Scanner scanner = new Scanner(System.in);
int valueSmall = 20;
int valueLarge = 25;
int small = 0;
int large = 0;
while (small + large <= 8) {
// Ask for user input, notice I am accumulating using +=
System.out.println("Enter number of small dogs: ");
small += scanner.nextInt();
System.out.println("Enter number of large dogs: ");
large += scanner.nextInt();
// Perform accountability
int revenue = ((small * valueSmall) + (large * valueLarge));
int food = ((small + large) * (2));
int facility = 30;
int expenses = (food + facility);
int difference = (revenue - expenses);
// Print the report
System.out.println("Revenue is " + revenue);
System.out.println("Expenses = " + expenses);
System.out.println("Difference = " + difference);
}
// If number exceeds the limit, your loop breaks and you print the message.
System.out.println("The number of dogs has exceeded the facility limit.");
System.out.println("Goodbye");
}
}
``` |
218191 | I am using react dropzone uploader as per the doc to upload file to my server. I am adding some extra body params to formdata object as mentioned in the RDU component document here <https://react-dropzone-uploader.js.org/docs/api#getuploadparams>
but it it always sending the request with standard request body of RDU.
my `getUploadParams` method looks like this
```
getUploadParams = ({ file, meta }) => {
const data = new FormData()
data.append('customFile', file)
data.append('type', 'normal')
return { data, url: uploadUrl }
}
```
Any help how to send our own request formdata object? | Correct way of using this
```
getUploadParams = ({ file, meta }) => {
const body= new FormData()
body.append('customFile', file)
body.append('type', 'normal')
return { url: uploadUrl, body }
}
``` |
219330 | In my Rails app I've created a set of checkboxes as follows:
```
<div class="form_row">
<label for="features[]">Features:</label>
<% ['scenarios', 'news', 'role_profiles', 'private_messages', 'chatrooms', 'forums', 'polls'].each do |feature| %>
<br><%= check_box_tag 'features[]', feature, (@features || {}).include?(feature) %>
<%= feature.humanize %>
<% end %>
</div>
```
I'd like to know how to create a button that would "Select All". | Using jQuery;
```
<script type="text/javascript">
function selectAll(){
$("input:checkbox").each(function(){
$(this).attr('checked', true);
});
return false;
}
</script>
```
HTML button:
```
<a href="#" onclick="selectAll()">Select All</a>
``` |
219754 | I'm using the `hyperref` package and am unable to load `tocloft`. I've tried everything including a *voodoo ritual involving a rubber chicken* to get the two to shake hands.
Is there a work around to get dots in the table of contents, list of figures/tables? Also, in my list of figures/tables I have the depth set to section, so I see an overlap-spacing problem with the numbering and the caption title. Is there a simple way to correct this spacing?
```
\documentclass[psamsfonts,10pt,reqno,letterpaper]{amsbook}
\usepackage{chngcntr}
\counterwithin{section}{chapter}
\counterwithin{figure}{chapter}
\counterwithin{table}{chapter}
\usepackage[Lenny]{fncychap}
\ChRuleWidth{1.618pt}
\ChTitleVar{\raggedright \huge }
\ChNameVar{\raggedleft \Huge }
\usepackage[bookmarksdepth=subsection,plainpages=false]{hyperref}
\usepackage[english]{babel}
\usepackage{blindtext}
\begin{document}
\listoftables
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\begin{table}
\begin{tabular}{c}
stuff
\end{tabular}
\caption{stuff}
\end{table}
\end{document}
``` | With the following setting chapters have their dots and **hyperref** doesn't complain.
```
\documentclass[a4paper]{book}
\usepackage{tocloft}
\renewcommand{\cftdot}{\normalfont.} % don't inherit the \bfseries attribute
\renewcommand{\cftchapdotsep}{4.5} % same spacing as for sections
\usepackage{hyperref}
``` |
220018 | If $\gamma:[a,b] \rightarrow \mathbb{C}$ is a piecewise smooth differentiable curve. Let $\overline{\gamma}$ denote the image of $\gamma$ under $z \mapsto \overline{z}$. Show if $f$ is continuous on $\gamma$, then $z \mapsto \overline{f(\overline{z})}$ is continuous and
$$\overline{\int\_\gamma f(z) dz}=\int\_\overline{\gamma} \overline{f(\overline{z})} dz$$
So from my understanding, $z \mapsto \overline{z}$ is the map sending $x+iy \mapsto x-iy$. How do I conjugate the whole function and the variable $z$? To show the map is continuous, is it just a limit argument? Any hints greatly appreciated! Could I let $f(x,y)=u(x,y)+iv(x,y)$ where $u,v$ satisfy Cauchy Riemann? | Use Taylor's formula with integral remainder. If you take $x\_{0}\in\Omega$ you
can find a ball $\overline{B(x\_{0},r)}\subseteq\Omega$. The ball is actually a
cube. Then for every $x,y\in B(x\_{0},r)$,
$$
f\_{n}(x)=f\_{n}(y)+\sum\_{|\alpha|=1}^{k}\frac{1}{\alpha!}\partial^{\alpha}%
f\_{n}(y)(x-y)^{\alpha}+\sum\_{|\alpha|=k+1}c\_{\alpha}(x-y)^{\alpha}\int\_{0}%
^{1}(1-t)^{k}\partial^{\alpha}f\_{n}(tx+(1-t)y)\,dt.
$$
By uniform convergence in the compact set $\overline{B(x\_{0},r)}$,
$$
f(x)=f(y)+\sum\_{|\alpha|=1}^{k}\frac{1}{\alpha!}v^{\alpha}(y)(x-y)^{\alpha
}+\sum\_{|\alpha|=k+1}c\_{\alpha}(x-y)^{\alpha}\int\_{0}^{1}(1-t)^{k}v^{\alpha
}(tx+(1-t)y)\,dt.
$$
Taking $x=y+te\_{i}$, dividing by $t$ and letting $t\rightarrow0$ gives
$\partial\_{\iota}f(y)=v^{e\_{i}}(y)$. You can now use an induction argument, or
apply the same reasoning with $f$ replaced by $\partial^{\beta}f$ to conclude
that $\partial^{\alpha}f(y)=v^{\alpha}(y)$ for every $y\in B(x\_{0},r)$ and every multi-index $\alpha$. |
220359 | How would I handle a belong\_to with the following include. Instead of displaying the product\_colour\_id id like to show the associated colour (**Update:Solved this part below**). The product\_colour\_id is in the Product table and matches the corresponding Product\_colour id.
***Its the case of two or more has\_many associations that i cant work out. Can it be done?***
**app/controller/home\_controller.rb**
```
class HomeController < ApplicationController
def index
products = Product.last(5)
product_ids = products.map(&:id)
@product_colour_ids = products.map(&:product_colour_id)
@allproduct_colours = ProductColour.all
@product_colour_map = ProductColour.find(@product_colour_ids)
@product_images = Product.includes(:product_images)
.where(product_images: {product_id: product_ids, :default_image => true})
end
end
```
**/app/views/home/index.html.erb**
```
<% @product_images.each do |pd| %>
<%= content_tag :div, :class => "col-md-3 col-sm-6 hero-feature" do %>
<% pd.product_images.each do |i| %>
<div class="thumbnail">
<%= image_tag (i.product_image(:medium)) %>
<% end %> </div>
<div class="caption">
<h3><%= pd.product_name %></h3>
<p><%= pd.product_description %></p>
<p> <%= pd.product_colour_id %></p>
</div>
<% end %>
<% end %>
</div>
```
I'm having difficulty finding examples of multiple has\_many includes. I assume there is a very straight forward pattern to it but cant work it out from [apidock](http://apidock.com/rails/ActiveRecord/QueryMethods/includes) or [api.rubyonrails.org](http://api.rubyonrails.org/). The problem i'm having is adding the Supply\_company which is a has\_many :through relationship to the one I already have with the product\_image include.
Thankyou in advance for your advise
**Update** I have worked out how to display the belongs\_to... feeling a little dumb on that as it was very easy just needed some time to think
```
<% pd.product_images.each do |pd| %>
<p> <%= pd.product_colour.product_colour %></p>
<% end %>
```
**/app/models/product.rb**
```
class Product < ActiveRecord::Base
belongs_to :product_type
belongs_to :product_category
belongs_to :product_colour
belongs_to :product_size
has_many :product_supply_companies, :foreign_key => 'product_id'
accepts_nested_attributes_for :product_supply_companies, :allow_destroy => true
has_many :supply_companies, :through => :product_supply_companies
accepts_nested_attributes_for :supply_companies
has_many :product_images, dependent: :destroy, :foreign_key => 'product_id'
accepts_nested_attributes_for :product_images, :allow_destroy => true
end
```
**app/models/product\_supply\_company.rb**
```
class ProductSupplyCompany < ActiveRecord::Base
belongs_to :product
belongs_to :supply_company
# accepts_nested_attributes_for :supply_company
# accepts_nested_attributes_for :product
end
```
**app/models/supply\_company.rb**
```
class SupplyCompany < ActiveRecord::Base
has_many :products, :through => :product_supply_companies
has_many :product_supply_companies, :foreign_key => 'supply_company_id'
accepts_nested_attributes_for :products
accepts_nested_attributes_for :product_supply_companies, :allow_destroy => true
end
```
**app/models/product\_colour.rb**
```
class ProductColour < ActiveRecord::Base
has_many :products
end
```
**Database Schema**
```
create_table "product_categories", force: true do |t|
t.string "product_category"
t.string "product_category_description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "product_colours", force: true do |t|
t.string "product_colour"
t.string "product_colour_description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "product_images", force: true do |t|
t.integer "product_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "product_image_file_name"
t.string "product_image_content_type"
t.integer "product_image_file_size"
t.datetime "product_image_updated_at"
t.boolean "default_image"
end
create_table "product_sizes", force: true do |t|
t.string "product_size"
t.string "product_size_description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "product_supply_companies", force: true do |t|
t.integer "product_id"
t.integer "supply_company_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "product_types", force: true do |t|
t.string "product_type"
t.string "product_type_description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "products", force: true do |t|
t.string "product_name"
t.text "product_description"
t.integer "product_type_id"
t.integer "product_category_id"
t.string "product_colour_id"
t.integer "product_size_id"
t.datetime "created_at"
t.datetime "updated_at"
end
``` | ```
@products = Product.includes(:product_images, :colour, :supply_companies)
.where(product_images: {product_id: product_ids, :default_image => true})
.select('products.*, product_colours.product_colour')
```
this the query with all associations.
index.html.erb
```
<% @products.each do |pd| %>
<%= content_tag :div, :class => "col-md-3 col-sm-6 hero-feature" do %>
<% pd.product_images.each do |i| %>
<div class="thumbnail">
<%= image_tag (i.product_image(:medium)) %>
</div>
<% end %>
<div class="caption">
<h3><%= pd.product_name %></h3>
<p><%= pd.product_description %></p>
<p><%= pd.product_colour %></p>
</div>
<% end %>
<% end %>
```
Product.rb
```
belongs_to :colour, class: 'ProductColor', foreign_key: 'product_colour_id'
``` |
220435 | I just started coding in React using [create-react-app](https://github.com/facebookincubator/create-react-app). In the documentation it's said
>
> The page will reload if you make edits.
>
>
>
I don't know which module is responsible for auto reload (webpack or react-hot-reloader?) but it's not working. I edited file using different editors (Sublime, VIM, ..) but it seems problem is for something else. Any advice how to debug it? | I hope to save someone else the same pain I experienced.
I'm using Windows 10 and Ubuntu 20.04 WSL, with nvm to manage node/npm.
I had to:
* Use Node v16.14.2 in nvm (which also uses npm 8.5.0)
* Change react-scripts from `"react-scripts": "5.0.0"` to `"react-scripts": "4.0.3"` in my package.json file
* Change my package.json start script to
```
"start": "CHOKIDAR_USEPOLLING=true react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
```
* I then ran `npm install` to update react scripts and restarted the bash terminal
* I also followed Ronald Araújo's advice in his answer for good measure.
5 hours later, it's finally working!
Good luck everyone! |
220448 | I just changed my Laptop, downloaded Android Studio Arctic Fox and cloned the project on which I was already working on in my previous machine. I see that few of the tags are not imported and are in red in the xml layout. When I hover over it, it says "Cannot resolve class TextView". Similar issue with ImageView. What is wrong?
[![enter image description here](https://i.stack.imgur.com/1R9DJ.png)](https://i.stack.imgur.com/1R9DJ.png) | ***after clean the project sync the build gradle or cut and paste a one dependency and sync the gradle*** |
220518 | I'm trying to group two columns in my MySQL database and show counts for them respectively (as separate columns). Is there a way of doing this or do I have to join two sub-queries?
I'm aware of `WITH ROLLUP` but can't produce the right query.
This gives the right result:
```
SELECT A.mid, B.pid, A.count AS mid_count, B.count as pid_count
FROM (Select mid , COUNT(*) AS count FROM test GROUP BY mid) AS A,
(Select mid, pid, COUNT(*) AS count FROM test GROUP BY mid, pid) AS B
WHERE A.mid = B.mid ORDER BY mid_count DESC
```
This is the expected output
```
+-----+-----+-----------+-----------+
| mid | pid | mid_count | pid_count |
+-----+-----+-----------+-----------+
| 3 | 12 | 5 | 2 |
| 3 | 14 | 5 | 1 |
| 3 | 15 | 5 | 2 |
| 4 | 12 | 2 | 1 |
| 4 | 17 | 2 | 1 |
+-----+-----+-----------+-----------+
```
I've created a fiddle at: <http://sqlfiddle.com/#!9/e3ebe1/12> | I removed one of the subqueries from yours but fundamentally as mysql doesn't support count over partition etc, it will need more than one pass through the table:
```
Select test.mid, test.pid, A.cnt as midCount, count(*) as pidCount
from test join
(Select mid, count(*) as cnt from test group by mid) A
on test.mid = A.mid
Group by mid, pid
``` |
220655 | I'm using IO.DirectoryInfo to sanitize a path. However, it seems to exhibit strange behaviour when a path ends with "\CON". For example:
```
IO.DirectoryInfo("C:\FOOBAR\").FullName
```
Will return:
```
C:\FOOBAR\
```
However, in these examples:
```
IO.DirectoryInfo("C:\CON").FullName
IO.DirectoryInfo("C:\SUB\CON").FullName
IO.DirectoryInfo("..\CON").FullName
IO.DirectoryInfo("CON").FullName
```
The return value is always:
```
\\.\CON
```
So, when the user wants to create a directory called "CON", the whole program blows up.
Of all the weird things I've seen the .Net Framework do in the past, this takes the cake. Can anyone explain what's going on here? | CON is a reserved file name, with a long history as an MS-DOS device name. As is stated in documentation on naming files, paths and namespaces:
>
> **Do not use the following reserved names for the name of a file:**
> CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names followed immediately by an extension; for example, NUL.txt is not recommended.
>
>
>
Refer to <https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx> |
220664 | After reading up on how to best [handle users in multiple timezones](https://stackoverflow.com/questions/2532729/daylight-saving-time-and-timezone-best-practices) properly, I've learned that the way to go is to store all dates in an normalized, application-wide timezone - `UTC` and then apply the diff between the normalized timezone and the individual users timezone when outputting. Today I came to think if this would be appropriate to apply this approach to handling currency in software:
All stored currency are converted to a application-wide currency, lets say `EUR` (€), and when outputting, the currency is converted back into the users own currency, with an updated exchange rate of the day?
What's common sense here? How is this generally solved and what should I be aware of before choosing a way to handle this? | One standard approach is to store both an amount and a currency whenever monetary values are held and manipulated.
See the [Money Pattern](http://martinfowler.com/eaaCatalog/money.html) in Martin Fowler's Patterns of Enterprise Application Architecture.
Fowler describes defining a simple datatype to hold the two primitive components, with overloaded arithmetical operators for performing monetary operations:
>
> "The basic idea is to have a Money class with fields for the numeric
> amount and the currency. You can store the amount as either an
> integral type or a fixed decimal type. The decimal type is easier for
> some manipulations, the integral for others. You should absolutely
> avoid any kind of floating point type, as that will introduce the kind
> of rounding problems that Money is intended to avoid. Most of the time
> people want monetary values rounded to the smallest complete unit,
> such as cents in the dollar. However, there are times when fractional
> units are needed. It’s important to make it clear what kind of money
> you’re working with, especially in an application that uses both
> kinds. It makes sense to have different types for the two cases as
> they behave quite differently under arithmetic.
>
>
> Money needs arithmetic operations so that you can use money objects as
> easily as you use numbers. But arithmetic operations for money have
> some important differences to money operations in numbers. Most
> obviously, any addition or subtraction needs to be currency aware so
> you can react if you try to add together monies of different
> currencies. The simplest, and most common, response is to treat the
> adding together of disparate currencies as an error. In some more
> sophisticated situations you can use Ward Cunningham’s idea of a money
> bag. This is an object that contains monies of multiple currencies
> together in one object. This object can then participate in
> calculations just like any money object. It can also be valued into a
> currency."
>
>
> |
220917 | Launching myself into Swift and SwiftUI, I find the process of migrating from UIKit quite hard.
Presently stomped by UserDefaults, even after trying to make sense of the many tutorials I found on the web.
Please tell me what I'm doing wrong here :
VERY simple code to :
1. register a bool value to a UserDefault,
2. display that bool in a text !
Doesn't get any simpler than that.
But I can't get it to work, as the call to UserDefaults throws this error message :
>
> Instance method 'appendInterpolation' requires that 'Bool' conform to '\_FormatSpecifiable'
>
>
>
My "app" is the default single view app with the 2 following changes :
1- In AppDelegate, I register my bool :
```
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UserDefaults.standard.register(defaults: [
"MyBool 1": true
])
return true
}
```
2- in ContentView, I try to display it (inside struct ContentView: View) :
```
let defaults = UserDefaults.standard
var body: some View {
Text("The BOOL 1 value is : Bool 1 = \(defaults.bool(forKey: "MyBool 1"))")
}
```
Any ideas ?
Thanks | Your issue is that the `Text(...)` initializer takes a `LocalizedStringKey` rather than a `String` which supports different types in its string interpolation than plain strings do (which does not include `Bool` apparently).
There's a couple ways you can work around this.
You could use the `Text` initializer that takes a `String` and just displays it verbatim without attempting to do any localization:
```
var body: some View {
Text(verbatim: "The BOOL 1 value is : Bool 1 = \(defaults.bool(forKey: "MyBool 1"))")
}
```
Alternatively, you could extend `LocalizedStringKey.StringInterpolation` to support bools and then your original code should work:
```
extension LocalizedStringKey.StringInterpolation {
mutating func appendInterpolation(_ value: Bool) {
appendInterpolation(String(value))
}
}
``` |
221076 | I'm using *`LabelEncoder`* and *`OneHotEncoder`* from *`sklearn`* in a Machine Learning project to encode the labels (country names) in the dataset. Everything works good and my model runs perfectly. The project is to classify whether a bank customer will continue with or leave the bank based on a number of features(data), including the customer's country.
My issue arises when I want to predict (classify) a new customer (one only). The data for the new customer is still not pre-processed (i.e., country names are not encoded). Something like the following:
```
new_customer = np.array([['France', 600, 'Male', 40, 3, 60000, 2, 1,1, 50000]])
```
In the online course, where I learn machine learning, the instructor opened the pre-processed dataset that included the encoded data and ***manually*** checked the code for France and updated it in the `new_customer`, as the following:
```
new_customer = np.array([[0, 0, 600, 'Male', 40, 3, 60000, 2, 1,1, 50000]])
```
I believe that this is not practical, there must be a way to automatically encode France to the same code used in the original dataset, or at least a way to return a list of the countries and their encoded values. Manually encoding a label seems tedious and error-prone. So how can I automate this process, or generate the codes for the labels? Thanks in advance. | It seems like you may be looking for the `.transform()` method of your estimator.
```
>>> from sklearn.preprocessing import LabelEncoder
>>> c = ['France', 'UK', 'US', 'US', 'UK', 'China', 'France']
>>> enc = LabelEncoder().fit(c)
>>> encoded = enc.transform(c)
>>> encoded
array([1, 2, 3, 3, 2, 0, 1])
>>> encoded.transform(['France'])
array([1])
```
This takes the "mapping" that was learned when you called `fit(c)` and applies it to new data (in this case, a new label). You can see this mapping in reverse:
```
>>> enc.inverse_transform(encoded)
array(['France', 'UK', 'US', 'US', 'UK', 'China', 'France'], dtype='<U6')
```
As mentioned by the answer here, if you want to do this between Python sessions, you could serialize the estimator to disk like this:
```
import pickle
with open('enc.pickle', 'wb') as file:
pickle.dump(enc, file, pickle.HIGHEST_PROTOCOL)
```
Then load this in a new session and transform incoming data with it. |
221284 | When I click on an item of a listView, the background of an other item than I have clicked is changed. If I click on the first one, the background of that and of the last item of the ListView is changing. If I scroll down and click on an item, the item after the one I clicked changes its color. What can I do to just change the selected item's background?
XML:
```
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lvPlace"/>
```
Java:
```
lvPlace=(ListView) findViewById(R.id.lvPlace);
lvPlace.setAdapter(placeAdapter);
lvPlace.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lvPlace.getChildAt(position).setBackgroundColor(myColors[0]);
}
});
``` | You can set the background of the list item when you click with `xml` also
First add `android:listSelector` to `listview`
```
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:divider="@android:color/transparent"
android:dividerHeight="4.0sp"
android:listSelector="@drawable/list_row_selector"/>
```
Now create `list_row_selector.xml` in drawables
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_row_bg" android:state_pressed="false" android:state_selected="false"/>
<item android:drawable="@drawable/list_row_bg_hover" android:state_pressed="true"/>
<item android:drawable="@drawable/list_row_bg_hover" android:state_pressed="false" android:state_selected="true"/>
```
list\_row\_bg.xml
```
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<gradient
android:startColor="#ffffff"
android:centerColor="#ffffff"
android:endColor="#ffffff"
android:angle="270" />
```
list\_row\_bg\_hover.xml
```
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<gradient
android:startColor="#18d7e5"
android:centerColor="#16cedb"
android:endColor="#09adb9"
android:angle="270" />
```
Hope this will work for you..!! |
221339 | I need to change edit/create methods in Pages controller (or any custom generated engine), but can't find any. I has overrode all the controllers and tried searching the whole project for any "def edit" and did not find any.
I am new to Rails and I don't understand how this works. debug(params) points to refinery/admin/pages when I try to edit page, but there is no edit methods nor in admin or pages controller. So where the request is actually going when I hit update button or creating new page? | You said:
>
> floatval(preg\_replace('/[^\d.]/', '', $price[0]))
> but it added "36"
> to the number - insteadh of 18.95 i got 3618.95
>
>
>
It comes in my mind that you doesn't have a `$` sign in front of your values but `$` that is the representation of `$`.
In order to see if my guess is correct, print the array in a terminal instead of a browser. Or look at the source of the page.
In this case, you could do:
```
$val = preg_replace('/$/', '', $val);
```
or, more generalist:
```
$val = preg_replace('/&.*?;/', '', $val);
``` |
221392 | New to react native. Here is what I am trying to do:
1. Render a page with three components: top panel, middle row, and content box.
2. When the user scrolls down, the top panel is scrolled and disappears, middle row is scrolled but is sticky to the top of the screen, and the content box is scrolled all the way down until the end of the content.
Below code serves my intention. However, when I use this code, I get warnings about nesting virtualized views.
```
return (
<View style={style.profileContainer}>
<ScrollView
stickyHeaderIndices={[1]}
showsVerticalScrollIndicator={false}
>
<TopPanel /> // This is a view component and is scrolled up as the user scrolls down.
<MiddleRow /> // This is a view component that is sticky to the top of the screen
<BottomArray /> //This is a FlatList
</ScrollView>
</View>
)
```
Below code gets rid of the warning but all the scroll/sticky behaviors of the top/middle components disappear. They just remain fixed as the user scrolls down.
```
return (
<View style={style.profileContainer}>
<SafeAreaView style={{flex:1}}>
<TopPanel /> // This is a view component and is fixed as the user scrolls down.
<MiddleRow /> // This is a view component and is fixed as the user scrolls down.
<BottomArray /> //This is a FlatList
</SafeAreaView>
</View>
)
```
Is there a way to make the top panel scrollable and middle row sticky without relying on ScrollView? This is one of the key interfaces of the app and I'd like to keep it alive.
Thanks! | It's just an eslint warning so you don't *have* to fix it. But basically any variables which are used in the `useEffect` function are expected to be included in the dependency array. Otherwise, the effect will never be re-run even if the function `fetchBudgets` were to change.
It is expecting your hook to look like
```
useEffect(() => {
fetchBudgets();
}, [fetchBudgets]);
```
Where the effect will run once when the component is mounted and run again any time that the `fetchBudgets` function changes (which is probably never).
If it's executing more than once, that means that `fetchBudgets` has changed and you should try to figure our where and why it has been redefined. Maybe it needs to be memoized?
[Here are the docs](https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies) on putting functions in the dependency array. |
221560 | I have this in my viewWillAppear method
```
[RPCoreData
getFetchedControllerForCategoryDiscoverDelegate:self completion:^(NSFetchedResultsController *controller) {
self.fetchedResultController = controller;
self.fetchedResultController.delegate = self;
}];
```
and this in my CoreData.m
```
+ (void)
getFetchedControllerForCategoryDiscoverDelegate:(id<NSFetchedResultsControllerDelegate>)delegate
completion:(void (^)(NSFetchedResultsController *controller))
completion {
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
NSFetchedResultsController *controller = [ItemData MR_fetchAllGroupedBy:@"category.id"
withPredicate:nil
sortedBy:@"category.id"
ascending:NO
delegate:delegate
inContext:localContext];
completion(controller);
}];
}
``` | You don't need to wrap the creation of a `NSFetchedResultsController` around a `saveWithBlock:` from `MagicalRecord` since you are effectively only fetching objects, not changing them.
I do understand why you did it though (in order to get a local `NSManagedObjectContext`)
`MagicalRecord` has a convenience method that does not require you to pass a `NSManagedObjectContext`:
```
+ (NSFetchedResultsController *) MR_fetchAllGroupedBy:(NSString *)group withPredicate:(NSPredicate *)searchTerm sortedBy:(NSString *)sortTerm ascending:(BOOL)ascending;
```
This will use the context for the current thread you're in during execution, so if you're not doing anything too complex like switching between threads and managing different contexts, you should be fine with it.
This way your method should be able to return a `NSFetchedResultsController` right away, without using blocks.
Moreover, it seems like you are setting up the `delegate` twice, once inside the block and once when passed as a parameter to the `MR_fetchAllGroupedBy:..`
Finally, make sure your newly created `NSFetchedResultsController` is not `nil`, and implement one of `delegate` methods in the same class as your `viewWillAppear:`, then use breakpoints/logging to see if they are called:
```
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
NSLog(@"objects: %@", controller.fetchedObjects);
}
``` |
222166 | In book 2 of [*Aurora Leigh*](https://www.gutenberg.org/ebooks/56621) by Elizabeth Barrett Browning, Aurora’s cousin Romney doubts there is any value in women writing poetry:
>
> ‘Who has time,
>
> An hour’s time … think! … to sit upon a bank
>
> And hear the cymbal tinkle in white hands?
>
> When Egypt’s slain, I say, let Miriam sing!—
>
> Before … where’s Moses?’
>
>
>
But Aurora defends herself:
>
> ‘Ah—exactly that!
>
> Where’s Moses?—is a Moses to be found?—
>
> You’ll seek him vainly in the bulrushes,
>
> While I in vain touch cymbals. Yet, concede,
>
> Such sounding brass has done some actual good,
>
> (The application in a woman’s hand,
>
> If that were credible, being scarcely spoilt,)
>
> **In colonising beehives**.’
>
>
>
Most of this is straightforward. [Miriam](https://en.wikipedia.org/wiki/Miriam) is an Israelite woman in the Book of Exodus. She plays a [timbrel](https://en.wikipedia.org/wiki/Timbrel) (tambourine) and sings a song in [Exodus 15:20-21](https://biblehub.com/exodus/15-20.htm) after the death of Pharoah (“Egypt”) at the crossing of the Red Sea. She is traditionally identifed with Moses’ sister, who watched their mother place the baby Moses in a basket among the reeds (“bulrushes”) of the Nile, in [Exodus 2:4](https://biblehub.com/exodus/2-4.htm). “Sounding brass”, “cymbal”, and “tinkle” are references to [1 Corinthians 13:1](https://biblehub.com/1_corinthians/13-1.htm):
>
> Though I speak with the tongues of men and of angels, and have not charity, I am become as sounding brass, or a tinkling cymbal.
>
>
>
But what does Aurora mean by “colonising beehives”? | Removing the parenthetical interruption so as to follow the syntax better, we have
>
> While I in vain touch cymbals. Yet, concede,
>
> Such sounding brass has done some actual good,
>
> ...
>
> In colonising beehives.’
>
>
>
So what do cymbals have to do with beehives? In [this webpage](https://www.medievalists.net/2015/06/medieval-beekeeping/) on medieval bee-keeping, it quotes a 10th-century Byzantine text which says:
>
> This animal [the bee] is pleased by a good tune: when they are scattered, therefore, beekeepers clash cymbals or clap their hands rhythmically to bring them home.
>
>
>
I assume Elizabeth Barrett Browning knew about this custom. It was probably still being practiced eight centuries later, when she wrote. Even today, people are [still asking](https://www.beesource.com/forums/archive/index.php/t-285423.html) about the accuracy of the "old wives' tale" that clapping your hands will cause a swarm of bees to land so they can be captured.
I have no idea whether this advice is accurate. However, its metaphorical relevance to the poem is clear. Aurora is saying that even though she's sitting tinkling her cymbals while other people are actively looking for Moses in the bulrushes, it's nevertheless possible that the cymbals will call Moses to her. |
222399 | When a user open the app for the first time the permissions page comes back with a *code* that i'm using here
<https://graph.facebook.com/oauth/access_token?client_id=ID&redirect_uri=MY_URL&client_secret=SECRET&code=CODE>
to get the access token.
If is the first time that the user open the app it works. If is not the first time i can't get an updated token. I've tried saving the code for each user that joins, but it changes and old codes can't provide an access token. I've also tried to save the token but it expire too.
I also prefere to don't use the offline\_access permission.
Thanks in advance for the help ;) | No, this cannot be done. However, as [Nick Johnson](https://stackoverflow.com/a/1318416/1101070) points out, you can use [remote\_api](http://code.google.com/appengine/articles/remote_api.html) to do what you need. |
223242 | I am getting this error
>
> "Android resource linking failed
> C:\Users\xervice111\AndroidStudioProjects\ud843-QuakeReport-starting-point\app\src\main\res\layout\list\_item.xml:10:
> error: resource drawable/magnitude\_circle (aka
> com.example.android.quake
>
>
> report:drawable/magnitude\_circle) not found. error: failed linking
> file resources."
>
>
>
[This is the error](https://i.stack.imgur.com/GKjzc.png)After I added a drawable resource file named "magnitudeCircle.xml". I have done things like clean project, rebuild project, Invalidate and restart etc but the error is still there ...
[This is my magnitubeCircle.xml file](https://i.stack.imgur.com/eB300.png)
```
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<!-- Background circle for the magnitude value -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/magnitude1" />
<size
android:width="36dp"
android:height="36dp" />
<corners android:radius="18dp" />
</shape>
``` | **Try This**
```
<?xml version="1.0" encoding="utf-8"?>
<!-- Background circle for the magnitude value -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/magnitude1" />
<size
android:width="36dp"
android:height="36dp" />
<corners android:radius="18dp" />
</shape>
``` |
223358 | I would like to use CSS filters in JavaScript.
Example of CSS filters:
```
.filter {
-webkit-filter: blur(20px); /* Blur filter */
-webkit-filter: invert(1); /* Invert filter */
-webkit-filter: hue-rotate(100deg); /* Rotate Hue */
...
}
```
For example, how can I make a blurred image using JavaScript?
```
<img id="image" onmouseover="ImageHover();" src="source.png"/>
```
while
```
function ImageHover() {
document.getElementById('image').??????='???'
}
```
I hope you guys understand what I want. | I recommend using **this** so the function can be used with any element/Img you want later
```
<img id="image" onmouseover="ImageHover(this);" src="source.png"/>
function ImageHover(el){
el.classList.add("filter");
};
``` |
223494 | So I have the code bellow. My problem, is that to make the «vous êtes amis» message appear, the user have to click twice on the submit button. But I want to make the user click only once on the submit button. Thanks!
```
<?php
$checkcontact = mysql_query("SELECT * FROM contacts WHERE IDcontact = '".$dnn['id']."'");
if(mysql_num_rows($checkcontact) == 1)
{
echo "<h1>Vous êtes amis</h1>";
}
else
{
?>
<form method="post" action="profile.php?id=<?php echo $dnn['id']; ?>">
<input type="hidden" value="<?=$dnn['Username'];?>" name="userid" />
<input type="submit" value="Add as Friend" />
</form>
<?php
if ($_POST)
{
$fid = htmlspecialchars(stripslashes($_POST['userid']));
$fid = mysql_real_escape_string($fid);
include("base.php");
mysql_query("INSERT into contacts (ID, Nom, IDcontact, Nomcontact) VALUES ('".$_SESSION ['id']."', '".$_SESSION['Username']."', '".$dnn['id']."', '$fid')");
}
}
?>
``` | Move this block of code to the end:
```
$checkcontact = mysql_query("SELECT * FROM contacts WHERE IDcontact = '".$dnn['id']."'");
if(mysql_num_rows($checkcontact) == 1)
{
echo "<h1>Vous êtes amis</h1>";
}
else
{
```
This checks the value in the database AFTER it's been inserted. Right now, You're checking before it's been submitted |
223548 | Something is wrong with my code that i can't figure it out, will you help me to find my mistake? Thank you!
```
/// Calculate Prime
private static int countPrimes(int number){
int count =0;
for(int i=1; i<=MAX_PRIME; i++) {
if(isPrime(i)){
count++;
}
}
System.out.println("Exactly "+ count + " prime numbers exist between "+number + " and 1000.");
return number;
}
```
here is my result:
Exactly 180 prime numbers exist between 1 and 1000. Which is wrong and has to be 168!!! | It seems that your implicit parameter, int number, is never used in your program.
Try this code:
```
private static int countPrimes(int number){
int count =0;
int countPrimes=0;
if(number<2)
return 0;
for(int i=2; i<=number; i++) { //start i=2, because you know that 1 is not a prime number.
for(int j=1; j<=i; j++){
if(i%j==0)
count++;
}
if(count ==2)
countPrimes++;
count=0;
}
return number;
}
```
Then, in your runner method, call:
```
int numOfPrimes = countPrimes(10000);
```
In this, you can vary what number you want to count up to. In this example it counts the primes up to 10000.
```
int numOfPrimes = countPrimes(100);
```
This will count primes up to 100. If you want to keep track of the primes, in your program you could add:
```
ArrayList<Integer> listOfPrimes = new ArrayList<Integer>();
private static int countPrimes(int number){
int count =0;
int countPrimes=0;
if(number<2)
return 0;
for(int i=2; i<=number; i++) { //start i=2, because you know that 1 is not a prime number.
for(int j=1; j<=i; j++){
if(i%j==0)
count++;
}
if(count ==2){
countPrimes++;
listOfPrimes.add(i);
}
count=0;
}
return number;
}
```
In order to retrieve your numbers you could do something like this:
```
System.out.println("Exactly "+ countPrimes(number) + " prime numbers exist between "+ "1" + " and " + number + ".");
System.out.println("These numbers are: ");
for(int i =0; i<listOfPrimes.size();i++){
System.out.println(listOfPrimes.get(i));
}
``` |
223988 | I'm using a SplitViewController which can't be part of a navigation controller. I'm using SetRootViewController on an IBAction, which is fine, but it's not animated. Ideally I'd like to use the same animation as the Navigation Controller does (slide in from the left/right) but if that's not possible I'd like to use a consistent animation when ever I need to do this. | I'm not sure about this, but I would suggest the following.
Set the `UISplitViewController` as your `UIWindow`'s `rootViewController`. In the `viewDidLoad`, you make a `presentModalViewController:animated:` call with the button's `UIViewController` as modal. Make sure you don't animate it. This gives you the illusion that the modal view is the first you see when the app launches.
When you push the button, you animate the button's `UIViewController` out with `dismissModalViewControllerAnimated:`. Now you can choose how to animate. One of your choices is cross disolve. |
224315 | I am trying to read and get the size of the zip file in PHP.
Following is my code:
```
function create_zip($files, $file_name, $overwrite = false) {
foreach ($files as $imglink) {
$img = file_get_contents($imglink);
$destination_path = $_SERVER['DOCUMENT_ROOT'] . 'demoproject/downloads/' . time() . '.jpg';
file_put_contents($destination_path, $img);
$imgFiles[] = $destination_path;
}
if (file_exists($file_name) && !$overwrite) {
return false;
}
$valid_files = array();
if (is_array($imgFiles)) {
foreach ($imgFiles as $file) {
$valid_files[] = $file;
}
}
if (count($valid_files)) {
$zip = new ZipArchive();
if ($zip->open($file_name, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
echo "Sorry ZIP creation failed at this time";
}
foreach ($valid_files as $file) {
$zip->addFile($file, pathinfo($file, PATHINFO_BASENAME));
}
$count = $zip->numFiles;
$resultArr = array();
$resultArr['count'] = $count;
$resultArr['destination'] = $file_name;
$filename = $file_name;
$filepath = $_SERVER['DOCUMENT_ROOT'] . 'demoproject/';
$fileSize = filesize($filepath . $filename) / 1024;
echo 'size of the file is : ' . $fileSize . ' kb';
exit;
// $size = 0;
// $resource = zip_open($filepath . $filename);
// while ($dir_resource = zip_read($resource)) {
// $size += zip_entry_filesize($dir_resource);
// }
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . zip_entry_filesize($filepath . $filename));
if (@readfile($filepath . $filename) === false) {
header('http://localhost/demoproject/fbindex.php');
return 500;
} else {
header('Location:http://localhost/demoproject/fbindex.php');
return 200;
}
} else {
return false;
}
}
```
`$files` : contain the array of images and
`$file_name` : contain name of file : that is : `$file_name = time() . ".zip";`
In the above code `$filename` contains the actual zip file and `$filepath` contains the location of the zip file.
The issue is it's reading the file but always showing its size 0 instead of actual file size.
This is I am doing :
`echo $size;`
`O/P : 0`
Where am I going wrong? Need Help. Thanks | try this -
```
$fileSize = filesize($filepath . $filename)/1024;
echo 'size of the file is : '.$fileSize.' kb';
``` |
224399 | The DenOfGeek article [Brew2013] has screen captures from the movie [*Superman III*](https://en.wikipedia.org/wiki/Superman_III), in particular the early scenes in the movie where character Gus Gorman is at computer programming school.
![A screen capture from Superman III](https://i.stack.imgur.com/oL2lL.jpg)
The terminal used appears to be a real terminal, attached to something that is running a BASIC interpreter.
(The program listed is BASIC; albeit that the program-within-a-program that it outputs, supposedly the character's `PLOT BILATERAL CO-ORDINATES` program, is really not; as it lacks `LET`s and `FOR`s and would be a `SYNTAX ERROR IN 10`.
But this question isn't about the programming language, which is easy and covered in the likes of [Birken2008].)
It could be a home computer of the time, alternatively.
It's tricky to identify *what* terminal/home computer, though.
Some observations:
* There might be a logo on the plate to the right of the CRT, but it is illegible in the screen captures.
* There is no numeric keypad at all. (It looks like something that could have a numeric keypad option, though.)
* The `Return` key occupies a single row, rather than being a reversed "L" shape.
* There are arrow keys, which are on the top two rows, above `Return`.
* The arrow keys include diagonal arrows.
* The keys come in (at least) blue, black, white, and green.
* There are three knobs between the keyboard and CRT; again with illegible labels. (My *guess* would be brightness and vertical/horizontal adjust.)
* There are also, on the left hand side, what appear to be two pushbuttons.
The keyboard rules out a [DECmate](https://en.wikipedia.org/wiki/DECmate) or a [Zenith Z-89](https://en.wikipedia.org/wiki/Zenith_Z-89).
There is a resemblance to things like the [Wang OIS](https://en.wikipedia.org/wiki/Wang_Laboratories#Wang_OIS_2) and the Wang 5536, but the keyboard and knobs are wrong.
It is not curvy enough to be an ADDS Regent or ADDS Consul, and again the knobs are wrong.
And given that in the long shots several of the students in the Archibald School of Data Processing have these, it seems more likely to be something off-the-shelf rather than something that the props department dummied up.
What terminal/home computer is it?
References
==========
* Simon Brew (2013-10-23). *[What Superman 3 teaches us about computer programming](https://denofgeek.com/movies/what-superman-3-teaches-us-about-computer-programming/)*. denofgeek.
* Mike Birken (2008-03-30). "[Gus Gorman's Super BASIC Program](https://meatfighter.com/superman3/part1/index.html)". *Superman III Analysis*. Meat Fighter. | *[So far not an Answer, just a pointer from some Google supported memory - nice question research BTW]*
There are other scenes showing the terminals, for example later on, when he get's his first pay check (and the idea to round up pennies) like seen in [this Youtube clip](https://www.youtube.com/watch?v=N7JBXGkBoFc). Here they are setup in a data center (\*1). Notable point here are the [disk drives](https://youtu.be/N7JBXGkBoFc?t=90) in the back (another [overview seen here](https://youtu.be/RtiPaSKlHsI?t=14)). They are most certainly OEMed CDC 844-2 storage units of ~1972, safe to be scrapped into movie use by 1980.
Bad part, CDC was *the* essential OEM manufacturer for mainframe peripherals at the time. So unless someone recognizes the exact colouring, labeling and button caps (they differ in colour from the original CDC setup), chances are slim to get an identification.
*Additional find:* [An answer pointing to ICL's 1900](https://retrocomputing.stackexchange.com/a/15506/6659) made me looking again, and while I couldn't find any 1900 reference, I came across a site mentioning an [ICL 2900](http://www.chilton-computing.org.uk/acd/ga/p001.htm) sowing a picture with [ICLed CDC 844-2 drives](http://www.chilton-computing.org.uk/gallery/ral76/orig/r28666.jpg). Comparing the big ICL plaque on the left side with a similar sized but [blurry ones](https://youtu.be/N7JBXGkBoFc?t=90) in the clip supports the theory a lot. Except, they are blue, not orange as suggested.
So yes, I'd say ICL for the drives might be a great lead ... but leaving the OEM issue.
Since the terminals as well are of lower function and at least as old (early 70s), it might be safe to assume they did come with the drives. In fact, all of the equipment looks rather fitting, so the prop team may have scored a full data center.
So the question might be narrowed down which mainframe manufacturer of the early 70s did use the shown design.
For the terminal itself, the key colouring is quite revealing as it follows standards set by keypunches (like IBM 028, Univac 1710 or alike) (\*2). So it must have been designated for a mainframe environment (see the disk drive) as well it must be early on, as this kind of structuring already started to vanish in the early 1970s.
It also reassembles a bit a CDC 711/713 terminal in the way the additional switches below the screen are positioned. Then again, the case shape does not match.
---
\*1 - In fact one has to admire how hard the prop guys tried to make it right and how much the filming screwed that. Just think the incredible noise of 20+ drives, chain printers and alike. As expected many will wear earmuffs. Except, to make the scene work out, no (real) noise was present :(
\*2 - In fact, looking at the keys on the left and all the markings on the top row, were today numbers would be present,, it really reassembles a keypunch, not a later terminal. So what we see might be some quite early on non-IBM attempt to a data entry terminal. |
224593 | I've been working on an instantiation method that will allow me to package a variety of similar classes into one outer class. I could then instantiate each unique class type by passing the name of that type to the constructor. After a lot of research and errors, this is what I have come up with. I have left an error, to demonstrate my question.
```
import java.lang.reflect.Constructor;
public class NewTest
{
public static void main(String[] args)
{
try
{
Class toRun = Class.forName("NewTest$" + args[0]);
toRun.getConstructor().newInstance();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
public NewTest(){}
private class one //Does not instantiate
{
public one()
{
System.out.println("Test1");
}
}
private static class two //Instantiates okay
{
public two()
{
System.out.println("Test2");
}
}
}
```
Compiling this code and running `java NewTest two` results in the output `Test2`, as I intended.
Running `java NewTest one` results in
```
java.lang.NoSuchMethodException: NewTest$one.<init>()
at java.lang.Class.getConstructor(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at NewTest.main(NewTest.java:12)
```
I'm confused about this because, as far as I know, I am referencing an inner class correctly, an outer class should have access to an inner class, and I have a default no arg constructor. | Non-static inner classes need an instance of the outer class to work properly. So, they don't "really" have a default constructor, they always have a kind of hidden parameter in which they expect an outer class instance.
I don't know why you want to have them all in a single class. If you are doing this so that it's only one file, put them in a package and in separate classes. Having less files does not make your program better.
If instead you need them to share something, so the outer class will work as a kind of "scope", you can still do that without using inner classes, but by passing them a context of some sort.
If you really really want to instantiate the inner class, you need to use the hidden constructor taking the outer class as a parameter :
```
NewTest outer = new NewTest();
Class<?> toRun = Class.forName("NewTest$" + args[0]);
Constructor<?> ctor = toRun.getDeclaredConstructor(NewTest.class);
ctor.newInstance(outer);
``` |
224623 | Basically I need to replicate Hartley's 'A User's Guide to Solving Real Business Cycle Models' (<http://www.econ.ucdavis.edu/faculty/kdsalyer/LECTURES/Ecn235a/Linearization/ugfinal.pdf>). Specifically, I want to simulate the dynamical system implied by the model which is specified as follows:
![enter image description here](https://i.stack.imgur.com/2LuOx.png)
where $c$ is consumption, $h$ is labour supply, $k$ is capital, $z$ is the autoregressive technological process, $y$ is the output and $i$ is investment.
I simulate it using the following logic: say at time $t$, everything is at steady state and all the values are 0, from which we have $k\_{t+1}$. Then, at $t+1$ by giving a shock to the system through $\varepsilon$, i solve for $c\_{t+1}$ and $h\_{t+1}$ (as I have the 'shocked' $z\_{t+1}$ and previously obtained $k\_{t+1}$. Then, I plug those two to retrieve the rest, namely - $y\_{t+1}, i\_{t+1}, k\_{t+2}$ and repeat the process.
Unfortunately, I get an explosive process which doesn't make sense:
![enter image description here](https://i.stack.imgur.com/weeDr.png)
I also include R code that is used to simulate this:
```
n<-300
data.simulated <- data.table(t = 0, zval = 0, cval = 0, hval = 0, kval = 0, yval = 0, ival = 0)
data.simulated <- rbind(data.simulated, data.table(t = 1, kval = 0), fill = TRUE)
for (ii in 1:n){
##initial shocks
eps <- rnorm(1, mean = 0, sd = 0.007)
zt1 <- data.simulated[t == ii - 1, zval]*0.95 + eps
kt1 <- data.simulated[t == ii, kval]
##solve for ct, ht
lmat <- matrix(c(1, -0.54, 2.78, 1), byrow = T, ncol = 2)
rmat <- matrix(c(0.02 * kt1 + 0.44 * zt1, kt1 + 2.78 * zt1), ncol = 1)
solution <- solve(lmat, rmat)
ct1 <- solution[1, ]
ht1 <- solution[2, ]
##now solve for yt1 and kt2 and it1
yt1 <- zt1 + 0.36 * kt1 + 0.64 * ht1
kt2 <- -0.07 * ct1 + 1.01 * kt1 + 0.06 * ht1 + 0.1 * zt1
it1 <- 3.92 * yt1 - 2.92 * ct1
##add to the data.table the results
data.simulated[t == ii, c("zval", "cval", "hval", "yval", "ival") := list(zt1, ct1, ht1, yt1, it1)]
data.simulated <- rbind(data.simulated, data.table(t = ii + 1, kval = kt2), fill = TRUE)
}
a <- data.simulated[, list(t, cval, ival, yval)]
a <- data.table:::melt.data.table(a, id.vars = "t")
ggplot(data = a, aes(x = t, y = value, col = variable)) + geom_line()
```
Sy my question is simple - is the system specified in the paper is inherently unstable and ergo the results, or did I make a mistake somewhere? | **Explosiveness**
The paper contains an error, which causes the explosive dynamics in your simulation (although presumably the underlying computations in the paper were correct). The equilibrium condition derived from eigenvalue decomposition is contained in the third row of matrix $Q^{-1}$ on page 12 of the paper, with variables ordered as $(c,k,h,z)$ (I'll drop tildas, so all lowercase variables are to be understood as log-deviations). Comparing with eqn. (16) on p. 13, we see that coefficients for $k$ and $h$ are switched, and so the correct condition is
$$
c\_t = 0.54 k\_t + 0.02 h\_t + 0.44 z\_t
$$
**Simulation**
First, we can express consumption and labor as linear function of state variables (no need to solve the system at each step of the simulation). The intertemporal and intratemporal equilibrium conditions can be written as
$$
\begin{bmatrix}1 & -0.02 \\ 2.78 & 1 \end{bmatrix} \begin{bmatrix} c\_t \\ h\_t\end{bmatrix} = \begin{bmatrix} 0.54 & 0.44 \\ 1 & 2.78 \end{bmatrix} \begin{bmatrix} k\_t \\ z\_t\end{bmatrix}
$$
so after multiplying by an inverse we get
$$
\begin{bmatrix} c\_t \\ h\_t\end{bmatrix} = \begin{bmatrix} 0.53 & 0.47 \\
-0.47 & 1.47 \end{bmatrix} \begin{bmatrix} k\_t \\ z\_t\end{bmatrix}
$$
Next, transition for states can be written as
$$
\begin{bmatrix} k\_{t+1} \\ z\_{t+1} \end{bmatrix} = \begin{bmatrix} -0.07 & 0.06 \\ 0 & 0 \end{bmatrix} \begin{bmatrix} c\_t \\ h\_t\end{bmatrix} + \begin{bmatrix} 1.01 & 0.1 \\ 0 & 0.95 \end{bmatrix} \begin{bmatrix} k\_t \\ z\_t\end{bmatrix} + \begin{bmatrix} 0 \\ \epsilon\_{t+1}\end{bmatrix}
$$
which can be reduced by substuting for control variables to
$$
\begin{bmatrix} k\_{t+1} \\ z\_{t+1} \end{bmatrix} = \begin{bmatrix} 0.94 & 0.16 \\ 0 & 0.95 \end{bmatrix} \begin{bmatrix} k\_t \\ z\_t\end{bmatrix} + \begin{bmatrix} 0 \\ \epsilon\_{t+1}\end{bmatrix}
$$
Now the simulation should be trivial, here's a Matlab/Octave example:
```
T = 200;
X = zeros(2,T);
for i=2:T
X(:,i) = [0.94 0.16; 0 0.95] * X(:,i-1) + [0; 0.007*randn()];
end
Y = [0.53 0.47; -0.47 1.47] * X;
figure
plot(1:T, [X; Y])
legend('k','z','c','h')
```
![Simulation](https://i.stack.imgur.com/MPNc9.png)
Of course in practice, you should probably recompute the whole solution, including the eigenvalue decomposition, so that you would be able to change parameters, etc. |
224873 | I have an PHP code that makes a call to a webservice and returns a XSD, but I don't know how to read its elements. What would be the best way?
I've searched and ended up with DOMDocuments, but I didn't understood it quite well. Is that the best way?
**EDIT** - Ok, I was able to get my xsd to a DOMDocument, now how can I get, for example, the value from node CATEGORIA in the second product?
Here is the code it returns:
```
<?xml version="1.0" encoding="utf-8"?>
<DataSet xmlns="http://">
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Produtos">
<xs:complexType>
<xs:sequence>
<xs:element name="TIMESTAMP" type="xs:dateTime" minOccurs="0" />
<xs:element name="DEPARTAMENTO" type="xs:string" minOccurs="0" />
<xs:element name="CATEGORIA" type="xs:string" minOccurs="0" />
<xs:element name="SUBCATEGORIA" type="xs:string" minOccurs="0" />
<xs:element name="FABRICANTE" type="xs:string" minOccurs="0" />
<xs:element name="CODIGO" type="xs:string" minOccurs="0" />
<xs:element name="DESCRICAO" type="xs:string" minOccurs="0" />
<xs:element name="DESCRTEC" type="xs:string" minOccurs="0" />
<xs:element name="PARTNUMBER" type="xs:string" minOccurs="0" />
<xs:element name="EAN" type="xs:string" minOccurs="0" />
<xs:element name="GARANTIA" type="xs:int" minOccurs="0" />
<xs:element name="PESOKG" type="xs:decimal" minOccurs="0" />
<xs:element name="PRECOREVENDA" type="xs:decimal" minOccurs="0" />
<xs:element name="PRECOSEMST" type="xs:decimal" minOccurs="0" />
<xs:element name="DATAVALIDADEPRECO" type="xs:dateTime" minOccurs="0" />
<xs:element name="DISPONIVEL" type="xs:int" minOccurs="0" />
<xs:element name="URLFOTOPRODUTO" type="xs:string" minOccurs="0" />
<xs:element name="ESTOQUE" type="xs:string" minOccurs="0" />
<xs:element name="NCM" type="xs:string" minOccurs="0" />
<xs:element name="LARGURA" type="xs:decimal" minOccurs="0" />
<xs:element name="ALTURA" type="xs:decimal" minOccurs="0" />
<xs:element name="PROFUNDIDADE" type="xs:decimal" minOccurs="0" />
<xs:element name="ATIVO" type="xs:int" minOccurs="0" />
<xs:element name="SUBSTTRIBUTARIA" type="xs:int" minOccurs="0" />
<xs:element name="ORIGEMPRODUTO" type="xs:string" minOccurs="0" />
<xs:element name="ESTOQUEDISPONIVEL" type="xs:decimal" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet xmlns="">
<Produtos diffgr:id="Produtos1" msdata:rowOrder="0">
<TIMESTAMP>2017-08-11T11:09:26-03:00</TIMESTAMP>
<DEPARTAMENTO></DEPARTAMENTO>
<CATEGORIA></CATEGORIA>
<SUBCATEGORIA></SUBCATEGORIA>
<FABRICANTE>GENIUS</FABRICANTE>
<CODIGO>0064703</CODIGO>
<DESCRICAO></DESCRICAO>
<DESCRTEC></DESCRTEC>
<PARTNUMBER>31731047103</PARTNUMBER>
<EAN>4710268244738</EAN>
<GARANTIA>12</GARANTIA>
<PESOKG>3.1000</PESOKG>
<PRECOREVENDA>95.0000</PRECOREVENDA>
<PRECOSEMST>95.0000</PRECOSEMST>
<DATAVALIDADEPRECO></DATAVALIDADEPRECO>
<DISPONIVEL>1</DISPONIVEL>
<URLFOTOPRODUTO></URLFOTOPRODUTO>
<ESTOQUE>RJ</ESTOQUE>
<NCM></NCM>
<LARGURA>0.3000</LARGURA>
<ALTURA>0.3500</ALTURA>
<PROFUNDIDADE>0.1700</PROFUNDIDADE>
<ATIVO>1</ATIVO>
<SUBSTTRIBUTARIA>0</SUBSTTRIBUTARIA>
<ORIGEMPRODUTO></ORIGEMPRODUTO>
<ESTOQUEDISPONIVEL>63.0000</ESTOQUEDISPONIVEL>
</Produtos>
<Produtos diffgr:id="Produtos2" msdata:rowOrder="1">
<TIMESTAMP>2017-08-14T18:01:00-03:00</TIMESTAMP>
<DEPARTAMENTO></DEPARTAMENTO>
<CATEGORIA></CATEGORIA>
<SUBCATEGORIA></SUBCATEGORIA>
<FABRICANTE>GENIUS</FABRICANTE>
<CODIGO>0064694</CODIGO>
<DESCRICAO></DESCRICAO>
<DESCRTEC></DESCRTEC>
<PARTNUMBER>31731006100</PARTNUMBER>
<EAN>4710268238461</EAN>
<GARANTIA>12</GARANTIA>
<PESOKG>0.4900</PESOKG>
<PRECOREVENDA>28.9900</PRECOREVENDA>
<PRECOSEMST>28.9900</PRECOSEMST>
<DATAVALIDADEPRECO></DATAVALIDADEPRECO>
<DISPONIVEL>1</DISPONIVEL>
<URLFOTOPRODUTO></URLFOTOPRODUTO>
<ESTOQUE>RJ</ESTOQUE>
<NCM>85182100 </NCM>
<LARGURA>0.1500</LARGURA>
<ALTURA>0.1200</ALTURA>
<PROFUNDIDADE>0.0700</PROFUNDIDADE>
<ATIVO>1</ATIVO>
<SUBSTTRIBUTARIA>0</SUBSTTRIBUTARIA>
<ORIGEMPRODUTO></ORIGEMPRODUTO>
<ESTOQUEDISPONIVEL>100.0000</ESTOQUEDISPONIVEL>
</Produtos>
</NewDataSet>
</diffgr:diffgram>
</DataSet>
```
Its in portuguese, but I think you guys can understand what is what. It returns me around 20 Products, and I need to make use of each of those informations | Solved!! Turned my XSD into an array with code below
```
$doc = new DOMDocument();
$doc->preserveWhiteSpace = true;
$doc->loadXML($response);
$doc->save('t.xml');
$xmlfile = file_get_contents('t.xml');
$parseObj = str_replace($doc->lastChild->prefix.':',"",$xmlfile);
$ob = simplexml_load_string($parseObj);
$data = json_decode(json_encode($ob), true);
``` |
225455 | I am trying to link to an external site.
where as $location outputs the URL (e.g. www.siteurl.com)
How do I make the outputted url a link and not just text
Thanks | Just `echo` out the anchor tags
```
echo '<a href="'.$location.'">Click</a>';
``` |
225607 | I am able to successfully store image in SQL DB,
There is a field for image as varchar50.
This is the code that I tried
```
DataTable dt=new DataTable();
dt=neworder.Selectfromimage1();
if (dt.Rows.Count > 0)
{
// byte[] image =(byte[])dt.Rows[0]["image"];
byte image=Convert.ToByte(dt.Rows[0]["image"]);
MemoryStream stream = new MemoryStream(image);
//stream.Write(image, 0, image.Length);
stream.Seek(0,
SeekOrigin.Begin);
stream.Close();
btncompanion.Image =
Image.FromStream(stream);
}
```
I am getting error "Input string was not in corret format "
on
```
byte image=Convert.ToByte(dt.Rows[0]["image"]);
```
**EDITED**
Code for saving image is
```
private byte[] ImageToStream(string fileName)
{
MemoryStream stream = new MemoryStream();
tryagain:
try
{
Bitmap image = new Bitmap(fileName);
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
// image.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
}
catch (Exception )
{
goto tryagain;
}
return stream.ToArray();
}
fName ="C:\\Documents and Settings\\KAEM\\My Documents\\My Pictures\\images.jpg";
if (File.Exists(fName))
{
int id = 2;
byte[] content = ImageToStream(fName);
if (neworder.Insertintoimage1(content.ToString()))
{
}
}
else
{
MessageBox.Show(fName + " not found ");
}
``` | You store the path to the image in your database.
Your code should look like this:
```
string imagePath=dt.Rows[0]["image"].ToString();
byte[] imageBytes;
using (FileStream fs = File.Open(imagePath)) {
btncompanion.Image = Image.FromStream(fs);
}
```
Try this, not tested |
225868 | >
> **Possible Duplicate:**
>
> [count vs length vs size in a collection](https://stackoverflow.com/questions/300522/count-vs-length-vs-size-in-a-collection)
>
>
>
Really strange:
C# arrays such as the following
```
double[] test = new double[1];
```
support the Length property to get the size of the array. But arrays also implement an IList interface:
```
IList<double> list = test;
```
However, the IList interface provides also a Count property. How come the array ("test" in this case) doesn't?
**Edit**: Thanks to all of you who pointed out that it is in fact the ICollection interface (not IList) which provides the Count property, and also that this is due to explicit implementation of the interface. | Simply, they chose to call it `Length`, and implement `Count` via explicit interface implementation -something like:
```
int ICollection.Count { get { return Length; } }
``` |
226199 | hey there, I'm creating a series of input elements and for some reason their values aren't `$_POST`ing. Any light shed on the subject would be appreciated!
My current code is as follows:
`javascript`
```
Afields = 1;
function addAdultInput() {
if (Afields != 10) {
document.getElementById('adultMembers').innerHTML += "<input type='text' value='' name='adult_members_"+Afields+"' /><br />";
Afields += 1;
} else {
document.getElementById('adultMembers').innerHTML += "Only 10 Adult Member fields allowed.";
document.getElementById('addAdultMember').disabled=true;
}
}
```
`HTML`
```
<form name="form1" method="post" action="">
<tr>
<td class="style12" valign="top">Adult Members' Names:<br /><small>10 Max </small><input id="addAdultMember" type="button" onclick="addAdultInput()" name="add" value="Add Adult" /></td>
<td id="adultMembers">
<span class="erorr">*for paid members only</span><br />
<input type='text' value='' name='adult_members_0' /><br />
</td>
</tr>
<input type="submit" name="Submit" value="Register">
</form>
``` | I am not sure if this is what is particularly happening with you, but generally using `innerHTML` to add input fields is not recommended.
Instead, you should use `createElement()` and `appendChild()`, or you can alternatively use a library like JQuery or Prototype. You can find tons of help on using these two functions online. |
226272 | I would like to know which is best suited for displaying visitor stats in our websites
The key areas under our consideration are
1. User Count
2. Unique User Count
3. User Location
Regards,
naveenj | [Google Analytics](http://www.google.com/analytics/) is free and it fits all your requirements. |
226279 | Consider the following code:
```
auditlog.getMessages()
.stream()
.filter(m -> messageId.equals(m.getMessageid()))
.findFirst()
.orElseThrow(NoMessageFoundException::new)
```
`NoMessageFoundException` is a custom unchecked exception, extending from `RuntimeException`. When `findFirst()` returns an empty optional I expect a `NoMessageFoundException` to be thrown, however, the code just carries on.
Is it impossible to do this with unchecked exceptions?
I could change `NoMessageFoundException` to a checked exception, but then I would have to write a `try/catch` block or some sort of wrapper to catch the exception as explained [here](http://www.baeldung.com/java-lambda-exceptions) but I wish to not do that.
Any ideas? | There is no limitation on the type of Exception that can be thrown.
```
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
```
If the code "carries on", it means that a message is found. |
226304 | Tried everything. This UPDATE don't work. No error or something - it just not updates the table.
```
void SetDisable (Integer ID, boolean action){
Integer s;
if (action==true) s = 0; else s = 1;
db.rawQuery("UPDATE sms SET disabled="+s+" WHERE id="+ID+"",null);
}
```
This is my table schema:
```
CREATE TABLE sms (id INTEGER PRIMARY KEY, fromhour INT, frommin INT, tohour INT, tomin INT, disabled INT);
sqlite>
``` | **Try this:**
```
db.execSQL("UPDATE sms SET disabled="+s+" WHERE id="+ID+"");
```
SQL queries which return a table (a cursor) are to be run with rawQuery, and those that do not return tables are to be run with execSQL
**See this:**
[Increase the value of a record in android/sqlite database](https://stackoverflow.com/questions/3427516/increase-the-value-of-a-record-in-android-sqlite-database) |
227194 | I use Apache Camel module deployed inside ActiveMQ service.
Given I use Spring DSL and I have route definition ( implemented as `routeContext`) in the `FilteringRouteContext.xml` file (simplified):
```
<routeContext id="filteringRouteContext" xmlns="http://camel.apache.org/schema/spring">
<route id="myFilteringRoute">
<from uri="direct:filteringRoute"/>
<idempotentConsumer messageIdRepositoryRef="idempotentRepository" skipDuplicate="false">
<simple>${header.JMSType}</simple>
<filter>
<property>CamelDuplicateMessage</property>
<stop/>
</filter>
</idempotentConsumer>
</route>
</routeContext>
```
Next, I have configured Camel Context in other XML file (simplified):
```
<import resource="classpath:FilteringRouteContext.xml"/>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<routeContextRef ref="filteringRouteContext"/>
<route id="myRoute1">
<from uri="activemq:topic:source1" />
<to uri="direct:filteringRoute" />
<to uri="activemq:topic:target1" />
</route>
<route id="myRoute2">
<from uri="activemq:topic:source2" />
<to uri="direct:filteringRoute" />
<to uri="activemq:topic:target2" />
</route>
<route id="myRoute3">
<from uri="activemq:topic:source3" />
<to uri="direct:filteringRoute" />
<to uri="activemq:topic:target3" />
</route>
</camelContext>
<bean id="idempotentRepository"
class="org.apache.camel.processor.idempotent.MemoryIdempotentRepository">
<property name="cacheSize" value="10"/>
</bean>
```
I would like to have shared route (with id=`myFilteringRoute`) from `filteringRouteContext` declared as, using IoC terminology, **instance per dependency**, so each route from single Camel Context (with id=`myRoute1`, `myRoute2`, `myRoute3`) should use it's own instance of that shared route (with id=`myFilteringRoute`), with separate internal state, bean instances, etc.
In other words, each route from Camel Context (with id=`myRoute1`, `myRoute2`, `myRoute3`) **should not use the same instance of shared route** (with id=`myFilteringRoute`), but should has its **own completely separate instances** (with completely separated internal states and bean instances )
Please consider that my shared route (with id=`myFilteringRoute`) may use more beans, which may have various scopes (`singleton`, `prototype`, `request` etc.).
My questions are: Can I achieve this goal using single Camel Context, or do I need to place my routes (with id=`myRoute1`, `myRoute2`, `myRoute3`) in separate Camel Contexts? What is the best solution of my problem?
Is there important performance impact If I use more than one Camel Contexts, and each context uses beans to communicate with ActiveMQ (`org.apache.activemq.camel.component.ActiveMQComponent`), or other beans that consume internal or system resources?
Or maybe it's better to resolve my problem by using Java DSL instead of Spring DSL?
Thank You. | I got another instance of **ProcMon** running and filtered results to show only *IISExpress* results (Since this is the one which is giving me error).
Then I compiled and launched my application from the IDE and waited for the error to come. After I got the error, I filtered the results by "*Access Denied*".
Usually I filtered the results to look for system.web.dll, but this time i decided to ignore it.
I found that the only file which was throwing access denied was: "**C:\Users\1roj1\Documents\IISExpress\config\aspnet.config**" (Where 1roj1 is my user account).
I gave my impersonate user full access to this file and voila everything worked! |
227207 | I am trying to use gcm notification. My server code is working fine and I am getting success as acknowledgment.
The problem is notification is getting sent properly :
1) In most of devices notification is received instantaneously.
Tested on google nexus,sony phones.
2) Other devices are also receiving notification but after several hours. Yes, **hours**. Tested on Karbonn, Micromax some phones.
*Note:*
All the devices are connected to the same wifi so network connectivity not an issue . Using php at server side;
There are several unanswered questions regarding this topic . I am hereby listing some of them:
[gcm notification is not working on some devices like micromax](https://stackoverflow.com/questions/29619831/gcm-notification-is-not-working-on-some-devices-like-micromax)
[One device doesn't receive push notifications (GCM)](https://stackoverflow.com/questions/26132407/one-device-doesnt-receive-push-notifications-gcm)
[Push notifications delay with GCM](https://stackoverflow.com/questions/22741114/push-notifications-delay-with-gcm)
Anyone else having similar problem attach your question too.
*Failed trials of rectification:*
I have also made changes to code after going through several questions in which the developers found their solution like
removing this line of code from `onHandleIntent()`
```
GcmBroadcastReceiver.completeWakefulIntent(intent);
```
Or changing `delay_while_ideal` value to `true/false` in server code.
Or separately mentioning receiver and registration intent-filter
```
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.nothing.gcmclient" />
</intent-filter>
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.nothing.gcmclient" />
</intent-filter>
```
*Code:
Android.manifest*
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nothing.gcmclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.nothing.gcmclient.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.nothing.gcmclient.permission.C2D_MESSAGE" />
<uses-permission android:name="com.nothing.gcmclient.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="ANDROID.PERMISSION.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".RegisterActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name" >
</activity>
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.nothing.gcmclient" />
</intent-filter>
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.nothing.gcmclient" />
</intent-filter>
</receiver>
<service android:name=".GCMNotificationIntentService"></service>
<activity
android:name=".ChatActivity"
android:label="@string/title_activity_chat" >
</activity>
<activity
android:name=".RegisterScreen"
android:label="@string/title_activity_register_screen" >
</activity>
<activity
android:name=".RegisterChatButtonActivity"
android:label="@string/title_activity_register_chat_button" >
</activity>
<activity
android:name=".ChatHistory"
android:label="@string/title_activity_chat_history" >
</activity>
<activity
android:name=".MessageScreen"
android:label="@string/title_activity_message_screen" >
</activity>
</application>
</manifest>
```
*Code: GCMNotificationIntentService.java*
```
public class GCMNotificationIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCMNotificationIntentService";
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: "
+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
String sender=extras.get(Config.SENDER).toString().toLowerCase();
String message=extras.get(Config.MESSAGE_KEY).toString();
if(!RegisterActivity.appVisible==true)
{
sendNotification("New message Received from "+ extras.get(Config.SENDER));
}
}
}
//GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, ChatHistory.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.gcm_cloud)
.setContentTitle("New Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
}
```
Experts please look into the problem and suggest the appropriate cause and solution. My app would be of no use if it works only for certain phones.If you need any more file in our application kindly inform.
PS- Kindly read the entire question and then post your comments or answers or mark duplicate if necessary. | * GCM works through Google Play Services
* Devices connect to Google Play Services through **TCP on port 5228**
* Devices should use port 443 as fallback if port 5228 is blocked, but apparently they just don't use the fallback sometimes (happened to multiple of my devices)
* Device sends a **heartbeat packet to Google Play Services** every 28 minutes on mobile and 15 minutes on wifi
* You can check the connection state, heartbeat interval, connection address and port, etc. dialing `*#*#426#*#*` on a device
**How to fix common issues when devices don't connect to Google Play Services on wifi or lose connection frequently**:
1. **Open port 5228**
2. **Configure your routers, so they don't kill inactive tcp connections before waiting at least 15 minutes**
See [this post on Google Product Forums](https://productforums.google.com/forum/#!category-topic/nexus/connecting-to-networks-and-devices/fslYqYrULto) for more information. |
227291 | I'm running a script that returns HTML in the following format into a variable (i.e var results;)
```
var results = titleResults[0];
return results;
***RETURNS the below***
<h2>
<a href="https://www.southwest.com/about/southwest/index.html"><b>About Southwest</b></a>
</h2>
```
How can I parse out only the 'southwest.com' into another variable? | [EDIT] Full apps script code here:
```
var html = '<h2><a href="https://www.southwest.com/about/southwest/index.html"><b>About Southwest</b></a></h2>';
var doc = XmlService.parse(html);
var root = doc.getRootElement();
var children = root.getDescendants();
children.forEach(function(ch){
var chelm = ch.asElement();
if(chelm && chelm.getAttribute('href'))
{
var href = chelm.getAttribute('href');
var url = href.getValue();
Logger.log(url);
var hostname;
if (url.indexOf("//") > -1)
hostname = url.split('/')[2];
else
hostname = url.split('/')[0];
hostname = hostname.split('://').pop();
hostname = hostname.split('www.').pop();
hostname = hostname.split('?')[0];
Logger.log(hostname);
}
});
```
You can use XmlService.parse in apps script and get the link node & href attribute:
<https://sites.google.com/site/scriptsexamples/learn-by-example/parsing-html>
From the href attribute, you can extract the domain:
```
var hostname;
if (url.indexOf("//") > -1)
hostname = url.split('/')[2];
else
hostname = url.split('/')[0];
hostname = hostname.split('://').pop();
hostname = hostname.split('www.').pop();
hostname = hostname.split('?')[0];
``` |
227367 | I'm using bash to read a file and after doing opeation on particular line ,i need to delete that line from input file.
Can you please suggest some way to do so using sed or any other way ?
i've tried using sed command like this :-
```
#!/bin/sh
file=/Volumes/workplace/GeneratedRules.ion
while read line;do
printf "%s\n" "$line"
sed '1d' $file
done <$file
```
my aim in this program is to read one line and then deleting it.
Input :-
```
AllIsWell
LetsHopeForBest
YouCanMakeIt
```
but the output , i got is more weird than i thought.
output :-
```
AllIsWell
LetsHopeForBest
YouCanMakeIt
LetsHopeForBest
LetsHopeForBest
YouCanMakeIt
YouCanMakeIt
LetsHopeForBest
YouCanMakeIt
```
but i need to output as :
```
AllIsWell
LetsHopeForBest
YouCanMakeIt
```
as i want to delete line after reading it.
NOTE :- i have simplified my problem here . The actual usecase is :-
***I need to perform some bunch of operation on line except reading that and the input file is too long and my operation got fails in some way in between .So i want those lines which i have read to be deleted so that if i start the process again , it will not start from the beginning but at the point where it got stuck.***
please help. | You effectively said you want your process to be [restartable](https://en.wikipedia.org/wiki/Application_checkpointing). Depending upon how you define the successful completion of an iteration of your while loop, you should store a line number in a separate file, `x`, that indicates how many lines you have successfully processed. If the file doesn't exist, then assume you would start reading at line 1.
Otherwise, you would get the content of `x` into variable `n` and then you would start reading `$file` at line $n + 1.
How you start reading at a particular line depends on constraints we don't know yet.
One way you could do it is to use `sed` to put lines $n + 1 into a temporary file, remove `$file` and then move the temporary file to `$file` before your while loop begins.
There are other solutions but each one might not elegantly satisfy your constraints.
But you'll want to carefully consider what happens if some other process is modifying the content of `$file` and when it is changing the content. If it only changes the content before or after your bash script is running, then you're probably ok to continue down this path. Otherwise, you have a synchronization problem to solve. |
227395 | I'm using PHP and PHPMyAdmin to create a small profile site.
I'm giving members an ID number, based on which is the biggest number currently in the database, +1
I did 25 tests before I got the PHP script where I wanted it to be.
I then deleted those 25 entries using PHPMyAdmin.
But now, when my PHP code does this:
```
function getLatestID() {
$query = "SELECT max(member_id) FROM members";
$result = @mysql_query($query) or showError("unable to query database for user information");
if (!($record = mysql_fetch_array($result))) return null;
return $record[0];
}
```
I get the wrong number.
Test scenario: the database table holds 3 entries, with ID's 1, 2 and 3.
I start a debugging session and put a breakpoint on the return `$record[0]`.
I check its contents and instead of 3, which is the biggest number, it's 28.
As in 25+3=28, the 25 entries that I allready deleted...
Does anybody know what's causing this and how I can fix it? | It's probably because you have auto\_increment set and the query is returning the highest id. When you deleted the other records, you probably didn't reset the auto increment count. |
227455 | I'm working and on a large C++ project and making it compile with clang would be painful, so I'm stuck with GCC.
I want to use the nice `-fsanitize=leak` flag that I already used with clang on a previous job, but it does not seem to work.
I made a very simple example to test it:
```
#include <stdlib.h>
void FooBar() {
malloc(7);
}
int main() {
FooBar();
return 0;
}
```
With clang it works as expected:
```
>> clang -fsanitize=leak main.cpp
>> LSAN_OPTIONS=detect_leaks=1 ./a.out
=================================================================
==18052==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 7 byte(s) in 1 object(s) allocated from:
#0 0x41dcbc (~/dev/addresssanitizertest/a.out+0x41dcbc)
#1 0x431ac3 (~/dev/addresssanitizertest/a.out+0x431ac3)
#2 0x431ae3 (~/dev/addresssanitizertest/a.out+0x431ae3)
#3 0x7f8077e71a3f (/lib/x86_64-linux-gnu/libc.so.6+0x20a3f)
SUMMARY: LeakSanitizer: 7 byte(s) leaked in 1 allocation(s).
>>
```
But with gcc it does not seem to detect anything:
```
>> gcc -fsanitize=leak main.cpp
>> LSAN_OPTIONS=detect_leaks=1 ./a.out
>>
```
Did I miss something like a nice environment variable? Did someone ever made it work with gcc?
**EDIT**: This works for instance:
```
g++ -fsanitize=address main.cpp
ASAN_OPTIONS=detect_leaks=1 ./a.out
```
But I can't do that: the perf drawback is too much. I only want leak detection. | I think this is not possible at moment (with InfluxDB 0.9). In order to compute [ratios between timeseries (fields)](https://github.com/grafana/grafana/issues/2349) you would have to be able to do either [nested queries](https://github.com/influxdata/influxdb/issues/4619) or [joins](https://docs.influxdata.com/influxdb/v0.9/concepts/08_vs_09/) which were deprecated in InfluxDB 0.9:
>
> SELECT errors\_per\_minute.value / pages\_per\_minute.value FROM errors\_per\_minute INNER JOIN pages\_per\_minute. In InfluxDB 0.9 neither the MERGE nor JOIN operations are supported.
>
>
>
However you could avoid such queries if you report values already as percentage from collectd (from version 5.5 it supports reporting CPU as percentage).
This is a simple bash `exec` script for computing percentage of cpu, memory and disk usage:
```
#!/bin/bash
# a collectd script reporting resources usage as percentage
HOSTNAME="${COLLECTD_HOSTNAME:-`hostname -f`}"
INTERVAL="${COLLECTD_INTERVAL:-10}"
# delay for measuring CPU
DELAY=${1:-1}
# source: http://codereview.stackexchange.com/questions/62425/using-proc-stat-to-calculate-cpu-usage
function getstat() {
grep 'cpu ' /proc/stat | sed -e 's/ */x/g' -e 's/^cpux//'
}
function extract() {
echo $1 | cut -d 'x' -f $2
}
function change() {
local e=$(extract $ENDSTAT $1)
local b=$(extract $STARTSTAT $1)
local diff=$(( $e - $b ))
echo $diff
}
while sleep "$INTERVAL"
do
#Record the start statistics
STARTSTAT=$(getstat)
sleep $DELAY
#Record the end statistics
ENDSTAT=$(getstat)
#http://www.mjmwired.net/kernel/Documentation/filesystems/proc.txt#1236
#echo "From $STARTSTAT"
#echo "TO $ENDSTAT"
# usr nice sys idle iowait irq guest
#From 177834 168085 1276260 3584351494 144468 154895 0 0 0 0
#TO 177834 168085 1276261 3584351895 144468 154895 0 0 0 0
USR=$(change 1)
NICE=$(change 2)
SYS=$(change 3)
IDLE=$(change 4)
IOW=$(change 5)
#echo USR $USR SYS $SYS IDLE $IDLE IOW $IOW
ACTIVE=$(( $USR + $SYS + $IOW + $NICE))
TOTAL=$(($ACTIVE + $IDLE))
PCT=$(( $ACTIVE * 100 / $TOTAL ))
#echo "BUSY $ACTIVE TOTAL $TOTAL $PCT %"
date=$(date +%s)
# percentage of used CPU
echo "PUTVAL $HOSTNAME/cpu/gauge-all_pct interval=$INTERVAL $date:$PCT"
# percentage of used memory
mem_used=$(free | awk 'FNR == 3 {print $3/($3+$4)*100}')
echo "PUTVAL $HOSTNAME/memory/gauge-mem_used interval=$INTERVAL $date:$mem_used"
# percentage of used disk
disk_used=$(df -hl | grep 'rootfs' | awk '{print substr($5, 0, length($5))}')
echo "PUTVAL $HOSTNAME/df/gauge-used_pct interval=$INTERVAL $date:$disk_used"
done
```
It would be probably more efficient to write this as Python plugin. Anyway, then you can query memory usage:
```
SELECT mean("value") FROM "memory_value" WHERE "type" = 'gauge' AND $timeFilter GROUP BY time($interval), "host"
``` |
227599 | I am working on an android application using RSA encryption.
I can get from my server, my private key and my friends public key.
Private key are like this:
```
{"n":"...","d":"...","p":"...","q":"...","dmp1":"...","dmq1":"...","coeff":"..."} (jsbn json format)
modulus => n
public exponent => e
private exponent => d
prime1 => p
prime2 => q
exponent1 => dmp1
exponent2 => dmq1
coefficient => coeff
```
With this key, I need to decrypt messages received from my server and already crypted by a javascript library (SJCL).
I also need to crypt messages in order to be able to be decrypt them with the javascrypt library.
For now I have done this:
```
public static String decrypt (String data, String stringKey) throws Exception {
JSONObject jsonKey = new JSONObject(stringKey);
BigInteger n = new BigInteger(Base64.decode(jsonKey.getString("n"), Base64.DEFAULT));
BigInteger e = new BigInteger("10001");
BigInteger d = new BigInteger(Base64.decode(jsonKey.getString("d"), Base64.DEFAULT));
BigInteger p = new BigInteger(Base64.decode(jsonKey.getString("p"), Base64.DEFAULT));
BigInteger q = new BigInteger(Base64.decode(jsonKey.getString("q"), Base64.DEFAULT));
BigInteger dmp1 = new BigInteger(Base64.decode(jsonKey.getString("dmp1"), Base64.DEFAULT));
BigInteger dmq1 = new BigInteger(Base64.decode(jsonKey.getString("dmq1"), Base64.DEFAULT));
BigInteger coeff = new BigInteger(Base64.decode(jsonKey.getString("coeff"), Base64.DEFAULT));
KeySpec privateKeySpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, dmp1, dmq1, coeff);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dec = cipher.doFinal(data.getBytes());
return new String(Base64.decode(dec, Base64.DEFAULT));
}
```
Now I get this:
>
> javax.crypto.IllegalBlockSizeException: input must be under 96 bytes
>
>
> | change isset to !empty, and remove the else like suggested earlier.
```
if(!empty($_POST['email_address']) {
//do stuff
}
``` |
227803 | href # is not appending to end of URL
I have written the html page on which one of the anchor tag has href "#". Whenever I am clicking on it, # is not appending at the end of URL path in browser. Same functionality is working in different websites. Please suggest..
```
<li class="nav-item d-md-down-none">
<a class="nav-link" href="#">
<i class="icon-location-pin"></i>
</a>
</li>
```
My current url is `"http://localhost:8080/add/AddDocument.html"`
After clicking on the link i should get `"http://localhost:8080/add/AddDocument.html#"`
But i am getting this `"http://localhost:8080/add/#"` | This issue is solved.
There is `<base href=”/”>` tag present in my html which was loading alternative html link while clicking on `href="#"`.
Thanks for all your help. |
227850 | I am having hard time filtering using the checkboxes in the d3 graph. Here I have five checkboxes and I have to filter the particular data depends upon the checkboxes value.
HTML
```
<div id="company"
<ul id='BestBrands'>
<label class="checkbox">
<input class="select-all" type="checkbox" id="brandAll" name="bands" value="M&B"
onclick="selectMainBrandALL('brandAll');">
Select All</label>
<label class="checkbox">
<input type="checkbox" id="TCS" name="TCS"
>
TCS</label>
<label class="checkbox">
<input id="CTS" type="checkbox" name="CTS" " >
CTS </label>
<label class="checkbox">
<input type="checkbox" id="info" name="info" >
Info</label>
<label
</ul>
</div>
```
Here Is the D3 scatterplot code that generates the chart. I am using Rickshaw framework here..
```
v
ar nodes = graph.vis.selectAll("path")
.data(series.stack.filter( function(d) { return d.y !== null } ))
.enter().append("svg:circle")
.attr("cx", function(d) { return graph.x(d.x) })
.attr("cy", function(d) { return graph.y(d.y) })
.attr("fill-opacity", 1.0)
// .attr("render-order", 1)
.attr("r", function(d) { return ("r" in d) ? d.r : graph.renderer.dotSize});
```
If I have to filter the data depends upon the data I can do it like
```
.filter(function(d) {
return d.x < 100;
});
```
I have done this
```
var check =graph.vis.selectAll(".ck input").on("change", function () {
console.log(this.name)
var selected = this.name,
display = this.checked ? "inline" : "none";
graph.vis.selectAll("path")
series.stack.filter( function(series) { return d.name == selected; } )
.attr("display", display);
});
```
But its not working.. please help me out... | See here for a very similar question and answer: [d3 map with checkbox filtering](https://stackoverflow.com/questions/15044385/d3-map-with-checkbox-filtering)
I think you should start by appending the circles in your scatterplot to a "dot" class. Like so:
```
svg.selectAll(".dot")
.data(data)
.enter().append("circle")...
```
see here for example: <http://www.ryansloan.org/d3samples/scatterplot.html>
Then, assuming your data has some property "name" that you are trying to filter by, do something like:
```
d3.selectAll(".input class id").on("change", function () {
var selected = this.name,
display = this.checked ? "inline" : "none";
svg.selectAll(".dot")
.filter(function(d) { return d.name == selected; })
.attr("display", display);
});
``` |
228139 | So this code runs, but it's firing the callback in .flatmap 5 times:
```
var i = 0;
const values = {};
return this.obsClient.take(5)
.flatMap(v => {
const time = Date.now();
values[i] = {time: time, count: v.clientCount};
console.log('values => ', values);
i++;
return Rx.Observable.timer(100)
});
```
"values => x" will get logged 5 times.
I thought maybe if I did the following, it would to accumulate all 5 pieces of data before firing the flatMap callback:
```
var i = 0;
const values = {};
return this.obsClient.take(5).takeLast(5)
.flatMap(v => {
const time = Date.now();
values[i] = {time: time, count: v.clientCount};
console.log('values => ', values);
i++;
return Rx.Observable.timer(100)
});
```
but it still logs "values => x" 5 times. *How can I accumulate the data, and pass all the data to the callback and avoid firing the callback 5 times?* | **Types of Routing in Laravel**
There are some Routing methods in Laravel, There are
**1. Basic GET Route**
`GET` is the method which is used to retrieve a resource. In this example, we are simply getting the user route requirements then return the message to him.
```
Route::get('/home', function() { return 'This is Home'; });
```
**2. Basic POST Route**
To make a `POST` request, you can simply use the post(); method, that means when your are submitting a Form using `action="myForm" method="POST"`, then you want to catch the `POST` response using this `POST` route.
```
Route::post('/myForm', function() {return 'Your Form has posted '; });
```
**3. Registering A Route For Multiple Verbs**
Here you can retrieve `GET` request and `POST` requests in one route. `MATCH` will get that request here,
```
Route::match(array('GET', 'POST'), '/home', function() { return 'GET & POST'; });
```
**4. Any HTTP Verb**
Registering A Route Responding To Any HTTP Verb. This will catch all the request from your URL according to the parameters.
```
Route::any('/home', function() { return 'Hello World'; });
```
---
**Usage of Routing in Laravel**
When your are Using the `Route::`, Here you can manage your controller functions and views as follows,
**1. Simple Message Return**
You can return a simple message which will display in the webpage when user request that URL.
```
Route::get('/home', function(){return 'You Are Requesting Home';});
```
**2. Return a View**
You can return a View which will display in the webpage when user request that URL
```
// show a static view for the home page (app/views/home.blade.php)
Route::get('/home', function()
{
return View::make('home');
});
```
**3. Request a Controller Function**
You can call a function from the Controller when user request that URL
```
// call a index function from HomeController (app/Http/Controllers)
Route::get('/home', 'HomeController@index');
```
**4. Catch a value from URL**
You can catch a value from requested URL then pass that value to a function from Controller. Example : If you call `public/home/1452` then value 1452 will be cached and will pass to the controller
```
// call a show function from HomeController (app/Http/Controllers)
Route::get('/home/{id}', 'HomeController@show');
``` |
228255 | C/C++ would be good option to write some of the performance critical aspects of a Ruby Application. I know this is possible.
I would like to know how to add C/C++ code into Ruby code; any other language for that matter.
Are there any practical applications of this which you noticed in open source projects or else? | Look in the "Extending Ruby" section of the Pickaxe book:
<http://www.ruby-doc.org/docs/ProgrammingRuby/html/ext_ruby.html> |
228285 | SCCM Version: 2012 R2
PowerShell Version: 3
Operating System: Windows Server 2008 R2 SP1
I've written a script to create driver packs in SCCM using only signed hard drive controller (HDC) and network (NET) driver classes but I'm getting all sorts of drivers showing up in SCCM.
![problem description](https://i.stack.imgur.com/1vyB6.jpg)
I'm hoping this is not posted the wrong place as this issue will require knowledge of both SCCM and PowerShell.
Here is the script:
```
#Vars
$site = "SITENAME:"
$configMgrCmdLets = "D:\Program Files\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
$DriverPackagePath = "\\ServerName\sources\DriverPacks\PE\SignedBootDrivers"
$DriverPackageName = "Signed Boot Drivers"
$MaxQueryResults = 4000
#pre-reqs
Import-Module $configMgrCmdLets
Set-Location $site
if (get-cmSite)
{
#all good, let's proceed.
Set-CMQueryResultMaximum -Maximum $MaxQueryResults
#Does the driverpackage already exist? If not, Create it.
if (!(Get-cmDriverPackage -Name $DriverPackageName))
{
New-CMDriverPackage -Name $DriverPackageName -Path $DriverPackagePath -PackageSourceType StorageDirect
}
$drivers = Get-CMDriver | Where-Object `
{
$_.IsSuperseded -eq $false `
-and $_.IsEnabled -eq $true `
-and $_.IsHidden -eq $false `
-and $_.DriverSigned -eq $true `
-and ($_.DriverClass -eq "hdc" -or $_.DriverClass -eq "net") `
-and $_.SDMPackageXML -match "x64 Windows 8"
}
ForEach ($driver in $drivers)
{
Add-CMDriverToDriverPackage -Driver $driver -DriverPackageName $DriverPackageName
#Output the driver class so that I can verify the result is HDC or NET.
$driver.DriverClass
}
}
else
{
Write-Error -Message "Can't read Site: $site. Perhaps the SCCM CmdLets were not imported?"
}
```
As you can see at one point in the script I output the driver class so that I can manually verify the output to the driver pack and all that is output is hdc or net driver classes.
![driver class output](https://i.stack.imgur.com/DwImM.jpg) | From what I can see there is nothing wrong with your script. I am working on a similar solution but I get the same result as you. The output list looks good but when adding the drivers to a package I get all sort of other drivers no matter what I do. The only thing common to the drivers I want to add (only hdc in my case) and the rest of the of the drivers added is the source path. If you bring up the "Content Source Path" column in the console you you can see that the hdc driver has the same source path as the other drivers added. So my conclusion is that Add-CMDriverToDriverPackage adds all driver in the same location regardless of the one specified in your search string.
I think it's a flaw in the design of the cmdlet, it even says so in the description on Technet: <https://technet.microsoft.com/en-us/library/jj850173(v=sc.20).aspx> "*When a device driver is added to a driver package, Microsoft System Center 2012 Configuration Manager copies the device driver content from the driver source location to the driver package.*" |
228466 | I'm trying to generate some text in an image that will be embedded in an email.
I would like to look as much as possible as the other text in the message body; so I tried:
```
i = Image.new(500, 100)
d = Draw.new
d = d.annotate(i, 0,0,0,25,nombre){
self.font = "Arial-Regular"
self.pointsize = 12
self.text_antialias = true
}
```
but the output is awful (see [output here](http://i.imgur.com/oBK3brs.png))
I'm using Ubuntu, I've installed msttcorefonts (Arial appears on `convert -list font`). I've also tried using other fonts/font\_families and turning off `text_antialias` with the same luck
Any hints? | The problem is almost certainly not the DPI, it's that ImageMagick is doing both stroke and fill for fonts. Try `d.stroke('transparent')` on your graphics context, and then you should just see the fill, which is the actual region the font was trying to draw, rather than its outline. |
228613 | I am new to Kibana, logstash. I am trying push xml (generated as output of nunit) in logstash. I want to have the xml elements attributes, its Parents attributes and child attributes in the same row in Kibana.
However, i can get only the xml elements attribute. Parent and child attributes are not generated in the same row.
Below is the XML file Iam using:
--------------------------------
```
<test-suite type="TestFixture" name="bootAPIs" executed="True" result="Failure" success="False" time="12.811" asserts="0">
<results>
<test-case name="NunitBETests.bootAPIs.GetSeriescount" executed="True" result="Success" success="True" time="0.944" asserts="0">
<reason name="NeededforBooting">
<message />
</reason>
</test-case>
<test-case name="NunitBETests.bootAPIs.GetSeriescount" executed="True" result="Success" success="True" time="0.910" asserts="0">
<reason>
<message />
</reason>
</test-case>
<test-case name="NunitBETests.bootAPIs.GetToken" executed="True" result="Success" success="True" time="0.462" asserts="0">
<reason>
<message />
</reason>
</test-case>
</results>
</test-suite>
```
---
Below is Logstash Config File I am using:
-----------------------------------------
```
input { stdin { } }
filter {
xml {
store_xml => false
source => "message"
xpath =>
[
"//test-case/@name", "testcase",
"//test-case/@result", "res",
"//test-case/../../@name", "suitename",
"//test-case/reason/@name","reasonattr",
"//test-case/@time", "timetest"
]
}
date {
match => [ "date" , "dd-MM-yyyy HH:mm:ss" ]
timezone => "Europe/Amsterdam"
}
}
output {
elasticsearch {
action => "index"
index => "xml12"
hosts => ["localhost:9200"]
}
stdout { codec => rubydebug }
}
```
---
Result:
I am getting this output:
```
{
"message" => " <test-case name="NunitBETests.bootAPIs.GetSeriescount" executed="True" result="Success" success="True" time="0.462" asserts="0">\r",
"testcase" => [
[0] "NunitBETests.bootAPIs.GetSeriescount"
],
"res" => [
[0] "Success"
],
"host" => "DESKTOP-PC8JBMK"
}
```
However I am want to capture parent attribute of "testcase" node (that is "suitename") and child attribute of "testcase" xmlnode (that is "reasonattr") in same row.
Something like below is what i want to have:
```
{
"message" => " <test-case name="NunitBETests.bootAPIs.GetSeriescount" executed="True" result="Success" success="True" time="0.462" asserts="0">\r",
"testcase" => [
[0] "NunitBETests.bootAPIs.GetSeriescount"
],
"res" => [
[0] "Success"
],
"suitename" => [
[0] "bootAPIs"
],
"reasonattr" => [
[0] "NeededforBooting"
],
"@timestamp" => 2018-01-09T05:53:07.678Z,
"@version" => "1",
"timetest" => [
[0] "0.462"
],
"host" => "DESKTOP-PC8JBMK"
}
```
Please let me know what I am missing here. | **It depends on your needs**
If you require this number to be as random as physically possible, then yes you should use the `RNGCryptoServiceProvider()` class.
If this is just a random number for something seemingly trivial, then it's not really necessary that it uses this class. For example, if you are just trying to calculate a random number for something temporarily then it should be just fine.
For example, if you're generating a user's password, you should generate the salt using `RNGCryptoServiceProvider()` as it needs to be as secure as possible. However, if you're making a "Roll the dice" game or a "Guess the number" game, then it's much easier to just use `Random()` as it isn't a high security risk. |
228812 | i am doing a Wpf Application and i create a Control with the shape of an eye ,i put a Ellipse(eye) in a Canvas and my purpose is when the cursor of the mouse enter in the Canvas the Ellipse follow the cursor of mouse.
Do you have any suggestion how perform this task?
Thanks so much for your attention.
Cheers
EDIT
====
I have update my code in Xaml:
```
<Window Height="480" Title="Window2" Width="640" x:Class="WpfApplication5.Window2"
x:Name="Window" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<Storyboard x:Key="OnLoaded1">
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="ctrCircle"
Storyboard.TargetProperty="(UIElement.RenderTransform).( TransformGroup.Children)[3].(TranslateTransform.X)">
<EasingDoubleKeyFrame KeyTime="0:0:0.8" Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<ExponentialEase EasingMode="EaseOut" />
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="ctrCircle"
Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)">
<EasingDoubleKeyFrame KeyTime="0:0:0.8" Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<ExponentialEase EasingMode="EaseOut" />
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Style TargetType="Ellipse">
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleX="1" ScaleY="1"/>
</Setter.Value>
</Setter>
<Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
</Style>
</Window.Resources>
<Canvas MouseMove="mov" x:Name="LayoutRoot">
<Border ackground="Black" B="" Canvas.Left="178" Canvas.Top="103"
CornerRadius="250" Height="255.5" Width="290" x:Name="border_eye">
<Ellipse Fill="#FFFFC600" Height="12" HorizontalAlignment="Left"
Margin="0" RenderTransformOrigin="0.5,0.5" Stroke="{x:Null}"
VerticalAlignment="Center" Visibility="Visible" Width="12" x:Name="ctrCircle">
<Ellipse.RenderTransform>
<TransformGroup>
<ScaleTransform />
<SkewTransform />
<RotateTransform />
<TranslateTransform />
</TransformGroup>
</Ellipse.RenderTransform>
</Ellipse>
</Border>
</Canvas>
</Window>
```
and in the code behind :
```
private void mov(object sender, MouseEventArgs e)
{
System.Windows.Point pt = e.GetPosition((Canvas)sender);
Storyboard invokeStoryboard = this.Resources["OnLoaded1"] as Storyboard;
((DoubleAnimationUsingKeyFrames)invokeStoryboard.Children[0]).KeyFrames[0].Value = pt.X;
((DoubleAnimationUsingKeyFrames)invokeStoryboard.Children[1]).KeyFrames[0].Value = pt.Y;
invokeStoryboard.Begin();
}
```
now my purpose is when i move the mouse in the Canvas area(LayoutRoot) the Ellipse(ctrCircle) move only inside the Border(border\_eye) and don't overcome the area of the "border\_eye" this effect is similar an eye.
Do you have any input to work out this step?
Thanks so much
Have a nice day.
Cheers | Use MouseMove and make sure the Canvas has a Background for hit testing.
XAML:
```
<Canvas MouseMove="Canvas_MouseMove"
Background="Transparent">
<Ellipse x:Name="eye"
Width="50"
Height="20"
Fill="Blue" />
</Canvas>
```
Codebehind:
```
private void Canvas_MouseMove( object sender, System.Windows.Input.MouseEventArgs e )
{
var pos = e.GetPosition((Canvas)sender);
Canvas.SetLeft(eye, pos.X);
Canvas.SetTop(eye, pos.Y);
}
``` |
229147 | I have a cron job which parses a # of RSS feeds. It turns out it takes too long so I'm getting a HardDeadlineExceededError. I tried just creating two cron jobs, one which parses the even feeds, one which parses the odd feeds, I still get the error.
What's the best way to break up this work so it fits within a 30 second window? | I recommend using the [Task Queue](http://code.google.com/appengine/docs/java/taskqueue/overview.html) -- a task can perform any number N of sub-tasks of your choice, making sure to get close but not *too* close to the hard-deadline, then it spawns another task to continue where the spawner left off. |
229459 | I'm having trouble using `strpos` correctly. if I search for`<br />` it will find it. If I search for `<br /><br /><br />` with or without space between, it won't and using `htmlspecialchars` I can tell the string is full of it.
```
<?php
$picArray = glob('projectData/' . $data['folder'] . '/*.jpg',GLOB_BRACE);
$text = nl2br($data['definition']).'<br />';
$cutP = 0;
foreach($picArray AS $insert) {
if(strpos($text,'<br /> <br /> <br />',$cutP) !== FALSE){
$cutP = strpos($text,'<br /> <br /> <br />',$cutP)+6;
echo $cutP.'_';
$str_to_insert = '<img class="inTextImg" title="int" src="'.$insert.'" />';
$text = substr($text, 0, $cutP) . $str_to_insert . substr($text, $cutP);
}
else {
echo 'haha';
$text .= '<img class="inTextImg" title="outText!" src="'.$insert.'" />';
}
}
?>
```
Thank your for your ideas. | This is because `nl2br` keeps the original line break characters in place, just after the `'<br />'`. You need to include the line break characters in the string to search for. Since there can be a few different patterns for this it's easiest to use a regexp to match it:
```
$text = preg_replace('/(?:<br \/>\r?\n?){3}/', $str_to_insert, $text);
``` |
229652 | I'm trying to get some exchange rates through API but I do not know how to transform all this to one table like:
```
date | timestamp | base | Currency Name | Currency |
```
I need rates to expand in two columns Currency Name and Currency?
```bsh
$request = website
$X = Invoke-WebRequest $request
$JSONResult = $x | ConvertFrom-Json
$JSONResult
```
```json
{
"success": true,
"timestamp": 1519296206,
"base": "EUR",
"date": "2018-06-12",
"rates": {
"AUD": 1.566015,
"CAD": 1.560132,
"CHF": 1.154727,
"CNY": 7.827874,
"GBP": 0.882047,
"JPY": 132.360679,
"USD": 1.23396,
[...]
}
}
``` | After the conversion the value of the `rates` property of your JSON data is a custom object with the currency names as properties and the exchange rates(?) as their value. Use the intrinsic property `PSObject` of that object to enumerate the object properties and their values:
```
$JSONResult.rates.PSObject.Properties | ForEach-Object {
New-Object -Type PSObject -Property @{
'Date' = $JSONResult.date
...
'Currency Name' = $_.Name
'Currency' = $_.Value
}
}
``` |
229759 | I'm pretty new to React, I'm trying to return a JSX from a method, code as follows:
```js
import React, { useReducer } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
const formatName = (user) => {
return user.firstName + ' ' + user.lastName;
}
const getGreeting = (user) => {
if (user) {
return {greeting}
}
else {
return {forbidden}
}
}
const user = {
firstName: 'John',
lastName: 'Smith'
};
const greeting = (
<h1>Hello {formatName(user)}</h1>
);
const forbidden = (
<h1>Hello stranger!</h1>
);
const element = (
<div>{getGreeting(user)}</div>
);
ReactDOM.render(
element, document.getElementById('root')
);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
```
As you can see, `element` contains a div which I wish to render `getGreeting`, since `user == true`, it should return `greeting`, which calls the method `formatName`. However it returns an error:
```
Error: Objects are not valid as a React child (found: object with keys {greeting}). If you meant to render a collection of children, use an array instead.
```
What am I doing wrong here? | `getGreeting` should return a JSX and not an object
try this:
```
const greeting = (
<h1>Hello {formatName(user)}</h1>
);
const forbidden = (
<h1>Hello stranger!</h1>
);
const getGreeting = (user) => {
if (user) {
return greeting
}
else {
return forbidden
}
}
``` |
230185 | I tried searching but didn't get any useful information.
What does the word "Relational" mean here? Is it tables being related to each other just like the real life entities, or does it mean something else? | The word *relational* comes from <http://en.wikipedia.org/wiki/Relational_algebra> which was invented by E.F. Codd. SQL and relational databases started as an attempt to make Codd's ideas practical. |
230270 | Apologies if this has been answered elsewhere but I couldn't find anything here or online.
Does openrowset have a file size limit? I'm trying to write a stored procedure, part of which checks if certain characters exist within the file and if they do I'd have to skip to the next section of the stored procedure. So far I've simply bulk inserted the entire file into a one column table then did:
```
IF(SELECT COUNT(*) FROM #fulltable WHERE fulltable LIKE '%}%')>0 GOTO NEXTSECTION
IF(SELECT COUNT(*) FROM #fulltable WHERE fulltable LIKE '%~%')>0 GOTO NEXTSECTION
IF(SELECT COUNT(*) FROM #fulltable WHERE fulltable LIKE '%#%')>0 GOTO NEXTSECTION
```
It's reliable but very slow when dealing with large files (sometimes over 10GB). I'm thinking the below query would be quicker for large files
```
DECLARE @FILE NVARCHAR(MAX)
select @FILE = BULKCOLUMN from (
select * from openrowset(BULK N'filpath', single_clob) [a]
)a
IF(SELECT IIF(@FILE LIKE '%{%',1,0)) = 1 GOTO NEXTSECTION
IF(SELECT IIF(@FILE LIKE '%}%',1,0)) = 1 GOTO NEXTSECTION
IF(SELECT IIF(@FILE LIKE '%~%',1,0)) = 1 GOTO NEXTSECTION
IF(SELECT IIF(@FILE LIKE '%@%',1,0)) = 1 GOTO NEXTSECTION
IF(SELECT IIF(@FILE LIKE '%£%',1,0)) = 1 GOTO NEXTSECTION
```
But as I say Bulk insert is reliable and I'd hate to risk the file being truncated when using OPENROWSET if there is some sort of file size limit.
Any advice on the matter would be appreciated. | I know it's not your main question, but you mentioned slow performance. When checking if a certain character or substring exists within a larger string, you should try using CHARINDEX('x', strColumn) instead of LIKE '%x%'. This will boost your performance drastically. Using LIKE with % surrounding your search-term is very slow and costly. |
230396 | **Spring Boot Actuator** provides several **endpoints** to **monitor** an **application** as:
```
/metrics
/beans
/health
...
```
Checking the endpoints with:
```
curl http://localhost:8080/metrics
```
results in:
```
{"counter.status.200.env":1,"counter.status.200.health":1,"counter.status.200.info":2,"counter.status.200.metrics":2,"gauge.response.env":5.0,"gauge.response.health":22.0,"gauge.response.info":1.0,"gauge.response.metrics":1.0,"mem":1030144,"mem.free":56118,"processors":8,"uptime":5108095,"instance.uptime":5102906,"heap.committed":1030144,"heap.init":262144,"heap.used":974031,"heap":3728384,"threads.peak":81,"threads.daemon":21,"threads":77,"classes":8854,"classes.loaded":8860,"classes.unloaded":6,"gc.ps_scavenge.count":119,"gc.ps_scavenge.time":7223,"gc.ps_marksweep.count":12,"gc.ps_marksweep.time":17573}
```
This is **fine for machine consumption** but **hard to read** by **humans**.
I'd like to **format** (i.e. pretty print) the **JSON** output of the **Spring Boot Actuator** endpoints to make them easier to read by operations personel.
Something like:
```
{
"counter.status.200.env":1,
"counter.status.200.health":1,
"counter.status.200.info":2,
"counter.status.200.metrics":2,
"gauge.response.env":5.0,
"gauge.response.health":22.0,
"gauge.response.info":1.0,
...
}
```
I tried setting
```
http.mappers.json-pretty-print=true
```
but this setting didn't affect the Actuator output.
Is there a **configuration** to **enable pretty print** of the **Spring Boot Actuator JSON** output?
**UPDATE:**
The [official sample](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-actuator) works for me.
It's important to follow the comments from @DaveSyer: the property to set is
```
http.mappers.jsonPrettyPrint=true
```
Investigation is still under way.
In the meantime I use the the json pretty print **command line** as **workaround**:
Install jsonpp (e.g. for OS X):
```
brew install jsonpp
```
Then pipe the curl output trough jsonpp which formats the json file on the fly:
```
curl http://localhost:8080/metrics | jsonpp
```
Results in:
```
{
"counter.status.200.env": 1,
"counter.status.200.health": 1,
"counter.status.200.info": 2,
"counter.status.200.metrics": 2,
...
}
``` | For Spring Boot 1.5.1 I have in my YML file:
```
spring:
jackson:
serialization:
INDENT_OUTPUT: true
```
@BertrandRenuart answer was the closest, but by IDE did not see indent\_output as correct. |
230425 | What is the best way to allow for the adding of images and embedding of video in the body:text field of a Ruby on Rails blog.
I understand that I can use an attachment like Paperclip to add a photo to a record but I am wondering how to get images/vids into the actual body of the post. | Try [CKEditor for Rails](http://github.com/galetahub/rails-ckeditor#readme). It is new version of FCK editor with very clean HTML generator. Very easy to embed. All you need to do is replace your input(text-area) helper tag (for content) with another helper tag. Everything is described nicely in project [README](http://github.com/galetahub/rails-ckeditor#readme).
You can upload files (pictures) and use them in content directly from CKEditor. |
230478 | I'm having trouble getting Angular 2 routing to work. I am using Angular 2 and Webpack. In the Angular 2 webpack starter, I noticed they had webpack generating their html and their links, but I was hoping I would not have to webpack my html files.
Here's my app.routes.ts...
```
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from "./home/home.component";
import { ScheduleComponent } from "./schedule/schedule.component";
import { PageNotFoundComponent } from "./PageNotFoundComponent";
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'schedule', component: ScheduleComponent },
{ path: '**', component: PageNotFoundComponent }
];
export const appRoutingProviders: any[] = [
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
```
Here's my @NgModule code...
```
@NgModule({
imports: [
BrowserModule,
HttpModule,
FormsModule,
routing ],
declarations: [
AppComponent,
AppBanner,
AppLogin,
HomeComponent,
ScheduleComponent,
PageNotFoundComponent
],
bootstrap: [ AppComponent ],
providers: [
ApplicationState,
appRoutingProviders
]
})
export class AppModule { }
```
Here is the schedule component...
```
import { Component } from '@angular/core';
@Component({
template: `
<div>Schedule</div>
`
})
export class ScheduleComponent {
}
```
And here's my HTML where I tried to add my routes...
```
<a [routerLink]=" ['/schedule'] ">Schedule</a>
```
I know this is a lot of code, but here is my webpack build as well. As you can see, the webpack task does not touch my HTML pages, so this webpack code may be irrelevant...
```
module.exports = {
entry: {
'polyfills': __dirname + '/src/polyfills.ts',
'vendor': __dirname + '/src/vendor.ts',
'app': __dirname + '/src/main.ts'
},
output: {
filename: '[name].bundle.js',
path: __dirname + '/src/bundle/',
publicPath: '/',
sourceMapFilename: __dirname + '/src/bundle/[name].bundle.map.js'
},
resolve: {
extensions: ['', '.ts', '.js'],
alias: { 'rxjs': 'rxjs-es' }
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader']
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file?name=/fonts/[name].[ext]" },
{ test: /\.(woff|woff2)$/, loader:"url?prefix=font/&limit=5000&name=/fonts/[name].[ext]" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream&name=/fonts/[name].[ext]" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml&name=/fonts/[name].[ext]" }
]
},
plugins: [
new ExtractTextPlugin('css/[name].css')
]
}
```
Unfortunately, when I click on the Schedule link, I just get an error. Here's the detailed error info from zone...
```
Unhandled Promise rejection: no elements in sequence ; Zone: angular ;
Task: Promise.then ; Value: Error: no elements in sequence(…)
EmptyError: no elements in sequence
```
Any tips? What is the problem here? | Add `pathMatch: 'full'`
```
{ path: '', component: HomeComponent, pathMatch: 'full' },
```
otherwise both routes
```
{ path: '', component: HomeComponent },
{ path: 'schedule', component: ScheduleComponent },
```
match on route `/schedule` because `''` matches, but doesn't consume anything from the route and then also `'schedule'` matches. |
230545 | I would like to retrieve an ordered query result, but I need to have some specific row(s) to be in front of the list. Something like here on Stack Overflow, in the list of answers the right answer is always the first one.
Assumed I need to have the rows with IDs 1,2,3 to be the head, the rest sorted by a date field, is it possible to do something like:
```
SELECT * FROM foo ORDER BY id IN (1,2,3), created_date
```
If not what is more efficient? There will be many rows!
```
SELECT *, 0 AS head FROM foo WHERE id IN (1,2,3)
UNION
SELECT *, 1 AS head FROM foo WHERE id NOT IN (1,2,3)
ORDER BY head, created_date
```
or
```
SELECT *, IF(id IN (1,2,3), 0, 1) AS head
ORDER BY head, created_date
```
(I use MySQL now, but I'm interested in any other SQL solution.) | Your first example looks almost there to me.
```
SELECT * FROM foo ORDER BY id IN (1,2,3) DESC, created_date ASC
```
Added `DESC` because `id IN (1,2,3)` returns `1` if true or `0` if false. `1 > 0`, so ordering them in descending order gets the desired result.
Added `ASC` because I like to be explicit.
Based on your later examples, I think what you're missing is that, though it contains spaces, `field IN (list)` is a single operator that returns `0` or `1`. `IF(id IN (1,2,3), 0, 1)` is inherently redundant.
As such, you shouldn't need to use a `UNION` *or* sort manually, since MySQL makes this simpler than you even realize :) |
230548 | I'm learning react without redux, mobx or any other libraries.
The reason why I don't use redux, and so on is that someone told me that it is important to get use to react before using libraries.
I'm trying to get data from firestore and render it, but because of async, I'm stuck to render data.
I can't render because I don't get data when I render.
My react version is 16 and I practice react with firestore.
Here's my code.
I'll appreciate you whatever you give me your advice.
Thank you.
---
**CategoryButtonSet.js**
```
import React from 'react';
import CategoryButton from './CategoryButton';
import {test} from '../shared/Firebase';
export default class CategoryButtonSet extends React.Component {
categories = [];
componentDidMount() {
test().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.categories.push(doc.id).bind(this);
});
});
}
render() {
if(this.categories.length !== 0) {
console.log(this.categories);
return (
<div className="category-block">
This block is for the category button set.
{
this.categories.map(category => <CategoryButton key={category} name={category}/>)
}
</div>
);
} else {
return <div>Loading...</div>;
}
}
}
```
---
**CategoryButton.js**
```
import React from 'react';
export default (props) => {
return (
<div className="category-block__button">
Here's the category button.
<button>{props.name}</button>
</div>
);
}
``` | You are retrieving data but does not set your state, you don't have any state at all. This is why your component does not re-render after getting data. Maybe one approach could be like this (there could be better ways):
```
export default class CategoryButtonSet extends React.Component {
state = {
categories: [],
};
componentDidMount() {
test()
.then( querySnapshot => querySnapshot.map( doc => doc.id ) )
.then( data => this.setState( { categories: data } ));
}
render() {
if(this.state.categories.length) {
console.log(this.state.categories);
return (
<div className="category-block">
This block is for the category button set.
{
this.state.categories.map(category => <CategoryButton key={category} name={category}/>)
}
</div>
);
} else {
return <div>Loading...</div>;
}
}
}
``` |
230585 | My controller like this :
```
public function index(Request $request)
{
$param = $request->all();
$data = $this->itemDetailRepository->getData($param);
return view('item-detail.index', compact('param'))
->withItems(count($data)>0?$data:null);
}
```
If I debug `$data` or in laravel (`dd($data)`), the result like this :
[![enter image description here](https://i.stack.imgur.com/tmqLI.png)](https://i.stack.imgur.com/tmqLI.png)
So the array `$data` is collection and pagination like that
If I click in the attributes section, it display like this :
```
#attributes: array:5 [▼
"item_number" => "AB-0001"
"total_quantity" => "1000"
"location-a" => "500"
"location-b" => "500"
]
```
So the array data is there
In the view blade laravel like this :
```
<table>
<tr>
<th>ITEM NUMBER</th>
<th>TOTAL QUANTITY</th>
<th>LOCATION-A</th>
<th>LOCATION-B</th>
</tr>
@foreach($items as $item)
<tr>
<td>{{ $item->item_number }}</td>
<td>{{ $item->total_quantity }}</td>
<td>{{ $item['location-a'] }}</td>
<td>{{ $item['location-b'] }}</td>
</tr>
@endforeach
</table>
```
It works. But my key of the array is dynamic. The key can change
So the array can change like this :
```
#attributes: array:5 [▼
"item_number" => "AB-0001"
"total_quantity" => "500"
"location-a" => "500"
]
```
Or can change like this :
```
#attributes: array:5 [▼
"item_number" => "AB-0001"
"total_quantity" => "1500"
"location-a" => "500"
"location-b" => "500"
"location-c" => "500"
]
```
So the location is dynamic
How do I set it in the laravel view blade so that it can adjust to dynamic arrays?
**Update**
If I `echo '<pre>';print_r($data);'</pre>';die();`, the result like this :
```
Illuminate\Pagination\LengthAwarePaginator Object
(
[total:protected] => 2428
[lastPage:protected] => 1214
[items:protected] => Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\Models\ItemDetail Object
(
[table:protected] => items_details
[fillable:protected] => Array
(
[0] => item_number
[1] => quantity
...
)
[connection:protected] => mysql
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
[item_number] => AB-0001
[total_quantity] => 1000
[location-a] => 500
[location-b] => 500
)
[original:protected] => Array
(
[item_number] => AB-0001
[total_quantity] => 1000
[location-a] => 500
[location-b] => 500
)
[changes:protected] => Array
(
)
[casts:protected] => Array
(
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[appends:protected] => Array
(
)
[dispatchesEvents:protected] => Array
(
)
[observables:protected] => Array
(
)
[relations:protected] => Array
(
)
[touches:protected] => Array
(
)
[timestamps] => 1
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
)
[1] => App\Models\ItemDetail Object
(
[table:protected] => items_details
[fillable:protected] => Array
(
[0] => item_number
[1] => quantity
...
)
[connection:protected] => mysql
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
[item_number] => AB-0002
[total_quantity] => 1500
[location-a] => 1000
[location-b] => 500
)
[original:protected] => Array
(
[item_number] => AB-0002
[total_quantity] => 1500
[location-a] => 1000
[location-b] => 500
)
[changes:protected] => Array
(
)
[casts:protected] => Array
(
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[appends:protected] => Array
(
)
[dispatchesEvents:protected] => Array
(
)
[observables:protected] => Array
(
)
[relations:protected] => Array
(
)
[touches:protected] => Array
(
)
[timestamps] => 1
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
)
)
)
[perPage:protected] => 2
[currentPage:protected] => 1
[path:protected] => http://my-project.test/admin/item-detail
[query:protected] => Array
(
)
[fragment:protected] =>
[pageName:protected] => page
)
``` | Try this out:
```
@php
$counts = array_map('count', $data);
$key = array_flip($counts)[max($counts)];
@endphp
<table>
<tr>
@foreach ($data[$key] as $key => $value)
<th>{{$key}}</th>
@endforeach
</tr>
@foreach($data as $value)
<tr>
@foreach ($value as $key => $value)
<td>{{$value}}</td>
@endforeach
</tr>
@endforeach
</table>
``` |
230926 | ```
ResponseEntity<JsonNode> response = null;
//Calling POST Method
response=restTemplate.exchange(url, HttpMethod.POST,request,JsonNode.class);
restResponse.setStatusCode(response.getStatusCode());
restResponse.setHeaders(response.getHeaders());
if(response.getBody().isNull())
{
//DO SOMETHING
}
```
**Issue: Facing Null Pointer Exception**
Eventhough I am trying to handle Not Null scenario using check `response.getBody().isNull()` , but seems like this check also leads to null pointer exeception.
My assumptions : `response.getBody()` should return me JsonNode object on which I am trying to execute `isNull()` method.
I am not sure how this call again lead to Null Pointer Exception.
On Intellij It shows as `getBody()` method is `@Nullable` there are chances of Null pointer exception.
I searched online some solution says to use `response.getBody()!=null` will work. I am confused. Then what is use of `isNull()` method? | I would use [`HttpEntity#hasBody`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/HttpEntity.html#hasBody--) before retrieving the body. There is a good chance the entity doesn't have a body. It's more expressive than a `response.getBody() != null` check.
Please, don't assume that `isNull()` on an object would check that object on null. `this == null` is fundamentally wrong and never true.
```
class Body {
public boolean isNull() {
return this == null; // never makes sense
}
}
``` |
231337 | I have a view controller in Cocoa Touch that detects when the device rotates and switches between the views of the 2 view controllers it has: landscape and portrait.
I want the `UIViewControllers` in it to be able to access the `FRRRotatingViewController`, in a similar way as all `UIViewControllers` can access the `UINavigationController` they're in.
So I created a `UIViewController` subclass (`FRRViewController`) that will have a `rotatingViewController` property.
I also modified `FRRRotatingViewController`, so it takes `FRRViewControllers` instead of plain `UIViewControllers`.
Unfortunately, when I include `FRRRotatingViewController.h` in `FRRViewController.h` (and vice versa), I seem to get into a circular import issue. I don't know how to fix it. Any suggestions?
Here's the code:
```
//
// FRRViewController.h
#import <UIKit/UIKit.h>
#import "FRRRotatingViewController.h"
@interface FRRViewController : UIViewController
@end
//
// FRRRotatingViewController.h
#import <UIKit/UIKit.h>
#import "FRRViewController.h"
@class FRRRotatingViewController;
@protocol FRRRotatingViewControllerDelegate
-(void) FRRRotatingViewControllerWillSwitchToLandscapeView: (FRRRotatingViewController *) sender;
-(void) FRRRotatingViewControllerWillSwitchToPortraitView: (FRRRotatingViewController *) sender;
@end
@interface FRRRotatingViewController : FRRViewController {
// This is where I get the error:Cannot find interface declaration for
// 'FRRViewController', superclass of 'FRRRotatingViewController'; did you
// mean 'UIViewController'?
}
@property (strong) UIViewController *landscapeViewController;
@property (strong) UIViewController *portraitViewController;
@property (unsafe_unretained) id<FRRRotatingViewControllerDelegate> delegate;
-(FRRRotatingViewController *) initWithLandscapeViewController: (UIViewController *) landscape andPortraitViewController: (UIViewController *) portrait;
-(void) deviceDidRotate: (NSNotification *) aNotification;
@end
``` | You can use forward declarations for classes and protocols in headers in most situations to avoid circular import issues, except in the case of inheritance. In `FRRViewController.h`, instead of importing `FRRRotatingViewController.h`, can you not make a forward declaration?
```
@class FRRRotatingViewController;
``` |
231873 | I am having issues with my combo box. I am trying to set the selection at runtime, but the binding is not working.
```
public ICLINKDesignatorCandidate SelectedDesignator
SelectedDesignator.Designator = somevalue;
...
<ComboBox Grid.Row="4" DisplayMemberPath="DisplayName"
SelectedValuePath="{Binding Path=DesignatorId}"
SelectedItem="{Binding Path=SelectedDesignator}"
ItemsSource="{Binding DesignatorList}" />
```
So I am getting a binding error:
>
> BindingExpression path error: 'DesignatorId' property not found on 'object' ''TCard4312VM' (HashCode=47413204)'. BindingExpression:Path=DesignatorId; DataItem='TCard4312VM' (HashCode=47413204); target element is 'ComboBox' (Name=''); target property is 'SelectedValuePath' (type 'String')
>
>
>
**So WHY is it looking at the parent view model instead of the CLINKDesignatorCandidate object?**
So the SelectedValuePath is looking at the parent view model INSTEAD of the property on an element in the DesignatorList. **The weird thing is, when my DesignatorList was a list of type "DESIGNATOR"(which was an entity framework entity), this worked perfectly fine, and there was no binding issues.**
DisplayName is obviously working properly, so I don't know why DesignatorID isn't. Here is the class:
```
public class CLINKDesignatorCandidate : ICLINKDesignatorCandidate
{
public CLINKDesignatorCandidate()
{
}
public int DesignatorID { get; set; }
public DESIGNATOR Designator
{
get;
set;
}
public string DisplayName
{
get;
set;
}
}
```
Here is the code that USED to work when I was binding to a list of type DESIGNATOR(entity framework entity):
```
<ComboBox Grid.Row="3" IsEditable="True"
DisplayMemberPath="DesignatorName"
SelectedValuePath="{Binding Id}"
SelectedItem="{Binding SelectedDesignator}"
ItemsSource="{Binding DesignatorList}" />
```
This worked perfectly fine and I never had any binding issues where it tried to look for "Id" in the parent view model.
I am setting the view model in code behind as follows:
```
public New4312(IEquipment4312VM vm)
: this()
{
InitializeComponent();
this.DataContext = vm;
}
```
I am using a DataTemplate in a resource dictionary for the combo box:
```
<DataTemplate x:Key="resTCard4312MIP">
<Button Tag="{Binding}" >
<Grid DataContext="{Binding}">
<telerik:Tile Width="100" Background="Purple">
<ComboBox Grid.Row="4" IsEditable="True"
DisplayMemberPath="DisplayName"
SelectedValuePath="{Binding Path=DesignatorId}"
SelectedValue="{Binding Path=SelectedDesignator.DesignatorID}"
SelectedItem="{Binding Path=SelectedDesignator}"
ItemsSource="{Binding DesignatorList}" />
</Grid>
</telerik:Tile>
etc...
```
**Keep in mind all of this code worked when my DesignatorList was a list of entites instead of a custom class.**
Thanks for any assistance. I hope I have explained the issue well enough. | DesignatorId
is not the same as
DesignatorID
Property names are case sensitive
The XAML does not match the property name |
232078 | I'm trying to join tables and load data with a specific value from a Textbox but It's giving the following error:
"An exception of type 'System.NullReferenceException' occurred in Boxing.exe but was not handled in user code
Additional information: Object reference not set to an instance of an object."
My code:
```
Dim Joinloin As New MySqlCommand("SELECT boxno, specie, netweight, producttype, loin FROM loins, boxing WHERE loins.code = boxing.loin AND type = '" & Label9.text & "' ORDER BY loincode", conn.getConnection)
```
I tried to run without the "type = '" & Label9.text & "'" and works perfectly. | You could use a map to achieve this
See the snippet below
```js
function removeDuplicate(arrayOfObject){
let store = new Map()
return arrayOfObject.filter(obj=>{
// If the item exist in the store already return false and do not add it to the new array
if(store.get(obj.name) === obj.customer_id ){
return false
}
// If other wise, add it and return true
store.set(obj.name, obj.customer_id)
return true
})
}
``` |
232288 | I've been doing the Weather tutorial on [The New Boston](http://www.youtube.com/watch?v=Z1rtldBTzCE&feature=edu&list=PL2F07DBCDCC01493A&noredirect=1)
In logcat I see the following error : error opening trace file: No such file or directory(2).
The emulator can run the program but when I type "stad" in the upper edittext-box it doesn't return anything from the URL. Can you tell me what Im doing wrong please ? Here are my three classes and the XML file.
```
package com.example.weatherxml;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
static final String baseURL = "http://api.yr.no/weatherapi/seaapproachforecast/1.0/?location=";
TextView tv;
EditText city;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.activate);
tv = (TextView)findViewById(R.id.textView1);
city = (EditText)findViewById(R.id.city);
//state = (EditText)findViewById(R.id.state);
b.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
String c = city.getText().toString();
//String s = state.getText().toString();
StringBuilder URL = new StringBuilder(baseURL);
URL.append(c);
String fullUrl = URL.toString();
try{
URL website = new URL(fullUrl);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
String information = doingWork.getInformation();
tv.setText(information);
}catch (Exception e){
tv.setText("error");
}
}
}
package com.example.weatherxml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class HandlingXMLStuff extends DefaultHandler {
private XMLDataCollected info = new XMLDataCollected();
public String getInformation(){
return info.dataToString();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equals("location")){
String city = attributes.getValue("name");
info.setCity(city);
}else if (localName.equals("windSpeed")){
String t = attributes.getValue("mps");
int temp = Integer.parseInt(t);
info.setTemp(temp);
}
}
}
package com.example.weatherxml;
public class XMLDataCollected {
int temp = 0;
String city = null;
public void setCity(String c){
city = c;
}
public void setTemp(int t){
temp = t;
}
public String dataToString(){
return "In " + city + " the Current windspeed is " + temp + "mps ";
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<EditText
android:id="@+id/city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"
android:ems="10"
android:inputType="text"
android:text="" />
<EditText
android:id="@+id/state"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/city"
android:layout_gravity="fill_horizontal"
android:ems="10"
android:inputType="text"
android:text="" />
<Button
android:id="@+id/activate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/textView1"
android:layout_alignParentLeft="true"
android:layout_marginBottom="34dp"
android:text="Generate"
tools:context=".MainActivity" />
</RelativeLayout>
``` | The easiest thing to do here is to write a regular expression to capture the text, then parse out the captures to see what you got. To start, lets assume you have your test bench:
```
$tests = array(
'Genesis 1:1' => 'Genesis Chapter 1, Verse 1',
'1 Kings 2:5' => '1 Kings Chapter 2, Verse 5',
'Job 3' => 'Job Chapter 3',
'Romans 8:1-7' => 'Romans Chapter 8, Verses 1 to 7',
'1 John 5:6-11' => '1 John Chapter 5, Verses 6 to 11'
);
```
So, you have, from left to right:
1. A book name, optionally prefixed with a number
2. A chapter number
3. A verse number, optional, optionally followed by a range.
So, we can write a regex to match all of those cases:
```
((?:\d+\s)?\w+)\s+(\d+)(?::(\d+(?:-\d+)?))?
```
And now see what we get back from the regex:
```
foreach( $tests as $test => $answer) {
// Match the regex against the test case
preg_match( $regex, $test, $match);
// Ignore the first entry, the 2nd and 3rd entries hold the book and chapter
list( , $book, $chapter) = array_map( 'trim', $match);
$output = "$book Chapter $chapter";
// If the fourth match exists, we have a verse entry
if( isset( $match[3])) {
// If there is no dash, it's a single verse
if( strpos( $match[3], '-') === false) {
$output .= ", Verse " . $match[3];
} else {
// Otherwise it's a range of verses
list( $start, $end) = explode( '-', $match[3]);
$output .= ", Verses $start to $end";
}
}
// Here $output matches the value in $answer from our test cases
echo $answer . "\n" . $output . "\n\n";
}
```
You can see it working in [this demo](http://viper-7.com/EJihDl). |
232459 | I have to open different Modals based on the onClick event on IDs using same Function. I'm using If condition to check, but it is always taking the first condition to be true. Please help.
```
//html
<div id="Remote-Parking" class="element parking" onclick="modalFunction()">Remote-Parking</div>
<div id="Emergency-Braking" class="element collision-detection" onclick="modalFunction()">Emergency-Braking</div>
//javascript
function modalFunction() {
if (document.getElementById('Emergency-Braking').onclick) {
document.getElementById('Popup-Emergency-Braking').style.display="block";
}
if (document.getElementById('Remote-Parking').onclick) {
document.getElementById('Popup-Remote-Parking').style.display="block";
}
}
``` | In the way you have asked the questioned, my answer is following. Hope it will help you
```html
<div id="Remote-Parking" class="element parking" onclick="modalFunction( this.id )">Remote-Parking</div>
<div id="Emergency-Braking" class="element collision-detection" onclick="modalFunction( this.id )">Emergency-Braking</div>
<script>
function modalFunction( id ) {
if ( id == 'Remote-Parking') {
//document.getElementById('Popup-Emergency-Braking').style.display="block";
console.log('IF');
} else if ( id == 'Emergency-Braking' ){
//document.getElementById('Popup-Remote-Parking').style.display="block";
console.log('ELSE');
} else {
// in case id didn't find
// do something;
}
}
</script>
``` |
232470 | I'm having some trouble trying to make a simple view background within a method like:
```
self.view.backgroundColor=[UIColor redColor];
```
It works on the "- (void)viewDidLoad" thing, but not on mine.
Heres the .m:
```
#import "DetailView.h"
#import "MainViewController.h"
@interface DetailView ()
@end
@implementation DetailView
static DetailView *_sharedInstance;
MainViewController *mainView;
+ (DetailView *) sharedInstance
{
if (!_sharedInstance)
{
_sharedInstance = [[DetailView alloc] init];
}
return _sharedInstance;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
mainView = [MainViewController sharedInstance];
self.view.backgroundColor=[UIColor redColor]; //Works here! D:
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)createOption:(CGRect)pos Valor1:(NSString *)valor1 Valor2:(NSString *)valor2{
self.view.backgroundColor=[UIColor redColor]; //Doesn't work here :(
}
@end
```
and here's my .h:
```
#import <UIKit/UIKit.h>
@interface DetailView : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *controlVar;
+ (DetailView *) sharedInstance;
-(void)createOption:(CGRect)pos Valor1:(NSString *)valor1 Valor2:(NSString *)valor2;
@end
```
Edit:
Here's where I'm calling the 'createOption' (on viewDidLoad of the another class):
```
DetailView *detailView = [DetailView sharedInstance];
[detailView createOption:CGRectMake(0, 0, 50, 50) Valor1:@"Teste1" Valor2:@"Teste2"];
```
What am i missing here and how can i fix it? | The way I understand it right now is that Node-space is local to that node, and World-space is global space (but not necessarily screen-space, because of 3D cameras or whatever).
The so if you want to get a position of one node's position relative to another, you first convert that node's position to world-space, using it's parent, then using the other target parent's convertToNodeSpace.
So if you want the globalized position of a node,
```
Vec2 node_space_pos = my_node->getPosition(); //this is the node's node-space position
Vec2 world_space_pos = my_node->getParent()->convertToWorldSpace(node_space);
```
then in the root scene or whatever is relevant to you, you'd take the world-space/universal coords and convert it to the root node's local-space:
```
Vec2 root_local_pos = root_scene->convertToNodeSpace(world_space_pos);
my_node->removeFromParent();
root_scene->addChild(my_node);
my_node->setPosition(root_local_pos);
```
Now `my_node` is still in the absolute same position on screen, but now it's a child of the root scene instead of wherever else in the graph it was before. |
232497 | I'm new to python and continuously learning to build better codes in python. I have two lists; one with indexes stored in x variable, where the indexes in the x represents index of tuples in list named bb with string ('IN') and surrounded on both sides at least with one tuple containing 'NN'.
What i'm trying to get from the below code is, From every index mentioned in x in bb, how many continuous strings starting with 'NN' are present on both sides of the string tuple in bb list.
I tried the below code, but the code isn't efficient enough. Anybody please help me in making the code efficient.
```
bb = [('The', 'RB'),
('company', 'NN'),
('whose', 'NNS'),
('stock', 'IN'),
('has', 'NNP'),
('been', 'NNS'),
('on', 'NNP'),
('tear', 'VBJ'),
('this', 'VB'),
('week', 'NNS'),
('already', 'NN'),
('sells', 'IN'),
('its', 'NNP'),
('graphics', 'NNS'),
('processing', 'VB'),
('units', 'VBJ'),
('biggest', 'NNS'),
('cloud', 'NN'),
('companies', 'IN'),
('just', 'NNP'),
('that', 'IN')]
def solvr(bb):
x = []
for i in range(len(bb)-1):
if bb[i][1] == 'IN':
if 'NN' in (bb[i-1][1]) and 'NN' in (bb[i+1][1]):
x.append(i)
#===============================
for i in range(len(bb)-1):
if i in x:
k=[]
front = bb[i+1:]
v = 0-i
back = bb[:-v]
#======================
for i in back:
if 'NN' in i[1]:
k.append(i[0])
[[] for i in k]
#================================
for i, j in enumerate(front):
if front[i][1][:2] == 'NN':
k.append(front[i][0])
else:
break
return(k)
>> solvr(bb)
output:
['company',
'whose',
'has',
'been',
'on',
'week',
'already',
'its',
'graphics',
'biggest',
'cloud',
'just']
```
My expectation from code is to get each iteration result in new list with also 'IN' string included in every list.
```
[['company', 'whose', 'stock', 'has', 'been', 'on'],
['week', 'already', 'sells', 'its', 'graphics'],
['biggest', 'cloud', 'companies', 'just']]
```
Would be thankful if someone provides any changes to my code. | This seems like a good problem for [`itertools.groupby`](https://docs.python.org/2/library/itertools.html#itertools.groupby) which groups contiguous elements of a list together based on whether each element is true or not according to some condition that you define.
In your case you can use the following:
```
groups = itertools.groupby(bb, lambda x: x[1][:2] in ['IN', 'NN'])
result = [list(b) for a,b in groups if a]
result = [[w[0] for w in b] for b in result if 'IN' in [w[1] for w in b]]
print(result)
[['company', 'whose', 'stock', 'has', 'been', 'on'],
['week', 'already', 'sells', 'its', 'graphics'],
['biggest', 'cloud', 'companies', 'just', 'that']]
```
This works because groups splits your original `bb` list into sublists every time the condition (that the second element is 'IN' or starts with 'NN') goes from false to true (or vice versa). If we display groups you can see how it is split:
```
groups = itertools.groupby(bb, lambda x: x[1][:2] in ['IN', 'NN'])
print([(a,list(b)) for a,b in groups])
[(False, [('The', 'RB')]),
(True,
[('company', 'NN'),
('whose', 'NNS'),
('stock', 'IN'),
('has', 'NNP'),
('been', 'NNS'),
('on', 'NNP')]),
(False, [('tear', 'VBJ'), ('this', 'VB')]),
(True,
[('week', 'NNS'),
('already', 'NN'),
('sells', 'IN'),
('its', 'NNP'),
('graphics', 'NNS')]),
(False, [('processing', 'VB'), ('units', 'VBJ')]),
(True,
[('biggest', 'NNS'),
('cloud', 'NN'),
('companies', 'IN'),
('just', 'NNP'),
('that', 'IN')])]
```
The boolean value says whether the following list contains elements that satisfy or don't satisfy the condition. Now all you have to do is only keep the one's who's boolean values are true (the condition is satisfied) and then keep the sublists that contain `'IN'` as one of the part of speech tags.
And just for fun, if you want the whole solution as a (almost unreadably long) one-liner, you can use:
```
[[w[0] for w in b] for b in [list(b) for a,b in itertools.groupby(bb, lambda x: x[1][:2] in ['IN', 'NN']) if a] if 'IN' in [w[1] for w in b]]
```
**EDIT**
In order to only keep the sublists that contain an '`IN`' word with *at least one* `'NN'` word on either side you can do the following:
Start with the same initial `groups` and `results` variables as before:
```
groups = itertools.groupby(bb, lambda x: x[1][:2] in ['IN', 'NN'])
result = [list(b) for a,b in groups if a]
```
Apply the same `groupby` function to the sublists but this time set the condition to having a part of speech equal to `'IN'`:
```
result = [[(a,list(b)) for a,b in itertools.groupby(r, lambda x: x[1] == 'IN')] for r in result]
```
Now iterate through `result` and remove any elements in the sublists who's boolean value from the `groupby` is true (POS is `'IN'`) and it is at the right or left edge of the sublist (index is `0` or `-1`)
```
result = [[b for i,(a,b) in enumerate(r) if (a and i not in [0,len(r)-1]) or not a] for r in result]
```
Now that we have removed these we can join everything together and take out the POS tags to get the correct output format (for details on the list flattening syntax see [here](https://stackoverflow.com/a/952952/5992438))
```
result = [[w[0] for sub in r for w in sub] for r in result]
print(result)
[['company', 'whose', 'stock', 'has', 'been', 'on'],
['week', 'already', 'sells', 'its', 'graphics'],
['biggest', 'cloud', 'companies', 'just']]
``` |
232761 | I'm a noob with R. I want the alphabet index of each letter in a word. I don't understand what I'm doing wrong, since the individual command works perfectly...
```
word <- "helloworld"
l <- numeric(nchar(word))
for (i in 0:nchar(word)) {
l[i] <- match(substr(word,i,i+1), letters)
}
l
```
returns a weird `[1] NA NA NA NA NA NA NA NA NA 4`
when `match(substr(word,0,1), letters)` returns the appropriate `[1] 8` | The problem with your code is two fold.
First R indices start at 1 so when i = 0, l[i] is undefined.
Second, it doesn't just pull off a single letter at a time
```
i = 1
substr(word,i,i+1)
[1] "he"
```
A different approach
```
setNames(1:26, letters)[ strsplit("hello", NULL )[[1]] ]
``` |
233522 | Recently, I am doing the flyback, when I design the control stage I have some questions:
This is the [optocoupler(PC817)](https://www.farnell.com/datasheets/73758.pdf) I used and this figure is Current Transfer Ratio vs. Forward Current. There are my questions:
1.) How to decide the CTR value, because the forward current will change when the circuit is in the closed-loop control.
2.)This curve has two slews positive slew and negative slew, which one is the best to decide.
[![enter image description here](https://i.stack.imgur.com/3lO0Y.png)](https://i.stack.imgur.com/3lO0Y.png)
3.) How to decide the RL value, the minimum current value is 2.5m, so I just let the current above 2.5m is OK? what else do I need to consider?
[![enter image description here](https://i.stack.imgur.com/oEkgt.png)](https://i.stack.imgur.com/oEkgt.png) | In a closed-loop system like with a switching power supply, the optocoupler collector current will vary depending on the operating conditions. For most of the controllers configurations, regulation is ensured by pulling down the FB pin. This is easy for the PCB layout as you do not need to resort to another bias and route it to the opto.
In the below configuration, you can see that the pull-up resistance is 20 kohms and the internal \$V\_{dd}\$ bias is 5 V. The maximum collector current is therefore obtained with the collector-emitter junction saturates at 150 mV or so: \$I\_{c,max}=\frac{V\_{dd}-150m}{20k}=242.5\;µA\$
[![enter image description here](https://i.stack.imgur.com/d540G.png)](https://i.stack.imgur.com/d540G.png)
This collector current will then be reflected in LED current by an \$I\_F\$ value depending on the optocoupler current transfer ratio or CTR. Now it depends on several aspects on how you want to select your CTR:
1. you do not want to operate the LED at too high a current because its life-time depends on it. Fortunately, with a 250-µA collector current worst-case, you will operate the LED at a very small current and its dynamic resistance \$r\_d\$ will affect the overall gain. Unfortunately, in this low-current operating mode, the CTR is extremely poor and values of 100-200 given by the data-sheet often drop to 20-30%.
The below table excerpted from the SFH615A shows how the CTR drops at two different LED currents:
[![enter image description here](https://i.stack.imgur.com/n9bI3.png)](https://i.stack.imgur.com/n9bI3.png)
2. if you want to push crossover and do not want to be bothered by the low-frequency optocoupler pole, then you will select low CTR grades. They have a smaller parasitic capacitance compared to the large CTRs ones but obviously impose larger circulating currents. If you select the large CTR grade, you will see how poor the dynamic response will be.
3. if you look for the smallest standby power at no load, you want to minimize the LED current and will shoot for the largest CTR. For a 19-V output, assume a CTR of 30-40%, then the 250-µA collector current becomes a 833-µA LED current which, multiplied by 19 V gives 16 mW lost in regulation. When brought back to the primary side, it can easily be the double. Now choose a higher CTR grade having around 100% despite the low LED current and the regulation power drops to (250u/1)\*19 = 4.75 mW which is much lower than before.
The PC817 is a popular reference and I have seen also the SFH615A quite often in high-volume designs. |
234252 | I have a URL displayed in the UI,Something like below
```
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="url" l10nTranslate
>URL</label
>
<a [href]="fg.Url.value">{{
fg.Url.value
}}</a>
</div>
```
So I have a clickable URL displayed in the UI below the URL label.
When I have the value of 'www.google.com/' in the URL.When I click on that it has to open the google page, instead it is routing to '<http://localhost:4202/www.google.com/>' instead of going to the google page.
Please help in the regards.
Thanks | The problem is that every call from the `run()` method to `studentRepository` and `studentService` are separate sessions/transactions.
It's virtually as-if you did this:
```
...
beginTransaction();
this.studentRepository.save(student);
commit();
...
beginTransaction();
this.sectionRepository.save(section);
commit();
beginTransaction();
Student student1 = studentRepository.findByName("student");
commit();
beginTransaction();
Section section1 = sectionRepository.findByName("section");
commit();
// This does it's own transaction because of @Transactional
studentService.addSection(student1, section1);
beginTransaction();
this.studentRepository.save(student1);
commit();
```
Since transaction = session here, it means that `student1` is detached, and that the lazy-loaded `studentSections` collection cannot be loaded on-demand outside the session, and hence the code fails.
Inserting a new student and a new section and associating them should really be one transaction, so if a later step fails, it's all rolled back.
Which basically means that you want the entire `run()` method to be one transaction, so in your case, it is the `run()` method that should be `@Transactional`, not the `addSection()` method.
Generally, in a [3-tiered approach](https://en.wikipedia.org/wiki/Multitier_architecture#Three-tier_architecture), you would put transaction boundaries on *service* layer:
* *Presentation tier.* This is `@Controller` classes, or the `run()` method for a simple command-line program.
* *Logic tier.* This is `@Service` classes. This is where you put `@Transactional`, so each service call is an atomic transaction, i.e. it either succeeds or it fails, as far as the database updates are concerned, no half updates.
* *Data tier.* This is `@Repository` and `@Entity` classes.
As such, you should keep the instantiation and initialization of the `Student` and `Section` *objects* in the `run()` method, but the rest of the code, incl. `save()`, should be moved to a single method in a `@Service` class. |
234454 | Referring to the [Question](https://serverfault.com/questions/339661/will-changing-nameservers-cause-down-time) already asked, several people have said
>
> No, as long as both sets of nameservers have the same records you'll experience no downtime.
>
>
>
What does same records meant here? How can I do that?
I currently want to change my hosting only for my [website](https://hkdramahd.com), and want to know If I change Nameserver on previous hosting, will there be any downtime? How can I avoid that? | I guess you know all IP range, so please scan all of them.
Generally speaking in the open port you will have the DNS for all the DC.
You can issue an **nbtstat** after to find the domain from computer that are possible DC from what you discovered;
>
> nbtstat -A IP\_ADDRESS
>
>
>
It would issue an answer like that;
[![enter image description here](https://i.stack.imgur.com/7HkSs.png)](https://i.stack.imgur.com/7HkSs.png)
In that picture, (sorry it's in French), my computer is in a workgroup mode and I issued the command to a DC, which you can see the command found the domain name in the second row, type called Groupe.
I dont think nbtstat command are routable on a VPN, so I would recommand to issue it locally from the subnet if you can. |
234579 | I want to, for example, use rules to notify all users in a particular section that an item of content in their section is 'awaiting moderation'.
Is there a way in Rules to get access to a node's Workbench section?
I can get access to the workbench access term id/menu id, depending on the scheme I'm using, but how can you find the users in that section from there... | If you use workbench access with a taxonomy scheme you could try this
In rules, add an event After moderation transition.
Add the conditions (previous state moderation, current state moderation) according to yours states in workbench moderation
Add the condition Entity has field and then select the field of your workbench access section (field\_section for example : should be the field of your taxonomy vocabulary)
Add an action : send an email.
Then in the field TO of the email , you could use this snippet php wich return the user's email wich have access to the section (specified in Editorial assignments by editor in Workbench Access) and have a specific role id. This snippet return too all the users who have been assigned by their role to the section by their role (Editorial assignments by role in Workbench Access)
```
<?php
$sections = $node->workbench_access;
$terms=taxonomy_term_load_multiple($sections);
foreach ($terms as $term) {
$parents=taxonomy_get_parents_all($term->tid);
if (!empty($parents)) {
foreach ($parents as $parent) {
$tid=$parent->tid;
$voc_name=$parent->vocabulary_machine_name;
if (!in_array($tid, $sections)) {
$sections[$tid]=$tid;
}
}
$sections[$voc_name]="'".$voc_name."'";
}
};
// Only the users who have the role id [ROLE_ID]
$role_id=[ROLE_ID];
$emails = array();
foreach ($sections as $section) {
$result = db_query("SELECT user.mail AS mail FROM users user, workbench_access_user workbench, users_roles roles WHERE roles.rid=$role_id AND user.uid=roles.uid AND user.uid=workbench.uid AND access_id=$section");
foreach($result as $record) {
$mail=$record->mail;
if (!in_array($mail,$emails)) { $emails[] = $mail; }
}
}
foreach ($sections as $section) {
$result = db_query("SELECT user.mail AS mail FROM users user, workbench_access_role workbench, users_roles roles WHERE user.uid=roles.uid AND roles.rid=workbench.rid AND access_id=$section");
foreach($result as $record) {
$mail=$record->mail;
if (!in_array($mail,$emails)) { $emails[] = $mail; }
}
}
print implode($emails, ",");
?>
```
And you complete the others email's field with the token available.
This sandbox project [Workbench Notify](http://drupal.org/sandbox/flocondetoile/1946080) implement this snippet |
235258 | I'm trying to send an invoice message in the Telegram bot, but get an error
{"ok":false,"error\_code":400,"description":"Bad Request: can't parse prices JSON object"}
Here is my send invoice def:
```
def sendInvoice(chat_id):
invoice = {'chat_id': chat_id,
'title': 'Оплата услуги',
'description': 'Лайки на фото для инстаграм',
'payload': 'Payload',
'provider_token': 'provider_token',
'start_parameter': 'insta pay',
'currency': 'UAH',
'prices': {'label': 'Цена', 'amount': 300000},
}
url = URL + 'sendInvoice'
response = requests.post(url, invoice)
print(response.__dict__)
``` | You need to convert your list of prices to json serializable -
use the json module built it in python
```
json.dumps([
{
"label": "My product",
"amount": 999999
}
])
``` |
235280 | I'm trying to redact phone number information from an html file ... and while I can identify all of the phone numbers easily enough I can't figure out why I am unable to replace the phone numbers that have parentheses in them. Sample below:
```
import re
from bs4 import BeautifulSoup
text = '''<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>
<style type="text/css">
.parsed {font-size: 75%; color: #474747;}
</style>
</head>
<body>
<div class="parsed">
<h1>Redacted Redacted</h1>
<h2> Contact Info</h2>
<ul>
<li>Position Title: My Fake Title</li>
<li>Email: Redacted@gmail.com</li>
<li>Phones: (555) 555-5555</li>
</ul><b>Category:</b> <ul><li>Title 2 </li><li>Fake Info</li></ul>
City, MO 11111 | (555) 111-1111 | myemail@gmail.com
Some Category / Some Name: 555-222-2222 | Record Number#:
</html>'''
soup = BeautifulSoup(text, 'html.parser')
def find_phone_numbers(text):
phones = re.findall(r"((?:\d{3}|\(\d{3}\))?(?:\s|-|\.)?\d{3}(?:\s|-|\.)\d{4})", text)
return phones
phones = find_phone_numbers(str(soup))
print(phones)
for i in phones:
target = soup.find_all(text=re.compile(i, re.I))
try:
for v in target:
v.replace_with(v.replace(i,'(XXX) XXX-XXXX'))
except TypeError:
pass;
print(soup)
```
These are my results from running the above:
```
['(555) 555-5555', '(555) 111-1111', '555-222-2222']
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>
<style type="text/css">
.parsed {font-size: 75%; color: #474747;}
</style>
</head>
<body>
<div class="parsed">
<h1>Redacted Redacted</h1>
<h2> Contact Info</h2>
<ul>
<li>Position Title: My Fake Title</li>
<li>Email: Redacted@gmail.com</li>
<li>Phones: (555) 555-5555</li>
</ul><b>Category:</b> <ul><li>Title 2 </li><li>Fake Info</li></ul>
City, MO 11111 | (555) 111-1111 | myemail@gmail.com
Some Category / Some Name: (XXX) XXX-XXXX | Record Number#:
</div></body></html>
``` | You can use `.find_all(text=True)` to obtain all text content from the HTML soup, and then replace it with `re.sub` (that way, you preserve all tags, including `<li>`):
```
for content in soup.find_all(text=True):
s = re.sub(r'(\(?\d{3}\)?)([\s.-]*)(\d{3})([\s.-]*)(\d{4})', '(XXX) XXX-XXXX', content)
content.replace_with(s)
print(soup)
```
Prints:
```
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>
<style type="text/css">
.parsed {font-size: 75%; color: #474747;}
</style>
</head>
<body>
<div class="parsed">
<h1>Redacted Redacted</h1>
<h2> Contact Info</h2>
<ul>
<li>Position Title: My Fake Title</li>
<li>Email: Redacted@gmail.com</li>
<li>Phones: (XXX) XXX-XXXX</li>
</ul><b>Category:</b> <ul><li>Title 2 </li><li>Fake Info</li></ul>
City, MO 11111 | (XXX) XXX-XXXX | myemail@gmail.com
Some Category / Some Name: (XXX) XXX-XXXX | Record Number#:
</div></body></html>
``` |
235433 | I'm trying to make a service that works 24/7 and it's been working until I updated to Android 12. I've checked the new foreground restrictions but still don't understand why it isn't working since I'm starting it from an activity.
ACTIVITY
```
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startForegroundService(new Intent(TestActivity.this, TestService.class));
}
}
```
SERVICE
```
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.media.MediaBrowserCompat;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.media.MediaBrowserServiceCompat;
import java.util.List;
public class TestService extends MediaBrowserServiceCompat {
@Override
public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid, @Nullable Bundle rootHints) { return null; }
@Override
public void onLoadChildren(@NonNull String parentId, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) { result.sendResult(null); }
@Override
public int onStartCommand(Intent ii, int flags, int startId) {
//CREATE NOTI CHANNEL
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"test", "Test Notifications",
NotificationManager.IMPORTANCE_HIGH);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
}
//CREATE NOTI
Notification notification = new NotificationCompat.Builder(this, "test")
.setSmallIcon(R.drawable.icon)
.setContentTitle("title")
.setContentText("test")
.setChannelId("test")
.setOngoing(true)
.setSilent(true)
.build();
//START FOREGROUND
startForeground(101, notification);
return START_STICKY;
}
}
```
I tried creating a new app with just these lines of code and it works fine so it must be something else making the service close after a minute. | Turns out samsung put my app on deep sleep which caused it to close itself if not used for a minute. Also thanks to the people who took their time to try and help. |
235568 | In device driver programming we are using 1. device driver code, 2. device file, 3. user space application code and 4. actual physical hardware.
* I am able to write the driver code, user space application code and manually creating device file but interfacing hardware i want to try (at least blinking an LED through device driver in Raspberry Pi) and it looks little difficult to me.
* And if I am able to blinking a LED means the communication is happening between all the above four listed items.
I was taken some online code for blinking LED and tested but its not working. | Because strings in JavaScript don't have an `equals` method. You compare them via `===`.
Also, you can simplify your `isPermutation` function by returning the result of the comparison directly.
```js
function sort(string) {
return string
.split("")
.sort()
.join("");
}
function isPermutation(s1, s2) {
return sort(s1) === sort(s2);
}
console.log(isPermutation("dog", "god"));
``` |
235579 | I'm building a program that communicates with Emacs, and one of the challenges I'm facing is writing Emacs's process filter function. Its input string is a series of s-expressions to be evaluated. Here is a sample:
```
(gimme-append-to-buffer "25 - William Christie dir, Les Arts Florissants - Scene 2. Prelude - Les Arts Florissants\n")
(gimme-append-to-buffer "26 - William Christie dir, Les Arts Florissants - Cybele: 'Je Veux Joindre' - Les Arts Florissants\n")
(gimme-append-to-buffer "27 - William Christie dir, Les Arts Florissants - Scene 3. Cybele: 'Tu T'Etonnes, Melisse' - Les Arts Florissants\n")
(gimme-append-to-buffer "28 - William Christie dir, Les Arts Florissants - Cybele: 'Que Les Plus Doux Zephyrs'. Scene 4. - Les Arts Florissants\n")
(gimme-append-to-buffer "29 - William Christie dir, Les Arts Florissants - Entree Des Nations - Les Arts Florissants\n")
(gimme-append-to-buffer "30 - William Christie dir, Les Arts Florissants - Entree Des Zephyrs - Les Arts Florissants\n")
(gimme-append-to-buffer "31 - William Christie dir, Les Arts Florissants - Choeur Des Nations' 'Que Devant Vous' - Les Arts Florissants\n")
(gimme-append-to-buffer "32 - William Christie dir, Les Arts Florissants - Atys: 'Indigne Que Je Suis' - Les Arts Florissants\n")
(gimme-append-to-buffer "33 - William Christie dir, Les Arts Florissants - Reprise Du Choeur Des Nations : 'Que Devant Nous' - Les Arts Florissants\n")
(gimme-append-to-buffer "34 - William Christie dir, Les Arts Flor*emphasized text*issants - Reprise De L'Air Des Zephyrs - Les Arts Florissants\n")
```
The first problem that I've faced is that the string is somehow not fully formed when the function is so called, so writing something like `(mapcar 'eval (format "(%s)" input-string))` won't work.
To deal with this first problem, I was using a loop. The full function I wrote is:
```
(defun eval-all-sexps (s)
(loop for x = (ignore-errors (read-from-string s))
then (ignore-errors (read-from-string (substring s position)))
while x
summing (or (cdr x) 0) into position
doing (eval (car x))))
```
Now the second problem that showed up is that the function is called twice with a somewhat large input, first with valid but partial content, then with what looks like pieces of the remaining data.
To solve this problem, I'm considering using a junk variable to hold up what remains from a loop and then concatenating it to the input of the next call, but I was wondering if you guys have any other suggestions on how to deal with such a problem more elegantly.
Thanks! | That's what I do in a shell mode I use.
I look for a special end-of-record string in the process output, to know when the output is complete. Until then I concat the chunks.
```
(defun my-shell-exec-filter (process result)
(let ((end-of-result (string-match my-shell-end-of-record-string result)))
(if (and end-of-result
(numberp end-of-result)
(> end-of-result 0))
(setq my-shell-reply
(concat my-shell-reply
(substring (substring result 0 end-of-result) 0 -1)))
(progn
(setq my-shell-reply (concat my-shell-reply result))
(accept-process-output process my-shell-exec-timeout 5)))))
```
This isn't quite right because the end-of-record string can be split across multiple invocations of that filter fn. So to be correct, it ought to concat first, then check for a match. But anyway you get the idea.
Also it recurses, and because of that, for very very long input, it can incur a stack overflow exception. So it definitely is not as clean as I would like.
The thing is kicked off with
```
(setq my-shell-reply nil)
(set-process-filter proc my-shell-exec-filter)
(process-send-string proc "whatever...")
(if (not (accept-process-output proc my-shell-exec-timeout 100))
(error "unexpected response."))
;; examine my-shell-reply here ...
``` |