qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
73,210,629 |
Is there a better way to write this such that I don't need to add a new column to the existing dataframe?
```
## Sample Data -- df_big
Groups, TotalOwned
0, 1
0, 5
1, 3
2, 2
2, 1
## My Code
df_mult = df_big[['Groups', 'TotalOwned']].copy()
df_mult['Multiple'] = np.where(df_mult['TotalOwned'] > 1, 1, 0)
df_mult.groupby('Groups')['Multiple'].mean().sort_index()
## Output -- now with fixed output!
Groups
0 0.5
1 1.0
2 0.5
```
|
2022/08/02
|
[
"https://Stackoverflow.com/questions/73210629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7722603/"
] |
I got the same issue resolved.
First you need to make sure
CONFIG\_DEBUG\_INFO\_BTF=y
is set and pahole is installed from <https://github.com/acmel/dwarves>.
And I enabled
CONFIG\_DEBUG\_INFO\_SWARF4=y
And you have to make the pahole libs linked(This stopped me for long.):
export LD\_LIBRARY\_PATH=/usr/local/lib:$LD\_LIBRARY\_PATH
My previous failures are:
1. I did not disable CONFIG\_DEBUG\_INFO\_NONE. This config is for disable all the debug config info.
2. some modules failure, like SSSE3 and chacha20 module. I just disabled them tool. These are crypto modules not sure why they fail.
I hope this would also help you.
|
1,839,705 |
Does the series $$\sum\_{n=1}^\infty(-1)^n\tan\left(\frac{\pi}{n+2}\right)\sin\left(\frac{n\pi}{3}\right )$$ converge and why?
I think that Leibniz' test may be helpful, but I wasn't able to find a proper way to apply it.
|
2016/06/25
|
[
"https://math.stackexchange.com/questions/1839705",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/350201/"
] |
The function $\;\tan\frac\pi{n+2}\;$ is monotone descending and positive, and also $\;\lim\limits\_{n\to\infty}\tan\frac\pi{n+2}=0\;$ , and since
$$\sin\frac{n\pi}3=\begin{cases}\pm\frac{\sqrt3}2\;,&n=1,2\pmod 3\\{}\\0\,,&n=0\pmod 3\end{cases}$$
and its series is bounded:
$$\left|\sum\_{n=1}^N\sin\frac{n\pi}3\right|=\left|\frac{\sqrt3}2+\frac{\sqrt3}2+0-\frac{\sqrt3}2-\frac{\sqrt3}2-0+\frac{\sqrt3}2+\ldots\right|\le\sqrt3$$
then using Dirichlet's test the series converges. Fill in details.(for example, how do you handle the $\;(-1)^n\;$ ?)
|
4,366,942 |
Is the following argument valid? if not why?
$$((P \lor (Q \land R) ) \land (\lnot R \lor S) \land (S \to \lnot T)) \to ( T \to P)$$
|
2022/01/26
|
[
"https://math.stackexchange.com/questions/4366942",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1019010/"
] |
Since $f$ is continuous at $g(c)$, the definition of continuity tells us that for all $\varepsilon > 0$ there is some $\delta\_1$ such that
$$|g(x) - g(c)| < \delta\_1\implies|f(g(x))-f(g(c))|<\varepsilon.$$
Also, since $g$ is continuous at $a$, there is some $\delta$ such that $$|x-c|<\delta \implies |g(x)-g(c)|<\delta\_1.$$
We've taken $\varepsilon =\delta\_1$ here. Now this tells us that for all $\varepsilon > 0$ there is some $\delta > 0$ (and a $\delta\_1 > 0$) such that $$|x-c| < \delta\implies|g(x)-g(a)|<\delta\_1\implies|f(g(x)) - f(g(c))|<\varepsilon,$$
which is what we wanted to show.
|
24,579,053 |
I got this very confusing array of hashes as an API response.
<http://jsfiddle.net/PP9N5/>
( the full response is massive. Posting only a part of it but it covers all elements of the response)
How can I get to "airlines".
I tried this
```
<% @flight["air_search_result"]["onward_solutions"]["solution"].each do|h| %>
<strong><%=h["pricing_summary"]["total_fare"] %></strong> -
<% h["flights"]["flight"]["segments"]["segment"].each do |s| %>
<%= s['airline'] %>
<% end %> <br> <hr>
<% end %>
```
And I get this error
>
> can't convert String into Integer
>
>
>
I did some modifications like
```
<%= h["flights"]["flight"]["segments"]["segment"].first["airline"] %>
Error received - can't convert String into Integer
```
and
```
<%= h["flights"]["flight"]["segments"]["segment"][0]["airline"] %>
Error received - undefined method '[]' for nil:NilClass
```
Isnt there a simple way, like I say to find a key "airline" and for that key it returns its value. I stumbled upon [this link](http://qugstart.com/blog/uncategorized/ruby-multi-level-nested-hash-value/), though I dont get any error, I also dont get any result.
Thanks.
UPDATE
I did this
```
<% h["flights"]["flight"]["segments"]["segment"].each do |o,p| %>
<% if o=="airline" %> <%= p %> <% end %>
<% end %> <br> <hr>
<% end %>
```
I can get few values of airlines where inside segment there is no array.
For eg, i can get where departure\_date\_time is 2014-07-07T07:10:00, index = 5.
<http://jsfiddle.net/PP9N5/1/> (scroll down)
|
2014/07/04
|
[
"https://Stackoverflow.com/questions/24579053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2096740/"
] |
Here is some code you can add which will extract all keys equal the parameter in any `Hash` within your `Hash`:
```
class Hash
def deep_find(query, &block)
flat_map do |key, value|
if key == query
yield value if block_given?
[value]
elsif value.is_a? Hash
value.deep_find(query, &block)
elsif value.is_a? Array
value.select { |i| i.is_a? Hash }.flat_map { |h| h.deep_find(query, &block) }
end
end
end
end
```
Example:
```
hash = {"h" => [{ 'x' => [1, 5] }, { 'x' => 2 }, { 'f' => { 'x' => [3, 4] } }], 'x' => 6 }
hash.deep_find('x') { |x| puts "#{x}" }
# [1, 5]
# 2
# [3, 4]
# 6
# => [[1, 5], 2, [3, 4], 6]
```
|
26,606,355 |
Are there any clever algorithms for computing high-quality checksums on millions or billions of prime numbers? I.e. with maximum error-detection capability and perhaps segmentable?
Motivation:
Small primes - up to 64 bits in size - can be sieved on demand to the tune of millions per second, by using a small bitmap for sieving potential factors (up to 2^32-1) and a second bitmap for sieving the numbers in the target range.
Algorithm and implementation are reasonably simple and straightforward but the devil is in the details: values tend to push against - or exceed - the limits of builtin integral types everywhere, boundary cases abound (so to speak) and even differences in floating point strictness can cause breakage if programming is not suitably defensive. Not to mention the mayhem that an optimising compiler can wreak, even on already-compiled, already-tested code in a static lib (if link-time code generation is used). Not to mention that faster algorithms tend to be a lot more complicated and thus even more brittle.
This has two consequences: test results are basically meaningless unless the tests are performed using the final executable image, and it becomes highly desirable to verify proper operation at runtime, during normal use.
Checking against pre-computed values would give the highest degree of confidence but the required files are big and clunky. A text file with 10 million primes has on the order of 100 MB uncompressed and more than 10 MB compressed; storing byte-encoded differences requires one byte per prime and entropy coding can at best reduce the size to half (5 MB for 10 million primes). Hence even a file that covers only the small factors up to 2^32 would weigh in at about 100 MB, and the complexity of the decoder would exceed that of the windowed sieve itself.
This means that checking against files is not feasible except as a final release check for a newly-built executable. Not to mention that the trustworthy files are not easy to come by. The [Prime Pages](http://primes.utm.edu/) offer files for the first 50 million primes, and even the amazing [primos.mat.br](http://www.primos.mat.br/indexen.html) goes only up to 1,000,000,000,000. This is unfortunate since many of the boundary cases (== need for testing) occur between 2^62 and 2^64-1.
This leaves checksumming. That way the space requirements would be marginal, and only proportional to the number of test cases. I don't want to require that a decent checksum like MD5 or SHA-256 be available, and with the target numbers all being prime it should be possible to generate a high-quality, high-resolution checksum with some simple ops on the numbers themselves.
This is what I've come up with so far. The raw digest consists of four 64-bit numbers; at the end it can be folded down to the desired size.
```cpp
for (unsigned i = 0; i < ELEMENTS(primes); ++i)
{
digest[0] *= primes[i]; // running product (must be initialised to 1)
digest[1] += digest[0]; // sum of sequence of running products
digest[2] += primes[i]; // running sum
digest[3] += digest[2] * primes[i]; // Hornerish sum
}
```
At two (non-dependent) muls per prime the speed is decent enough, and except for the simple sum each of the components has always uncovered all errors I tried to sneak past the digest. However, I'm not a mathematician, and empirical testing is not a guarantee of efficacy.
Are there some mathematical properties that can be exploited to design - rather than 'cook' as I did - a sensible, reliable checksum?
Is it possible to design the checksum in a way that makes it steppable, in the sense that subranges can be processed separately and then the results combined with a bit of arithmetic to give the same result as if the whole range had been checksummed in one go? Same thing as all advanced CRC implementations tend to have nowadays, to enable parallel processing.
**EDIT** The rationale for the current scheme is this: the count, the sum and the product do not depend on the order in which primes are added to the digest; they can be computed on separate blocks and then combined. The checksum does depend on the order; that's its raison d'Γͺtre. However, it would be nice if the two checksums of two consecutive blocks could be combined somehow to give the checksum of the combined block.
The count and the sum can sometimes be verified against external sources, like certain sequences on [oeis.org](http://oeis.org/A099825), or against sources like the batches of 10 million primes at [primos.mat.br](http://primos.mat.br/) (the index gives first and last prime, the number == 10 million is implied). No such luck for product and checksum, though.
Before I throw major time and computing horsepower at the computation and verification of digests covering the whole range of small factors up to 2^64 I'd like to hear what the experts think about this...
The scheme I'm currently test-driving in 32-bit and 64-bit variants looks like this:
```cpp
template<typename word_t>
struct digest_t
{
word_t count;
word_t sum;
word_t product;
word_t checksum;
// ...
void add_prime (word_t n)
{
count += 1;
sum += n;
product *= n;
checksum += n * sum + product;
}
};
```
This has the advantage that the 32-bit digest components are equal to the lower halves of the corresponding 64-bit values, meaning only 64-bit digests need to be computed stored even if fast 32-bit verification is desired. A 32-bit version of the digest can be found in this simple [sieve test program](http://pastebin.com/UyDSDG3D) @ pastebin, for hands-on experimentation. The full Monty in a revised, templated version can be found in a newer paste for [a sieve that works up to 2^64-1](http://pastebin.com/EjkuudTD).
|
2014/10/28
|
[
"https://Stackoverflow.com/questions/26606355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4156577/"
] |
I've done a good bit of work parallelizing operations on [Cell](http://en.wikipedia.org/wiki/Cell_(microprocessor)) architectures. This has a similar feel.
In this case, I would use a hash function that's fast and possibly incremental (e.g. [xxHash](https://code.google.com/p/xxhash/) or [MurmurHash3](https://code.google.com/p/smhasher/wiki/MurmurHash3)) and a [hash list](http://en.wikipedia.org/wiki/Hash_list) (which is a less flexible specialization of a [Merkle Tree](https://code.google.com/p/smhasher/wiki/MurmurHash3)).
These hashes are extremely fast. It's going to be surprisingly hard to get better with some simple set of operations. The hash list affords parallelism -- different blocks of the list can be handled by different threads, and then you hash the hashes. You could also use a Merkle Tree, but I suspect that'd just be more complex without much benefit.
* Virtually divide your range into aligned blocks -- we'll call these microblocks. (e.g. a microblock is a range such as [n<<15, (n+1)<<15) )
* To handle a microblock, compute what you need to compute, add it to a buffer, hash the buffer. (An incremental hash function will afford a smaller buffer. The buffer doesn't have to be filled with the same length of data every time.)
* Each microblock hash will be placed in a [circular buffer](http://en.wikipedia.org/wiki/Circular_buffer).
* Divide the circular buffer into hashable blocks ("macroblocks"). Incrementally hash these macroblocks in the proper order as they become available or if there's no more microblocks left.
* The resulting hash is the one you want.
Some additional notes:
* I recommend a design where threads reserve a range of pending microblocks that the circular buffer has space for, process them, dump the values in the circular buffer, and repeat.
* This has the added benefit that you can decide how many threads you want to use on the fly. e.g. when requesting a new range of microblocks, each thread could detect if there's too many/little threads running and adjust.
* I personally would have the thread adding the last microblock hash to a macroblock clean up that macroblock. Less parameters to tune this way.
* Maintaining a circular buffer isn't as hard as it sounds -- the lowest order macroblock still unhandled defines what portion of the "macroblock space" the circular buffer represents. All you need is a simple counter that increments when appropriate to express this.
* Another benefit is that since the threads go through a reserve/work/reserve/work cycle on a regular basis, a thread that is unexpectedly slow won't hinder the running time nearly as badly.
* If you're looking to make something less robust but easier, you could forgo a good bit of the work by using a "striped" pattern -- decide on the max number of threads (N), and have each thread handle every N-th microblock (offset by its thread "ID") and hash the resulting macroblocks per thread instead. Then at the end, hash the macroblock hashes from the N threads. If you have less than N threads, you can divide the work up amongst the number of threads you do want. (e.g. 64 max threads, but three real threads, thread 0 handles 21 virtual threads, thread 1 handles 21 virtual threads, and thread 2 handles 22 virtual threads -- not ideal, but not terrible) This is essentially a shallow Merkel tree instead of a hash list.
|
51,792,939 |
I have been trying to get a PySpark job to work which creates a RDD with a bunch of binary files, and then I use a `flatMap` operation to process the binary data into a bunch of rows. This has lead to a bunch of out of memory errors, and after playing around with memory settings for a while I have decided to get the simplest thing possible working, which is just counting the number of files in the RDD.
This also fails with OOM error. So I opened up both the spark-shell and PySpark and ran the commands in the REPL/shell with default settings, the only additional parameter was `--master yarn.` The `spark-shell`version works, while the PySpark version shows the same OOM error.
Is there that much overhead to running PySpark? Or is this a problem with `binaryFiles` being new? I am using Spark version 2.2.0.2.6.4.0-91.
|
2018/08/10
|
[
"https://Stackoverflow.com/questions/51792939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282350/"
] |
The difference:
* Scala will load records as `PortableDataStream` - this means process is lazy, and unless you call `toArray` on the values, won't load data at all.
* Python will call Java backend, but load the data as byte array. This part will be eager-ish, therefore might fail on both sides.
Additionally PySpark will use at least twice as much memory - for Java and Python copy.
Finally `binaryFiles` (same as `wholeTextFiles`) are very inefficient and don't perform well, if individual input files are large. In case like this it is better to implement format specific Hadoop input format.
|
63,456,486 |
Utilizing the `OEHR_EMPLOYEES` table on Oracle Apex, I would like to convert the `DEPARTMENT ID` column values to corresponding words. For example, `DEPARTMENT ID` with a value of 10 will become `'HR'`, `DEPARTMENT ID` with a value of 20 will become `'Finance'`, etc. The `DEPARTMENT ID` is currently a Number data type. I am not even sure where to begin with this task..
|
2020/08/17
|
[
"https://Stackoverflow.com/questions/63456486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023924/"
] |
`next` is control flow, so no, you cannot `next` from inside the yield.
Using `block_given?` is the only way to do it with this callback structure (without nonlinear control flow like `raise` or `throw`), and as you've mentioned, it works a bit weird b/c abstraction doesn't quite fit.
I think it would be more straightforward to "to things in-place" instead of injecting a block, like this:
```rb
to_increment, to_destroy = subscriptions_params.partition { |p| p[:checked] }
product.subscriptions.where(id: to_increment.map { _1[:id] })
.each { |sub| sub.counter += 1 }
.then { |subs| Subscription.update_all(subs) } # something like this, I forget exact syntax
product.subscriptions.where(id: to_destroy.map { _1[:id] }).destroy_all!
```
The reason for this is because there's not much shared logic or "work" to really extract -- it's just doing some action(s) multiple times.
Perhaps what you're looking for is to build those actions into `Subscription` as methods? like this:
```rb
class Subscription < ApplicationRecord
def increment!
self.counter += 1
end
end
product.subscriptions.where(id: to_increment).each(&:increment!).each(&:update!)
```
Or perhaps all you need is an `update_subs!` like:
```rb
class Product < ApplicationRecord
def update_subs!(sub_ids)
subs = subscriptions.where(id: ids).each { |sub| yield sub }
subs.each(&:update!)
end
end
# one line each, can't get much more straightforward than this
product.update_subs!(to_increment) { |sub| sub.counter += 1 }
product.subscriptions.where(id: to_destroy).each(&:destroy!)
```
|
31,734,441 |
Let's say we have class `A`:
```
class A {
public:
A& func1( int ) { return *this; }
A& func2( int ) { return *this; }
};
```
and 2 standlone functions:
```
int func3();
int func4();
```
now in this code:
```
A a;
a.func1( func3() ).func2( func4() );
```
is order of evaluation of functions `func3()` and `func4()` defined?
According to this answer [Undefined behavior and sequence points](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) one of the sequence points are:
* at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which
takes place before execution of any expressions or statements in the function body (`Β§1.9/17`).
So does "evaluation of all function arguments" mean, `func3()` has to be called before `func4()` as evaluation of `func1()` arguments has to happen before call of `func2()`?
|
2015/07/30
|
[
"https://Stackoverflow.com/questions/31734441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432358/"
] |
The gist of it is that in a function call, `X(Y, Z)` ; evaluation of all of `X`, `Y`, `Z` are indeterminately sequenced with respect to each other. The only sequencing is that `Y` and `Z` are *sequenced-before* the call to the function which `X` evaluated to.
Suppose we have:
```
typedef void (*fptr)(int, double);
fptr a();
int b();
double c();
a()(b(), c());
```
The three functions `a`, `b`, `c` may be called in any order. Of course this all applies recursively to any sub-expressions.
|
71,001,214 |
I have this array.map function:
```
{props.help.map((e, i) => {
return <a key={i}>{e.name}</a>
})}
```
{e} object have 'name' and 'href' keys
i got "Property 'name' does not exist on type 'object'" (typescript)
I am beginner in typescript.
|
2022/02/05
|
[
"https://Stackoverflow.com/questions/71001214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17107306/"
] |
You need to either cast the object to type `any` or the best practice is to add a type definition.
```
interface ExampleObject {
name: string;
}
```
```
{
props.help.map((e: ExampleObject, i) => {
return <a key={i}>{e.name}</a>
})
}
```
|
31,937,100 |
`new Guid()` and `Guid.Empty` produces the same results (all-0 guid (00000000-0000-0000-0000-000000000000).
```
var guid = new Guid();
Console.WriteLine(guid);//00000000-0000-0000-0000-000000000000
var emptyGuid = Guid.Empty;
Console.WriteLine(emptyGuid);//00000000-0000-0000-0000-000000000000
```
Is this a two different manners to do the same thing ? readabilty reasons ? or i'm missing something ?
|
2015/08/11
|
[
"https://Stackoverflow.com/questions/31937100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1197539/"
] |
`Guid` is a `struct`. All structs have an *implicit default constructor* which initializes all members to their default value. In `Guid`, you see that as setting all it's composite members to `0`.
[`Guid.Empty` simply caches the default value](http://referencesource.microsoft.com/#mscorlib/system/guid.cs,13baca63417ef924,references) via the invocation of the default constructor:
```
public struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid>
{
public static readonly Guid Empty = new Guid();
}
```
|
3,067,237 |
My website is like stackoverflow, there are many questions. I want to record how many times a question has been visited. I have a column called "view\_count" in the question table to save it.
If a user visits a question many times, the view\_count should be increased only 1. So I have to record which user has visited which question, and I think it is too much expensive to save this information in the database because the records will be huge. So, I would like to keep the information in memory and only persist the number to the database every 10 minutes.
I have searched about "cache" in Rails, but I haven't found an example. I would like a simple sample of how to do this, thanks for help~
|
2010/06/18
|
[
"https://Stackoverflow.com/questions/3067237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342235/"
] |
Casting is not what you want. This code:
```
int score = 0;
char* fixedscore=(char*)score;
```
is the equivalent of doing:
```
char* fixedscore = NULL;
```
I assume you are trying to get `fixedscore` to hold the textual value of the number in score. The easiest way using just standard C++ is via `stringstream`:
```
std::stringstream strm;
strm << score;
...
imgTxt = TTF_RenderText_Solid( font, strm.str().c_str(), fColor );
```
|
68,958,411 |
I have a date time that I am first converting to local time, followed by a conversion to another time zone. The first conversion works with no issue however the second conversion is ignored. What is the issue?
```
String input = "2020-05-20 01:10:05";
SimpleDateFormat localFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
localFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
try {
Date date = localFormat.parse(input);
System.out.println(date); //Wed May 20 01:10:05 PDT 2020 <--- Logs this (Expected)
SimpleDateFormat estFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
estFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String newDate = estFormat.format(date);
System.out.println(newDate); //2020-05-20 04:10:05 <--- Logs this (Expected)
Date dateEst = estFormat.parse(newDate);
System.out.println(dateEst); //Wed May 20 01:10:05 PDT 2020 <--- Logs this (Unexpected) Should be Wed May 20 04:10:05 EST 2020
}catch (Exception e){
e.printStackTrace();
}
```
It seems like the second `estFormat.parse()` is ignored when trying to convert to `America/New_York` time zone.
|
2021/08/27
|
[
"https://Stackoverflow.com/questions/68958411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11628353/"
] |
java.time
---------
I warmly recommend that you use java.time, the modern Java date and time API, for your date and time work. Once you get used to the slightly different mindset, you will likely also find the resulting code clearer and more natural to read. Letβs first define the constant stuff as constants:
```
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
private static final ZoneId FROM_ZONE = ZoneId.of("America/Los_Angeles");
private static final ZoneId TO_ZONE = ZoneId.of("America/New_York");
```
With these we can do our work:
```
String input = "2020-05-20 01:10:05";
ZonedDateTime fromDateTime
= LocalDateTime.parse(input, FORMATTER).atZone(FROM_ZONE);
System.out.println("From: " + fromDateTime);
ZonedDateTime toDateTime = fromDateTime.withZoneSameInstant(TO_ZONE);
System.out.println("To: " + toDateTime);
String formatted = toDateTime.format(FORMATTER);
System.out.println("Formatted: " + formatted);
```
Output is:
>
>
> ```
> From: 2020-05-20T01:10:05-07:00[America/Los_Angeles]
> To: 2020-05-20T04:10:05-04:00[America/New_York]
> Formatted: 2020-05-20 04:10:05
>
> ```
>
>
Edit:
>
> How would I get it to have `EST 2020` at the end?
>
>
>
A good option for most purposes is to use a localized formatter:
```
private static final DateTimeFormatter TARGET_FORMATTER
= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.US);
```
Like this:
```
String formatted = toDateTime.format(TARGET_FORMATTER);
```
>
>
> ```
> Formatted: May 20, 2020 at 4:10:05 AM EDT
>
> ```
>
>
A detail, we didnβt get EST at the end because New York and most of the East coast of Northern America uses summer time (DST) and hence is on Eastern Daylight time, EDT, in May.
What went wrong?
----------------
It seems that you were expecting your `Date` object to carry the time zone of the formatter that parsed it, America/New\_York. An old-fashioned `Date` object cannot do that. Itβs just a dumb point in time without any time zone or other additional information. What confuses many is that its `toString` method uses the default time zone of the JVM to render the string returned, thus giving the false impression of a time zone being present. In contrast the modern `ZonedDateTime`, as the name says, does hold a time zone.
Link
----
[Oracle tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/) explaining how to use java.time.
|
60,654,151 |
I tried connecting my PHP file to MySQli database but when i ran the code it displays [](https://i.stack.imgur.com/PBi2F.jpg)
But when i logon to phpmyadmin it works fine no errors i can login to my account with no problems
**Credentials in the database:**
[](https://i.stack.imgur.com/t9JIL.jpg)
**Connection Code:**
```php
<?php
$con = mysqli_connect('localhost','sotomango', '1234', 'mysql');
if(!$con) {
echo 'noooo';
}
?>
```
I double checked the database usernames, passwords, and privileges. Everything seems in place and correct, but the php file wont allow me to connect to the database.
|
2020/03/12
|
[
"https://Stackoverflow.com/questions/60654151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12062981/"
] |
As the error says the `coordibate` property is immutable
```
var coordinate: CLLocationCoordinate2D { get }
var userLocation: CLLocation { get }
```
you can't alter it in addition to `userLocation` , if you need a different location go directly with
|
23,142,796 |
To serialize an object to json using json.net, I need to create POCOs with attributes labled for each json property:
```
public class Priority
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("iconUrl")]
public string IconUrl { get; set; }
}
```
I'm using this to interact with Jira's REST API, and it works well for all the standard fields. Unfortunately, custom fields are where things trip up. Custom fields don't have determined field names, and instead have numbers assigned to them. So if I have a "Resolution Type" custom field, the property won't be called "ResolutionType", but rather "customfield\_10200".
I'm dealing with multiple deployments with the same custom fields, but they all have different field Ids. What I'd love to do is something like this:
```
[JsonProperty(ConfigurationManager.AppSettings["JiraResolutionTypeId"])]
public string ResolutionType{ get; set; }
```
But you can only have compile-time constants in attributes like that, so I can't dynamically set the id in that manner.
How can I get around this?
|
2014/04/17
|
[
"https://Stackoverflow.com/questions/23142796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76322/"
] |
Using a [custom contract resolver](http://james.newtonking.com/json/help/index.html?topic=html/ContractResolver.htm) should let you do this pretty easily. Adding your own `Attribute` class lets you do it in a generic way.
```
// add attribute so this only targets properties, or whatever you want
public class JiraAttribute : Attribute
{
public string LookupId { get; private set; }
public JiraAttribute(string lookupId)
{
this.LookupId = lookupId;
}
}
public class JiraContractResolver : DefaultContractResolver
{
public static readonly JiraContractResolver Instance = new JiraContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
var attr = member.GetCustomAttributes(typeof(JiraAttribute), true).Cast<JiraAttribute>().ToList();
if (attr != null && attr.Count > 0)
{
property.PropertyName = ConfigurationManager.AppSettings[attr[0].LookupId];
}
return property;
}
}
// in a class
[Jira("JiraResolutionTypeId")]
public string ResolutionType { get; set; }
//e.g.
// ConfigurationManager.AppSettings["JiraResolutionTypeId"] == "customfield_10200"
var settings = new JsonSerializerSettings { ContractResolver = JiraContractResolver.Instance };
var s = JsonConvert.SerializeObject(new Priority { Id = "123", ResolutionType = "abc" }, settings);
// {"id":"123","name":null,"iconUrl":null,"customfield_10200":"abc"}
var d = JsonConvert.DeserializeObject<Priority>(s, settings);
// d.ResolutionType == "abc"
```
|
65,329,896 |
I have a view that consists of multiple UI elements in a HStack:
1. Time
2. Icon
3. Summary
4. Divider
5. Value
I want 1), 2) and 5) to take up no more space than necessary i.e. I don't need to intervene.
With 3) and 4) I would like for the summary to take up as much space as it needs at the expense of the divider that follows. If that means none, or a minimal amount, of the divider can appear then so be it. However, despite my best attempts, the summary only seems to take up a certain amount of space, causing its content to run over multiple lines to ensure the divider always appears. Giving it a layoutPriority helped slightly.
I don't want to give it a minWidth because I'd like for the distribution of width to be dynamically arranged based on the content.
Here's the code:
```
HStack {
// MARK: Time
HStack {
VStack {
Spacer()
Text("9am")
Spacer()
}
}.padding(.horizontal, 4)
.padding(.vertical)
.background(Color.blue.opacity(0.2))
.cornerRadius(8)
VStack {
HStack {
// MARK: Icon
Image(systemName: "cloud.drizzle.fill")
.font(Font.title2)
// MARK: Summary
VStack {
HStack {
Text("Humid and overcast")
.padding(.trailing, 2)
.background(Color.white)
.layoutPriority(100)
Spacer()
}
}
// MARK: Line
VStack {
Spacer()
Divider()
Spacer()
}
// MARK: Values
VStack {
Text(String(22.66))
Text("25%")
.foregroundColor(Color.black)
.background(Color.white)
}
Spacer()
}
}
}
```
And this is what it looks like:
[](https://i.stack.imgur.com/FeG9T.png)
As you can the text runs over multiple lines when there's enough room for it to fit on one line, as long as the divider that followed accommodated the longer text by being shorter.
|
2020/12/16
|
[
"https://Stackoverflow.com/questions/65329896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/698971/"
] |
Fixed size should be helpful here. Tested with Xcode 12.1 / iOS 14.1
[](https://i.stack.imgur.com/mC1PR.png)
```
struct TestLongHStack: View {
var body: some View {
HStack {
// MARK: Time
HStack {
VStack {
Spacer()
Text("9am")
Spacer()
}
}.padding(.horizontal, 4)
.padding(.vertical)
.background(Color.blue.opacity(0.2))
.cornerRadius(8)
VStack {
HStack {
// MARK: Icon
Image(systemName: "cloud.drizzle.fill")
.font(Font.title2)
// MARK: Summary
VStack {
HStack {
Text("Humid and overcast").fixedSize() // << here !!
.padding(.trailing, 2)
.background(Color.white)
.layoutPriority(100)
Spacer()
}
}
// MARK: Line
VStack {
Spacer()
Divider()
Spacer()
}
// MARK: Values
VStack {
Text(String(22.66)).bold().italic()
Text("25%").font(.footnote)
.foregroundColor(Color.black)
.background(Color.white)
}
Spacer()
}
}
}.fixedSize(horizontal: false, vertical: true)
}
}
```
|
65,892,665 |
The code is basically asking for the total cost of bags made for each different colour, I wanted the while loop to exit and the total printed and calculated. However I met upon a complication, It works to some extent but I want it to consistently loop until "6" is entered so it can total but it doesn't at all. I was wondering how to get it to loop the main question and exit plus total. It will loop the question, it can exit but the total is equal to a trash figure.
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int total, price, bags, colour, cost, Exit ;
printf ("********************************************\n Enter 6 to exit if you desire to do so\n");
printf ("********************************************\nEnter the colour you desire:\n 1)Black\n 2)Red\n 3)Yellow\n 4)Green\n 5)Other\n********************************************\n");
scanf("%d", &colour);
while (Exit!=6)
{
switch (colour)
{
case 1:
{
printf("Enter the number of bags you intend: ");
scanf("%d", &bags);
price=400;
cost=cost+(price*bags);
}
break;
case 2:
{
printf("Enter the number of bags you intend: ");
scanf("%d", &bags);
price=350;
cost=price*bags;
}
break;
case 3:
{
printf("Enter the number of bags you intend: ");
scanf("%d", &bags);
price=120;
cost=cost+(price*bags);
}
break;
case 4:
{
printf("Enter the number of bags you intend: ");
scanf("%d", &bags);
price=200;
cost=cost+(price*bags);
}
break;
case 5:
{
printf("Enter the number of bags you intend: ");
scanf("%d", &bags);
price=50;
cost=cost+(price*bags);
}
break;
}
printf("********************************************\n Are you complete with your purchase? If so enter 6\n");
scanf("%d", &Exit);
}
printf("The total is %d", total=total+cost);
return 0;
}
```
|
2021/01/25
|
[
"https://Stackoverflow.com/questions/65892665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15079868/"
] |
In this case, it is best to use a regular expression. Since part of your expression is dynamically generated, you need to build one using the RegExp object:
```js
const sentences = [
{ reference: "Beautiful" },
{ reference: "Is beautiful" },
{ reference: "This is beautiful and This forest is beautiful" },
];
function getSentences() {
const result = [];
for (let i = sentences.length - 1; i >= 0; --i) {
if (i - 1 >= 0) {
var regexp = new RegExp(sentences[i - 1].reference + "$", "ig");
const res = sentences[i].reference.replace(regexp, '');
result.push(res);
} else {
result.push(sentences[i].reference);
}
}
return result;
}
console.log(getSentences());
```
|
14,965,016 |
I have a savant repository in my project and I want to add all of the jars contained within the repo to IntelliJ's depenedcies list. I can add the jars one at a time, but I want to be able to add them all at once.
Is there a way to add all the jars found within all the directories/subdirectories?
***Details:** IntelliJ 12*
***Update:** I can not change the repository structure, it is auto populated when ant builds.*
|
2013/02/19
|
[
"https://Stackoverflow.com/questions/14965016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/444639/"
] |
Adding jars from a directory is supported, but not recursively, please [vote for this feature request](http://youtrack.jetbrains.com/issue/IDEA-40818).
|
150,085 |
I have a CSV file.
```
"AGNOLI Valerio","ITA","AST"
```
In this example, the 2nd column says "ITA". I expect there are about 100 or so different nationalities listed in this file. I want to know exactly how many different nationalities there are.
|
2014/08/13
|
[
"https://unix.stackexchange.com/questions/150085",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/80738/"
] |
```
cut -d ',' -f 2 filename | sort -u | wc -l
```
Basically, I am specifying the `,` as the delimiter in the `cut` command and extracting the values in the second column using `-f` flag. Now, I sort them using `sort` and the `-u` flag makes the command to list only unique values. Finally, I have the `wc -l` command to get the count of unique countries in the second column.
**Testing**
```
cat filename
jill,us,123
jack,us,345
jill,en,234
mark,en,432
kate,us,354
kane,ru,435
```
Now, after issuing the command, I get the output as,
```
cut -d ',' -f 2 filename | sort -u | wc -l
3
```
|
44,318,761 |
I'm new to VBA and have been using a piece of code to sort, remove duplicates and populate a Combobox from a certain range on my worksheet. My question is, what additions do I need to make so that I can populate another Combobox from a different Column and still have it sort.
Code I'm using is as below. As you can see I'm currently filling cboTask with information starting from B4. I want to add another range to fill another Combobox, which would be cboEquipment with information starting at D4.
```
Dim Cell As Range
Dim Col As Variant
Dim Descending As Boolean
Dim Entries As Collection
Dim Items As Variant
Dim index As Long
Dim j As Long
Dim RngBeg As Range
Dim RngEnd As Range
Dim row As Long
Dim Sorted As Boolean
Dim temp As Variant
Dim test As Variant
Dim Wks As Worksheet
Set Wks = ThisWorkbook.Worksheets("Maintenance")
Set RngBeg = Wks.Range("b4")
Col = RngBeg.Column
Set RngEnd = Wks.Cells(Rows.Count, Col).End(xlUp)
Set Entries = New Collection
ReDim Items(0)
For row = RngBeg.row To RngEnd.row
Set Cell = Wks.Cells(row, Col)
On Error Resume Next
test = Entries(Cell.Text)
If Err = 5 Then
Entries.Add index, Cell.Text
Items(index) = Cell.Text
index = index + 1
ReDim Preserve Items(index)
End If
On Error GoTo 0
Next row
index = index - 1
Descending = False
ReDim Preserve Items(index)
Do
Sorted = True
For j = 0 To index - 1
If Descending Xor StrComp(Items(j), Items(j + 1), vbTextCompare) = 1 Then
temp = Items(j + 1)
Items(j + 1) = Items(j)
Items(j) = temp
Sorted = False
End If
Next j
index = index - 1
Loop Until Sorted Or index < 1
cboTask.List = Items
```
Thank you in advance, I thought this would be as simple as copying the code and changing the dim values, but it doesn't seem to work.
|
2017/06/01
|
[
"https://Stackoverflow.com/questions/44318761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8100391/"
] |
Move your main code into a Sub with two parameters and call it on each combobox and range:
```
With ThisWorkbook.Worksheets("Maintenance")
FillComboFromRange cboTask, .Range("B4")
FillComboFromRange cboOtherOne, .Range("C4")
End With
```
Sub to fill combobox:
```
Sub FillComboFromRange(cbo As msforms.ComboBox, RngBeg As Range)
'...
'...fill your Items array starting from RngBeg
'...
cbo.List = Items '<< assign to combo
End Sub
```
|
24,409,294 |
Project link:
```
http://50.87.144.37/~projtest/team/design/AHG/brochure/#28
```
The dark grey stripe at the bottom is an anchor tag, I can't seem to figure as to why it is not clickable. The css is very simple. The parent class is `posRel` and the anchor tag is `efgLink3` and 'bg-img' is the image over which a tag is arriving.
Html:
```
<div class="container posRel">
<a class="efgLink3" target="_blank" href="http://www.efginternational.com/"></a>
<img class="bg-img" src="pages/preview/cover-back.jpg" style="height: 587px; width: 415px;">
<img class="bg-img zoom-large" src="pages/preview/cover-zoomed-back.jpg" style="height: 587px; width: 415px;">
</div>
```
Css:
```
.posRel{
min-height: 100%;
position: relative;
}
.efgLink3 {
background: none repeat scroll 0 0 #333;
display: block;
height: 70px;
left: 0;
position: absolute;
top: 79%;
width: 100%;
z-index: 11;
}
.bg-img {
left: 0;
margin-top: 10px;
max-width: 100% !important;
position: absolute;
top: 0;
z-index: 10;
}
```
|
2014/06/25
|
[
"https://Stackoverflow.com/questions/24409294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1263571/"
] |
I'm also studying about Pseudo-LRU.
Here is my understand. Hope it's helpful.
* "Hit CL1": there's a referent to CL1, and hit
LRU state (B0 and B1) are changed to inform CL1 is recently referred.
* "Hit CL0": there's a referent to CL0, and hit
LRU state (B1) is updated to inform that CL0 is recently used (than CL1)
* "Miss; CL2 replace"
There's a miss, and LRU is requested for replacement index.
As current state, CL2 is chose.
LRU state (B0 and B2) are updated to inform CL2 is recently used.
(it's also cause next replacement will be CL1)
|
131,005 |
I have a circuit which currently runs off of either a 12VDC wall wart adapter, or it falls back to a 9V battery if the wall wart adapter is not connected. My circuit currently uses a chip which requires a clean 8VDC source in order to run.
Right now, I just have an 8V LDO regulator burning off the excess power as heat, but I've just realized that my 9V cells can drop as low as 7.8, and still have 50% capacity (mAh) remaining, and my LDO requires that the supply power be at least 0.2V greater than the output voltage, or it just shuts off.
What would be the best approach to constantly having an 8V low-noise output assuming a potential input voltage swinging between 7V and 12V? My initial guess would be to use a flyback or buck-boost switching transformer, which could handle the input swing being so large and the undesired circumstances where **Vi < Vo**.
However, I can't seem to find any 8V fixed output buck-boost regulators. [Also, one thing that has me confused is that both fixed-output and variable-output regulators **both** require external components](http://www.digikey.ca/product-detail/en/LT1110CN8-12/LT1110CN8-12-ND/6796) (diode, capacitor, inductor). Why do both require external components?
|
2014/09/26
|
[
"https://electronics.stackexchange.com/questions/131005",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/45913/"
] |
>
> What would be the best approach to constantly having an 8V low-noise output assuming a potential input voltage swinging between 7V and 12V? My initial guess would be to use a flyback or buck-boost switching transformer
>
>
>
It's a good approach. A buck-boost regulator can be implemented in a small area with a minimum component count (no isolation).
>
> both fixed-output and variable-output regulators both require external components (diode, capacitor, inductor). Why do both require external components?
>
>
>
The reason is that components such as capacitors and inductors occupy too much volume when they are integrated into an IC. For this reason, they are left as external components.
|
24,394,827 |
I am trying to make my Sprite move on the screen, I have created function that should make it happen but it does not work> the problem lies in move\_ip function, but I don't know how to fix it. These are my first attempts with classes so any suggestions are welcome.
```
import pygame
pygame.init()
finish = False
white = ( 255, 255, 255)
black = (0, 0, 0)
grey = (211, 211, 211)
font = pygame.font.Font("C:/Windows/Fonts/BRITANIC.TTF", 20)
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Game")
class Sprite(object):
def __init__(self, name):
self.health = 3
self.name = name
self.points = 0
self.x = 25
self.y = 25
def printName(self):
print (self.name)
class Dog(Sprite):
def __init__(self, name):
super(Dog, self).__init__(name)
self.dog_img = pygame.image.load("dog_left.png")
self.dog_rect = self.dog_img.get_rect()
def drawDog(self, screen):
screen.blit(self.dog_img, (self.x, self.y))
def takeBone(self, sp1, sp2):
takebone = pygame.sprite.collide_rect(sp1, sp2)
if takebone == True:
self.points += 1
def moving(self):
self.player_move_x = 0
self.player_move_y = 0
self.move = self.dog_img.move_ip(player_move_x, player_move_y)
class Bone(Sprite):
def __init__(self, name):
super(Bone, self).__init__(name)
self.neme = "Bone"
self.bone = pygame.image.load("bone.png")
self.bone_rect = self.bone.get_rect()
self.x = 250
self.y = 250
def drawBone(self, screen):
screen.blit(self.bone, (self.x, self.y))
end_pos = 170
player_x = 10
player_y = 10
background = pygame.image.load("grass.png")
background_rect = background.get_rect()
size = background.get_size()
screen2 = pygame.display.set_mode(size)
player = Dog("Tom")
bone = Bone("Bone")
timer = pygame.time.Clock()
while finish == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finish = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_move_x = -5
if event.key == pygame.K_RIGHT:
player_move_x = 5
if event.key == pygame.K_UP:
player_move_y = -5
if event.key == pygame.K_DOWN:
player_move_y = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player_move_x = 0
if event.key == pygame.K_RIGHT:
player_move_x = 0
if event.key == pygame.K_UP:
player_move_y = 0
if event.key == pygame.K_DOWN:
player_move_y = 0
screen.blit(background, background_rect)
player.drawDog(screen)
bone.drawBone(screen)
pygame.display.flip()
timer.tick(25)
pygame.quit()
```
I have made changes to my code:
```
import pygame
pygame.init()
finish = False
white = ( 255, 255, 255)
black = (0, 0, 0)
grey = (211, 211, 211)
font = pygame.font.Font("C:/Windows/Fonts/BRITANIC.TTF", 20)
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Game")
class Sprite(object):
def __init__(self, name):
self.health = 3
self.name = name
self.points = 0
self.x = 25
self.y = 25
def printName(self):
print (self.name)
class Dog(Sprite):
def __init__(self, name):
super(Dog, self).__init__(name)
self.dog_img = pygame.image.load("dog_left.png")
self.dog_rect = self.dog_img.get_rect()
def drawDog(self, screen):
screen.blit(self.dog_img, (self.x, self.y))
def takeBone(self, sp1, sp2):
takebone = pygame.sprite.collide_rect(sp1, sp2)
if takebone == True:
self.points += 1
def moving(self):
self.player_move_x = 0
self.player_move_y = 0
self.move = self.dog_rect.move_ip(self.player_move_x, self.player_move_y)
class Bone(Sprite):
def __init__(self, name):
super(Bone, self).__init__(name)
self.neme = "Bone"
self.bone = pygame.image.load("bone.png")
self.bone_rect = self.bone.get_rect()
self.x = 250
self.y = 250
def drawBone(self, screen):
screen.blit(self.bone, (self.x, self.y))
background = pygame.image.load("grass.png")
background_rect = background.get_rect()
size = background.get_size()
screen2 = pygame.display.set_mode(size)
player = Dog("Tom")
bone = Bone("Bone")
timer = pygame.time.Clock()
while finish == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finish = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.player_move_x = -5
if event.key == pygame.K_RIGHT:
self.player_move_x = 5
if event.key == pygame.K_UP:
player.dog_rect.move_ip(-5, 0)
player_move_y = -5
if event.key == pygame.K_DOWN:
self.player_move_y = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
self.player_move_x = 0
if event.key == pygame.K_RIGHT:
self.player_move_x = 0
if event.key == pygame.K_UP:
player.dog_rect.move_ip(0, 0)
player_move_y = 0
if event.key == pygame.K_DOWN:
self.player_move_y = 0
screen.blit(background, background_rect)
player.drawDog(screen)
player.moving()
bone.drawBone(screen)
pygame.display.flip()
timer.tick(25)
pygame.quit()
```
|
2014/06/24
|
[
"https://Stackoverflow.com/questions/24394827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2950888/"
] |
First of all, you shouldn't name your class `Sprite`, since the name collides with the `Sprite` class of pygame.
Also, if you want to work with the `Rect` class, your classes don't need a `x` and `y` field to store its position, since you can use the `Rect` for that.
Let's look at the `moving` function:
```
self.player_move_x = 0
self.player_move_y = 0
self.move = self.dog_rect.move_ip(self.player_move_x, self.player_move_y)
```
Here you set `player_move_x` and `player_move_y` to `0`, then you want to move `dog_rect` with these values. Beside the fact that you never actually use `dog_rect` for blitting the image at the right position, moving a `Rect` by `0, 0` doesn't do anything.
There are some more errors in both code sample you've given, but your code should probably look like this (I added some comments for explanation):
```
import pygame
pygame.init()
background = pygame.image.load("grass.png")
background_rect = background.get_rect()
size = background.get_size()
# only call set_mode once
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Game")
# no need for three different classes
class MySprite(pygame.sprite.Sprite):
def __init__(self, name, img_path, pos):
super(MySprite, self).__init__()
self.name = name
self.image = pygame.image.load(img_path)
self.rect = self.image.get_rect(topleft=pos)
# use rect for drawing
def draw(self, screen):
screen.blit(self.image, self.rect)
# use rect for moving
def move(self, dir):
self.rect.move_ip(dir)
player = MySprite("Tom", "dog_left.png", (10, 10))
bone = MySprite("Bone", "bone.png", (250, 250))
timer = pygame.time.Clock()
def main():
points = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return points
# get all pressed keys
pressed = pygame.key.get_pressed()
# pressed[some_key] is 1 if the key some_key is pressed
l, r, u, d = [pressed[k] for k in pygame.K_a, pygame.K_d, pygame.K_w, pygame.K_s]
# create a tuple describing the direction of movement
# TODO: normalizing/different speed
player.move((-l + r, -u + d))
if pygame.sprite.collide_rect(player, bone):
points += 1
screen.blit(background, background_rect)
player.draw(screen)
bone.draw(screen)
pygame.display.flip()
timer.tick(25)
if __name__ == '__main__':
print main()
```
|
55,549,569 |
In my route I have one Post endpoint for which I expecting to accept the list of strings which I will then proccessing in handler.
My question is, how can I get these list of strings from ServerRequest body and iterate over them using Flux?
**My Router**
```
@Configuration
public class TestUrlRouter {
@Bean
public RouterFunction<ServerResponse> routes(TestUrlHandler handler) {
return RouterFunctions.route(
RequestPredicates.POST("/urls").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
handler::testUrls
);
}
}
```
**My handler**
```
@Component
public class TestUrlHandler {
@Autowired
private TestUrlService testUrlService;
public Mono<ServerResponse> testUrls(ServerRequest request) {
request.bodyToFlux(List.class) // how to iterate over strings?
}
}
```
|
2019/04/06
|
[
"https://Stackoverflow.com/questions/55549569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6778072/"
] |
I finally solved it by this code:
```
@Component
public class TestUrlHandler {
@Autowired
private TestUrlService testUrlService;
public Mono<ServerResponse> testUrls(ServerRequest request) {
ParallelFlux<TestUrlResult> results = request.bodyToMono(String[].class)
.flatMapMany(Flux::fromArray)
.flatMap(url -> testUrlService.testUrls(url))
.doOnComplete(() -> System.out.println("Testing of URLS is done."));
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(results, TestUrlResult.class);
}
}
```
|
276,010 |
In the [bash](https://stackoverflow.com/questions/tagged/bash "show questions tagged 'bash'") tag, we get a lot of duplicates. Off the cuff, I would speculate that 10-20% of all Bash questions are reiterations of maybe 50 common questions -- basic quoting, variables, syntax, pipelines, and everyone's favorite: the user used Notepad++ and gets weird error messages because of the MS-DOS carriage returns in the script file.
I'm looking for advice on how to proceed to rectify the situation. I'm thinking perhaps there should be additional tools for coordination / community building than Meta and chat (neither of which seem to be frequented much by the high-rep users of this particular tag) but given what we have, how would I proceed to initiate a "dupe squashing meltdown" project?
This is a sort-of meta-meta question in that I would expect a popular answer to be "start a discussion on [https://meta.stackoverflow.com/"](https://meta.stackoverflow.com/%22), but given the extensive scope, we are talking about maybe 50-100 posts on Meta, not just an individual posting; and part of the question is also, how to promote any such effort so that the stakeholders (high-rep users and others with an interest) are made aware of it? Spamming (e.g. by posting @comments summoning users who have a high score, but who might not be interested in this effort at all) hardly seems like the way to go?
I know that the [python](https://stackoverflow.com/questions/tagged/python "show questions tagged 'python'") community has a dedicated site on <http://sopython.com/> but starting to build a site on my own seems a bit odd -- I presume there was (and still is) an active Python community who are contributing to the site (otherwise it might as well be a personal web site, again with the problem of how to promote it without going out of line with spam or other shenanigans). In fact there are also a few popular Bash sites which could work as a vehicle, including the Bash wiki at <http://wiki.bash-hackers.org/doku.php> and Greg's Bash site at <http://mywiki.wooledge.org/BashGuide> but they have their own agendas and their own communities; hijacking them for this would quite possibly be unwelcome.
If the "wiki" on the SE sites was actually a proper Wiki, I think that would fit the bill perfectly, but my impression is that the site developers have no desire to take the site in that direction.
I'm asking in particular for [bash](https://stackoverflow.com/questions/tagged/bash "show questions tagged 'bash'") on <https://stackoverflow.com/> but the question is general enough to apply to all tags and all sites.
Incidentally, I have [a query](https://data.stackexchange.com/stackoverflow/query/edit/242316) (forked from [this one](https://data.stackexchange.com/stackoverflow/query/238251/most-duplicated-questions)) which doesn't really reveal some of the most popular duplicates, but should be a start. Based on the results, and my own observations over the last 3+ years, it would seem that the problem is mainly one of agreeing on a proper common duplicate.
I have collected some examples, where all the answers get high Google rank, and many are the targets of duplicate nominations; in each group, one should be made the "proper" canonical answer, and all the others (and their duplicates) should be redirected there.
Here is "use double quotes, not single, for variable interpolation", specifically in the context of using `sed` to substitute a value with another from a variable.
* [Environment variable substitution in sed](https://stackoverflow.com/questions/584894/sed-scripting-environment-variable-substitution)
* [sed substitution with Bash variables](https://stackoverflow.com/questions/7680504/sed-substitution-with-bash-variables)
* [Replace a text with a variable](https://stackoverflow.com/questions/16297052/replace-a-text-with-a-variable-sed)
* [how to use sed to replace a string in a file with a shell variable](https://stackoverflow.com/questions/15230020/how-to-use-sed-to-replace-a-string-in-a-file-with-a-shell-variable) (with a variation in the misunderstanding)
* [Sed replacement not working when using variables](https://stackoverflow.com/questions/5156293/sed-replacement-not-working-when-using-variables) [duplicate]
* [Use a variable in a sed command](https://stackoverflow.com/questions/11146098/bash-use-a-variable-in-a-sed-command)
* [Using variable inside of sed -i (regex?) bash](https://stackoverflow.com/questions/19252880/using-variable-inside-of-sed-i-regex-bash) (not substitution)
* [bash : sed : regex in variable](https://stackoverflow.com/questions/13913382/bash-sed-regex-in-variable) (variation in misunderstanding)
Here is a related, but distinct group (the twist is that the variable value contains a slash).
* [sed substitution with Bash variables](https://stackoverflow.com/questions/7680504/sed-substitution-with-bash-variables)
* [In bash how to replace string variable, and set it into sed command](https://stackoverflow.com/questions/19647982/in-bash-how-to-replace-string-variable-and-set-it-into-sed-command)
* [SED substitution for variable](https://stackoverflow.com/questions/3712001/sed-substitution-for-variable)
* [Sed in Bash script - replace error cause of variable content](https://stackoverflow.com/questions/19283947/sed-in-bash-script-replace-error-cause-of-variable-content)
So my question is decidedly *not* "how can I personally decide which one of these" but rather, how can we together, as a community, decide which one of these, and a number of fifty-odd other similar groups, *then* proceed individually to actually do something about the problem?
|
2014/11/04
|
[
"https://meta.stackoverflow.com/questions/276010",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/874188/"
] |
>
> I'm looking for advice on how to proceed to rectify the situation. I'm thinking perhaps there should be additional tools for coordination / community building than Meta and chat (neither of which seem to be frequented much by the high-rep users of this particular tag) but given what we have, how would I proceed to initiate a "dupe squashing meltdown" project?
>
>
>
In all honesty? **Just do it.**
The problems with these initiatives is to get people to actually go through all the trouble and create canonical questions. When Felix did it with some questions in the JS tag - for example [this question](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call), it was *very* welcome.
The hardest part in these is execution - if you get to a point you have a solid and clear question and a good answer right. You've done this site a great service and you should definitely proceed.
While there is a "chance for exploit" here with rep gain - I'm yet to see people argue or fight about canonizing a question since it's so important. If you want collaborative help you can ask for the question to get a collaborative effort lock.
We need more people willing to pick up this glove.
|
7,174,611 |
I need to create a file under the "/Library/Preferences/" Mac directory. But in Lion only root user have write privilege to this dir.
```
#include <stdio.h>
int main()
{
FILE *fileHandle = NULL;
fileHandle = fopen("/Library/Preferences/v.test", "w");
fclose(fileHandle);
return 0;
}
```
this line of code works if I run this code as `sudo ./a.out`. I wants to do the same programmatically.
Thanks!
|
2011/08/24
|
[
"https://Stackoverflow.com/questions/7174611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571156/"
] |
can you set the executable to setuid? Just `chown` it to `root` and `chmod u+s`.
|
55,376,802 |
I am learning at `Numpy` and I want to understand such shuffling data code as following:
```
# x is a m*n np.array
# return a shuffled-rows array
def shuffle_col_vals(x):
rand_x = np.array([np.random.choice(x.shape[0], size=x.shape[0], replace=False) for i in range(x.shape[1])]).T
grid = np.indices(x.shape)
rand_y = grid[1]
return x[(rand_x, rand_y)]
```
So I input an `np.array` object as following:
```
x1 = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]], dtype=int)
```
And I get a output of `shuffle_col_vals(x1)` like comments as following:
```
array([[ 1, 5, 11, 15],
[ 3, 8, 9, 14],
[ 4, 6, 12, 16],
[ 2, 7, 10, 13]], dtype=int64)
```
I get confused about the initial way of `rand_x` and I didn't get such way in [numpy.array](https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html)
And I have been thinking it a long time, but I still don't understand why `return x[(rand_x, rand_y)]` will get a shuffled-rows array.
If not mind, could anyone explain the code to me?
Thanks in advance.
|
2019/03/27
|
[
"https://Stackoverflow.com/questions/55376802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5574794/"
] |
You are just sending the value of the array to the execute function. Send the key and the value in an array:
```
$a = array('avocado', 'apple', 'banana');
$b = array('green', 'red', 'yellow');
$c = array_combine($a, $b);
print_r($c);
$stmt = $pdo->prepare("INSERT INTO fruits (name, color) VALUES (?,?)");
try {
$pdo->beginTransaction();
foreach ($c as $name => $color)
{
$stmt->execute( [ $name, $color ] );
}
$pdo->commit();
}catch (Exception $e){
$pdo->rollback();
throw $e;
}
```
|
51,308,967 |
I have a bit of confusion with the following expression. Here it is:
```
char a = 'D';
int b = 5;
System.out.println(a++/b+--a*b++);
```
I am trying to solve it in the following way:
1. `('D'/b+--a*b++);`
Behind the scenes, `a = 'E'`
2. `'D'/b+'D'*b++;`
3. `'D'/b + 'D' * 5;`
Behind the scenes `b` value is incremented to 6, `b = 6`
4. `'D'/6 + 'D' *5;`
5. `11 + 'D' * 5;`
6. `11 + 345`
Since 'D' value is 69 in ASCII
7. `356`
But the compiler gives the output as 353. What is the mistake which I am doing it here?
|
2018/07/12
|
[
"https://Stackoverflow.com/questions/51308967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1400915/"
] |
What you are calculating is
```
(a++ / b) + (--a * b++)
```
In this [expression](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html), `--a` cancels the `a++`: *After* the division `a` has the value `E`, but *before* the multiplication it again has the value `D`. Post increment and pre decrement cancel each other. So the first operand for `/` and `*` each is `'D'` which is `68`. The post increment `b++` has no effect on the expression. So you do
```
(68 / 5) + (68 * 5)
```
which is `353` using integer rounding.
**Edit:** In detail, this is what happens:
```
char a = 'D';
int b = 5;
int divisonResult = a / b;
// a++ and --a cancel each other.
a++; // The incrementation of a happens after the divison.
--a; // The decrementation of a happens before the multiplication.
// Now a is back to 'D'.
int multiplicationResult = a * b;
b++; // This has no effect since b takes no part in the last step:
int additionResult = divisonResult + multiplicationResult;
```
|
317,925 |
I run Windows XP for occasional .Net dev and other downloads that are Win specific in VirtualBox 4.1 on top of a Ubuntu 11.04 host. I dont want to burden the guest with active Anti Virus. Is there any effective solutions for scanning from the host nightly, i.e. reading the vdmk presuming the guest file system is unencrypted? Is this as effective? Parts of me things probably more effective than in-guest scanning due no rootkits being able to alter scanning behavior?
|
2011/08/02
|
[
"https://superuser.com/questions/317925",
"https://superuser.com",
"https://superuser.com/users/39185/"
] |
Try updating your video driver to the latest version from [Nvidia](http://www.nvidia.com/Download/index.aspx?lang=en-us) or [AMD/ATI](http://support.amd.com/us/gpudownload/Pages/index.aspx) depending on which you have in your computer.
|
65,899,633 |
I want to upload a pdf from jspdf to my server.
I use Ajax for it.
I open the Javascript by a function in my form.
>
> onsubmit="pdferzeugen();"
>
>
>
above the ajax code i create the pdf by "jspdf" and save it to a datauri (base64).
**Javascript:**
```
var datauri = pdf.output('datauri');
var data = new FormData();
data.append("pdf_data", datauri);
$.ajax({
url: "./uploads/upload.php",
type: "POST",
processData: false,
contentType: false,
data: data,
});
```
**upload.php:**
```
if(!empty($_POST['pdf_data'])){
$data = $_POST['pdf_data'];
$fname = "test.pdf"; // name the file
$file = fopen("./uploads/" .$fname, 'w'); // open the file path
fwrite($file, $data); //save data
fclose($file);
}
```
But this isnt working for me.
Chrome always say:
>
> jquery.min.js:9600 XHR failed loading: POST "http://app-her-visitor/begehung/uploads/upload.php".
>
>
>
I searched whole google for this error, but no success.
I hope you can help me :-)
Thanks for help
Greetings
|
2021/01/26
|
[
"https://Stackoverflow.com/questions/65899633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15083176/"
] |
Why do you even need `b`?
```
def my_function(n, condition):
a = 1
for _ in range(n):
a += 1
if condition:
a += 2
return a
```
---
If all you want is to avoid PyCharm's warning, please it by setting a default value for `b`. As I understand your code, it will not be used anyway, this is just to silence the warning:
```py
def my_function(n, condition):
a = 1
b = None
if condition:
b = 2
[...]
```
---
Lastly, assuming you only access `b` under `if condition:` blocks, then there is no need to conditionally assign it in the first place. You can set it to the desired value, and you will only use it when needed:
```py
def my_function(n, condition):
a = 1
b = 2
for _ in range(n):
a += 1
if condition:
a += b
```
|
539,905 |
OK, so here's the scenario:
We have an environment with Exchange 2013 running on Windows Server 2012 (including the DC). Current users can access their emails through outlook and OWA.
However, whenever I try to configure a second Exchange account on a computer on the internal network, I get an error (it's quite random, one says there's a problem with the OST file, the other says it couldn't load the information store). When I try to configure an Exchange account on my mac (NOT on the internal network) it works perfectly with mail.app. When I try to do the same for my Windows PC (remote as well) it can't check the username...
All laptops on the internal network are connected through a switch to the server. No firewall or router is present between them AFAIK, so I think we can rule out a networking issue. Anyone have a clue what might be going on here?
|
2013/09/18
|
[
"https://serverfault.com/questions/539905",
"https://serverfault.com",
"https://serverfault.com/users/139117/"
] |
Not saying DanBig's answer isn't valid...but:
1. In this particular scenario, why not simply set forwarding on the mailbox of the employee that is leaving (in the EAC): <http://technet.microsoft.com/en-us/library/dd351134%28v=exchg.150%29.aspx> and possibly set an OOF auto-reply as well stating that "I'm no longer with the company, direct all email to [email protected] now."
2. If you really want "new employee" to have access to "old employee" mailbox, again it's easier in the EAC to simply give "new employee" full access permissions <http://technet.microsoft.com/en-us/library/bb124097%28v=exchg.150%29.aspx> and then in Outlook it will automatically show the additional mailbox on the left window pane (after a restart of Outlook)
|
37,823,875 |
I am new to ruby on rails development. I am currently having difficulties generating a new rails controller. here is what I input into the terminal:
```
$ rails generate controller static_pages home help
```
here is the response I receive:
```
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/connection_specification.rb:177
:in `rescue in spec': Specified 'sqlite3' for database adapter, but the gem is not loaded.
Add `gem 'sqlite3'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). (Gem::LoadError)
```
I am also using Heroku for production so I initially removed sqlite3 because Heroku cant use it by doing:
```
$ gem uninstall sqlite3
```
and I removed it from my gemfile and gemfile.lock. Was this a mistake? Any guidance would be much appreciated.
|
2016/06/14
|
[
"https://Stackoverflow.com/questions/37823875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6466923/"
] |
I found a solution
```
'variations' => array(
array(
'sku' => date('His').'_1',
'regular_price' => '29.98',
'attributes' => array(
array(
'id' => date('YmdHis', strtotime('+2 seconds')),
'slug'=>'color',
'name'=>'color',
'option'=>'red'
)
)
),
array(
'sku' => date('His').'_2',
'regular_price' => '29.98',
'attributes' => array(
array(
'id' => date('YmdHis'),
'slug'=>'color',
'name'=>'color',
'option'=>'black'
)
)
)
)
```
works for me if color attribute and red,black values exist.
You have to use `id`
|
190,296 |
What are the best practices for modeling inheritance in databases?
What are the trade-offs (e.g. queriability)?
(I'm most interested in SQL Server and .NET, but I also want to understand how other platforms address this issue.)
|
2008/10/10
|
[
"https://Stackoverflow.com/questions/190296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73794/"
] |
There are several ways to model inheritance in a database. Which you choose depends on your needs. Here are a few options:
**Table-Per-Type (TPT)**
Each class has its own table. The base class has all the base class elements in it, and each class which derives from it has its own table, with a primary key which is also a foreign key to the base class table; the derived table's class contains only the different elements.
So for example:
```
class Person {
public int ID;
public string FirstName;
public string LastName;
}
class Employee : Person {
public DateTime StartDate;
}
```
Would result in tables like:
```
table Person
------------
int id (PK)
string firstname
string lastname
table Employee
--------------
int id (PK, FK)
datetime startdate
```
**Table-Per-Hierarchy (TPH)**
There is a single table which represents all the inheritance hierarchy, which means several of the columns will probably be sparse. A discriminator column is added which tells the system what type of row this is.
Given the classes above, you end up with this table:
```
table Person
------------
int id (PK)
int rowtype (0 = "Person", 1 = "Employee")
string firstname
string lastname
datetime startdate
```
For any rows which are rowtype 0 (Person), the startdate will always be null.
**Table-Per-Concrete (TPC)**
Each class has its own fully formed table with no references off to any other tables.
Given the classes above, you end up with these tables:
```
table Person
------------
int id (PK)
string firstname
string lastname
table Employee
--------------
int id (PK)
string firstname
string lastname
datetime startdate
```
|
961,874 |
I am a bit confused about the exact statement of the Radon-Nikodym Theorem. Suppose that in the usual setup, $v \ll u$. Does it require **both $v$ and $u$** to be sigma-finite, or **only $u$** to be sigma finite for the theorem to hold?
|
2014/10/07
|
[
"https://math.stackexchange.com/questions/961874",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/21617/"
] |
You need both measures to be $\sigma$-finite. Suppose you have the collection of Lebesgue measurable sets on $[0,1]$ and let $\mu$ be the counting measure. The only set of measure zero with respect to $\mu$ is the empty set, so every measure is absolutely continuous with respect to $\mu$ and you can show that there is no nonnegative Lebesgue measurable function $f$ on $[0,1]$ for which
$$
m(E)=\int\_Ef\,d\mu
$$
where $E$ is any Lebesgue measurable set on $[0,1]$.
|
69,246,931 |
Note that this is referred to **make** a project from command prompt, not build or run it, by "make", i mean, creating a *.vcxproj* file like Visual Studio does.
I am unable to use Visual Studio for now, this is why i'm asking to make a project through cmd, i tried gcc, but it doesn't generate these project stuff.
|
2021/09/19
|
[
"https://Stackoverflow.com/questions/69246931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14373455/"
] |
The `vcxproj` format provides information the MSBuild tool to control the build process. It's an XML file that is automatically created by Visual Studio, but its possible to make it manually by writing the XML yourself, and then specifying the file when invoking MSBuild from the cmd prompt.
See [this walkthrough](https://learn.microsoft.com/en-us/cpp/build/walkthrough-using-msbuild-to-create-a-visual-cpp-project?view=msvc-160) in the MS docs, and [this reference](https://learn.microsoft.com/en-us/cpp/build/reference/vcxproj-file-structure?view=msvc-160) to the vcxproj format if you want it to work when you regain access to VS.
Alternatively, if you're not absolutely required to use Visual Studio and the Visual C++ ecosystem, then it might be worth exploring other build systems as suggested in other answers/comments.
|
44,748,128 |
I've got UITableViewController with UISearchController in the navigation's item title view. I want to make keyboard dismiss on tap anywhere in table view. How to make it?
This is my code so far:
```
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
class TableViewController: UITableViewController, UISearchResultsUpdating {
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
navigationItem.titleView = searchController.searchBar
}
func updateSearchResults(for searchController: UISearchController) {
//
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 40
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath)
cell.textLabel?.text = "test1"
return cell
}
}
```
|
2017/06/25
|
[
"https://Stackoverflow.com/questions/44748128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7141402/"
] |
You could use the body element itself for checking the elements and use a max variable to store the local max depth.
The recusion function need a `level` parameter, which is incremented for evey nested level. If no more children are found, `max` is adjusted, if necessary.
```js
function recursion (data, level) {
var i;
if (data.children.length > 0) {
for (i = 0; i < data.children.length; i++) {
recursion(data.children[i], level + 1);
}
} else {
if (level > max) {
max = level;
}
}
}
var max = 0;
recursion(document.body, 0);
console.log(max);
```
```html
<div><div><div><div><div><div></div></div></div></div></div></div><div><div><div><div></div></div></div><div><div><div><div><div><div></div></div></div></div><div><div><div></div></div></div></div></div></div>
```
Another approach without a level counter
```js
function getDepth(data) {
return +data.children.length && (1 + Math.max.apply(Math, [].map.call(data.children, getDepth)));
}
console.log(getDepth(document.body));
```
```html
<div><div><div><div><div><div></div></div></div></div></div></div><div><div><div><div></div></div></div><div><div><div><div><div><div></div></div></div></div><div><div><div></div></div></div></div></div></div>
```
|
58,486,299 |
It looks like you can use the to in so the router link extends. I want to make the link to the the front page. does not work and wrapping in changes the formatting. How can I make <-v-toolbar-title> link without changing the formatting? Thanks!
|
2019/10/21
|
[
"https://Stackoverflow.com/questions/58486299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4913436/"
] |
*There is a perfect way to handle this situation.*
>
> Use click event handler to navigate to the front page
>
>
>
**Just replace your v-toolbar-title code with the following code.**
```
<v-toolbar-title @click="$router.push('/')" class="headline text-uppercase" >
<span class="display-1 text-uppercase font-weight-medium">Company </span>
<span class="display-1 text-uppercase font-weight-light">Associates</span>
</v-toolbar-title>
```
>
> This way its very clean without adding any external css or additional
> button component just by adding this "$router.push('/')" to @click
> event handler
>
>
>
|
23,119,887 |
In Bash, converting the contents of a variable `A` can be achieved by `${A,,}`. In a Makefile, this doesn't work anymore. The following code
```
default:
@for i in a b CCC; do \
echo $${i,,}; \
done
```
yields the error
```
$ make
/bin/sh: 2: Bad substitution
make: *** [default] Error 2
```
How can you convert a variable in a Makefile to lower case?
|
2014/04/16
|
[
"https://Stackoverflow.com/questions/23119887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/353337/"
] |
The syntax for calling a pointer to member function is rather atrocious. Here's the correct syntax:
```
if ((targets[0]->*(targets[0]->OnFire))() == true)
```
That is downright ugly. This is why the [Parashift C++ FAQ page on calling pointers to member functions](http://www.parashift.com/c++-faq/macro-for-ptr-to-memfn.html) recommends defining a macro for this purpose -- and note that the author of those pages dislikes macros.
```
#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))
...
if (CALL_MEMBER_FN(*targets[0],targets[0]->OnFire)() == true)
```
Either use a macro or use a `std::function` as described in sehe's answer.
|
52,097,842 |
I am having a very difficult time trying to connect my computer to a domain I setup in a azure VM. I have spent several days googling for answers and still unable to join. I am not that familiar with networking so hoping one of you can guide me in the right direction. I am using a point to site vpn. I can ping the AD server via IP but not by host name. When I try to join the domain I get this error:
>
> The query was for the SRV record for \_ldap.\_tcp.dc.\_msdcs.xxxx.local
>
>
> Common causes of this error include the following:
>
>
> * The DNS SRV records required to locate a AD DC for the domain are not registered in DNS. These records are registered with a DNS server
> automatically when a AD DC is added to a domain. They are updated by
> the AD DC at set intervals. This computer is configured to use DNS
> servers with the following IP addresses:
>
>
> 192.168.250.6 (IP of AD server).
>
>
>
ipconfig /all of client machine:
>
>
> ```
> Ethernet adapter Ethernet:
>
> Connection-specific DNS Suffix . : hsd1.nj.net
> Description . . . . . . . . . . . : Intel(R) Ethernet Connection (2) I219-LM
> Physical Address. . . . . . . . . : C8-5B-76-D0-FA-4D
> DHCP Enabled. . . . . . . . . . . : Yes
> Autoconfiguration Enabled . . . . : Yes
> IPv4 Address. . . . . . . . . . . : 192.168.1.119(Preferred)
> Subnet Mask . . . . . . . . . . . : 255.255.255.0
> Lease Obtained. . . . . . . . . . : Tuesday, August 28, 2018 4:33:23 PM
> Lease Expires . . . . . . . . . . : Friday, August 31, 2018 8:27:41 AM
> Default Gateway . . . . . . . . . : 192.168.1.1
> DHCP Server . . . . . . . . . . . : 192.168.1.1
> DNS Servers . . . . . . . . . . . : 192.168.1.1
> NetBIOS over Tcpip. . . . . . . . : Enabled
>
> PPP adapter b2wise-vnet-weu:
>
> Connection-specific DNS Suffix . :
> Description . . . . . . . . . . . : xxx-vnet-weu
> Physical Address. . . . . . . . . :
> DHCP Enabled. . . . . . . . . . . : No
> Autoconfiguration Enabled . . . . : Yes
> IPv4 Address. . . . . . . . . . . : 192.168.252.2(Preferred)
> Subnet Mask . . . . . . . . . . . : 255.255.255.255
> Default Gateway . . . . . . . . . :
> NetBIOS over Tcpip. . . . . . . . : Enabled
>
> ```
>
>
ipconfig /all of ad server
```
Ethernet adapter Ethernet 2:
Connection-specific DNS Suffix . : eypda44s54judkzq3onclf52qb.ax.internal.cloudapp.net
Description . . . . . . . . . . . : Microsoft Hyper-V Network Adapter #2
Physical Address. . . . . . . . . : 00-0D-3A-44-50-8B
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
IPv4 Address. . . . . . . . . . . : 192.168.250.6(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Lease Obtained. . . . . . . . . . : Thursday, August 30, 2018 12:32:05 PM
Lease Expires . . . . . . . . . . : Sunday, October 6, 2154 7:29:42 PM
Default Gateway . . . . . . . . . : 192.168.250.1
DHCP Server . . . . . . . . . . . : 168.63.129.16
DNS Servers . . . . . . . . . . . : 127.0.0.1
NetBIOS over Tcpip. . . . . . . . : Enabled
```
I tried making the client pc's dns have only the ip of the ad server and when I do that I cant access the internet or the network.
Thank you for your help and patience!
|
2018/08/30
|
[
"https://Stackoverflow.com/questions/52097842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5782026/"
] |
It seems to be like a DNS misconfiguration. I think that you should look at your VNet configuration.
This [link](https://learn.microsoft.com/en-us/azure/dns/private-dns-overview) might be helpful.
And also, I want to remind you that you need a Site-to-Site VPN to have a computer joined in domain on cloud.
But, also Azure offers more solutions to have a Domain Controller on Azure this called Azure Active Directory Domain Services (Managed Domain) which does not require VPN connection.
[Azure Active Directory Domain Services (Managed Domain)](https://cloudopszone.com/azure-active-directory-domain-services-managed-domain/)
|
71,215,408 |
I have (2) div elements displayed as `inline-block`'s.
I'm attempting to make the second div container that is wrapped around a `<p>` element extend to the width of the screen. Not sure how to accomplish this.
Ideally, the red container will stretch to the edge of the screen to the right.
```html
<div style="background-color: grey; width:16px; display: inline-block;">
<p>-</p>
</div>
<div style="background-color: red; display: inline-block;">
<p>Test Text</p>
</div>
```
|
2022/02/22
|
[
"https://Stackoverflow.com/questions/71215408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17706352/"
] |
You could try this.
```
authors = ','.join(df['authors'].to_list())
with open('mycsv.csv', 'w', newline='') as myfile:
myfile.write(authors)
```
|
52,331,728 |
Need to move versioned files having a filename starting with certain chars
eg: I have to move files with filenames starting with "CQ" to a certain folder
But the source folder consists of versioned files like
```
cq72761.xxx.2
cq72762.xxx.3
cq73237hhh1.xyz.1
cq73237hhh1.xxx.5
cq73237hhh2.xyz.1
cq73237hhh2.xxx.5
cq73238hhhh.xyz.1
cq73238hhhh.xxx.5
```
I am getting error as below

Any help would be appreciated.
|
2018/09/14
|
[
"https://Stackoverflow.com/questions/52331728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10363582/"
] |
Well its an optional parameter.As its a callback you can pass a function as parameter to be called when the component has rendered or updated
```
ReactDOM.render(<App />, document.getElementById('root'),()=>{
console.log("rendered the root componnet");
});
```
|
45,280,547 |
I have an aspect that handles all methods that have a custom annotation.
The annotation has an enum parameter and I have to get the value in the aspect:
```
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Monitored {
MonitorSystem monitorSystem();
}
```
My case is very similar to that [question](https://stackoverflow.com/questions/21275819/how-to-get-a-methods-annotation-value-from-a-proceedingjoinpoint) and the accepted answer works for Spring beans that do not implement an interface.
The aspect:
```
@Aspect
@Component
public class MonitorAspect {
@Around("@annotation(com.company.project.monitor.aspect.Monitored)")
public Object monitor(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature signature = (MethodSignature) pjp.getSignature();
MonitorSystem monitorSystem = signature.getMethod().getAnnotation(Monitored.class).monitorSystem();
...
}
}
```
But if the Spring bean that is annotated with `@Monitored` (only the implementation class is annotated) implements an interface - `pjp.getSignature()` returns the signature of the interface and it does not have an annotation.
This is OK:
```
@Component
public class SomeBean {
@Monitored(monitorSystem=MonitorSystem.ABC)
public String someMethod(String name){}
}
```
This does not work - pjp.getSignature() gets the signature of the interface.
```
@Component
public class SomeBeanImpl implements SomeBeanInterface {
@Monitored(monitorSystem=MonitorSystem.ABC)
public String someMethod(String name){}
}
```
Is there a way to get the signature of the implementation method from ProceedingJoinPoint?
|
2017/07/24
|
[
"https://Stackoverflow.com/questions/45280547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383087/"
] |
Managed to do it with:
```
@Aspect
@Component
public class MonitorAspect {
@Around("@annotation(com.company.project.monitor.aspect.Monitored)")
public Object monitor(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = pjp.getTarget()
.getClass()
.getMethod(signature.getMethod().getName(),
signature.getMethod().getParameterTypes());
Monitored monitored = method.getAnnotation(Monitored.class);
...
}
}
```
|
64,967,154 |
I'm trying to run a basic HelloWorld express app on my localhost using docker.
**Docker version:** `Docker version 19.03.13`
**Project structure:**
```
my-project
src
index.js
Dockerfile
package.json
package-lock.json
```
**Dockerfile**:
```
# Use small base image with nodejs 10
FROM node:10.13-alpine
# set current work dir
WORKDIR /src
# Copy package.json, packge-lock.json into current dir
COPY ["package.json", "package-lock.json*", "./"]
# install dependencies
RUN npm install --production
# copy sources
COPY ./src .
# open default port
EXPOSE 3000
# Run app
CMD ["node", "index.js"]
```
**package.json**
```
{
"name": "knative-serving-helloworld",
"version": "1.0.0",
"description": "Simple hello world sample in Node",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "",
"license": "Apache-2.0",
"dependencies": {
"express": "^4.16.4"
},
}
```
**index.js**
```
const express = require('express');
const app = express();
app.get('/', (req, res) => {
console.log('Hello world received a request.');
res.send(`Hello world!\n`);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log('Hello world listening on port', port);
});
```
Here are the commands I'm running:
```
>> docker build --tag hello-world:1.0 . // BUILD IMAGE AND GET ID
>> docker run IMAGE_ID // RUN CONTAINER WITH IMAGE_ID
```
Image seems to build just fine:
[](https://i.stack.imgur.com/sXq2R.png)
And this is the result after I run the image:
[](https://i.stack.imgur.com/YKV99.png)
But this is what I get when I hit `localhost:3000`
[](https://i.stack.imgur.com/clXPE.png)
I'm very new to Docker. What am I doing wrong?
|
2020/11/23
|
[
"https://Stackoverflow.com/questions/64967154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10128619/"
] |
You need to publish your port 3000.
`docker run -p 3000:3000 IMAGE_ID`
Just exposing the port is not enough it needs to be mapped on the host's port too.
|
48,045,457 |
I'm trying to write a code that group everything by organization/corporate number,
but I get an error. Can anyone see what the reason is for the error?
The data looks like:
[](https://i.stack.imgur.com/X8N0t.png)
This is the code
```
select *, Differens = (nullif(Intrastat,0)-Moms)/ nullif(moms,0)
from
#Tabell1
Group by Orgnr
order by Orgnr, MΓ₯nad
```
The error i get is the following:
```
Msg 8120, Level 16, State 1, Line 23 Column '#Tabell1.Tillnr' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
```
|
2017/12/31
|
[
"https://Stackoverflow.com/questions/48045457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6692758/"
] |
if your input is always like that you can use `regex` to extract the values and insert them into a dictionary:
```
import re
dic = {}
input = 'item SHIRT 11-14 variance 11-12-13-14-15 color Red'
dic['Shirt Type'] = re.search('(?<=SHIRT\s)[\d-]+', input).group().split('-')
dic['Variance'] = re.search('(?<=variance\s)[\d-]+', input).group().split('-')
dic['Color']= re.search('(?<=color\s)\w+', input).group().split('-')
print(dic)
```
the result will be a dictionary with 3 `keys` and each `value` will be an array (size of array depends on the input and the number of the `-` in it) for example this is the result of your input:
```
{'Shirt Type': ['11', '14'], 'Variance': ['11', '12', '13', '14', '15'], 'Color': ['Red']}
```
|
6,377,894 |
I have been trying to make my website performs well. One way that may achieve this is by including a loader like LAB.js script inline within my HTML, and then load my scripts in parallel in the next line.
So, inside LAB.js library that contains a bunch of codes, there is this particular line of code`{var c=/^\w+\:\/\//,d;if(typeof a!=q)`. When I put that piece of code inline inside the script tag of my HTML, it works well both In mozilla and chrome..but then..it fails in this browser called internet explorer 8 built by this great software company called "microsoft".
take a look at the part where there is `"\/\//"`. Those last two characters "//" are parsed without any problem in both mozilla and chrome. However in IE, the last two characters are parsed as comment operators, therefore, any codes after those last two lines are rendered as comments (useless). This is really unbelievable. In IE, the rest of the codes after those two characters are literally useless and green colored (as in comment) Have anyone seen this issue happening before? Pls help. thanks.
In Mozilla and chrome: (last two characters)"//"`,d;if(typeof a!=q)`
In IE: `//,d;if(typeof a!=q)`
|
2011/06/16
|
[
"https://Stackoverflow.com/questions/6377894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/711926/"
] |
You could surround your regex with `(?:...)`:
```
c=/(?:^\w+\:\/\/)/,d;if(typeof a!=q)
```
|
40,786,438 |
I have a string that contains an array like:
```
$tarray = Array ( [gt_ref_id] => 36493115 [tender_notice_type] => [organisation_name] => ROSALES WATER DISTRICT [address] => No. 5 Bonifacio Street [address2] => [contact_person] => [tender_notice_no] => ROSALWD 2016-011-0144(Ref: 4206661)
)
```
but I want to access the value of this array like:
```
echo "ref id = ".$tarray['gt_ref_id'];
```
It should output like:
```
ref id = 36493115
```
but I can't because it's a string. I could if it was an array.
How can I convert the string to a proper PHP array?
|
2016/11/24
|
[
"https://Stackoverflow.com/questions/40786438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300259/"
] |
You can use [PyFormat](https://pyformat.info/#string_pad_align) to do this with padding and align options.
```
In [120]: p1 = 1
In [121]: p2 = 123
In [122]: p3 = 12345
In [123]: print "** BaseHP = " + '{:10}'.format(str(p1)) + '*'
In [124]: print "** BaseHP = " + '{:10}'.format(str(p2)) + '*'
In [125]: print "** BaseHP = " + '{:10}'.format(str(p3)) + '*'
```
OUTPUT:
```
** BaseHP = 1 *
** BaseHP = 123 *
** BaseHP = 12345 *
```
Though the len of variable changes the overall alignment remains same.
|
24,161,405 |
i have using one **div** to display a image. the **id** name of the div is **first**, i gave both background image and hover image using css. now i have to hover an first div image when hovering an another div.
here below the example
**`<div id="first"></div>`**
default background image of first div is - bgimg.jpg
The hover image of first div is - hoverbgimg.jpg
THE ANOTHER DIV IS **`<div id="second"></div>`**
here when i am **hovering second div** the **first div image should be change**.
|
2014/06/11
|
[
"https://Stackoverflow.com/questions/24161405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717611/"
] |
This cannot be done through CSS only.
Add below JS code in Js file
```
$(document).ready(function(){
$("#second").on("hover", function(){
$("first").css("background", "imagename.jpg");
});
});
```
Dont forget to include jquery file first.
|
28,606,124 |
i am trying to compute time intervals per day from a list of unix timestamps in Python. I have searched for simular questions on stack overflow but mostly found examples of computing deltas or SQL solutions.
I have a list of the sort:
```
timestamps = [1176239419.0, 1176334733.0, 1176445137.0, 1177619954.0, 1177620812.0, 1177621082.0, 1177838576.0, 1178349385.0, 1178401697.0, 1178437886.0, 1178926650.0, 1178982127.0, 1179130340.0, 1179263733.0, 1179264930.0, 1179574273.0, 1179671730.0, 1180549056.0, 1180763342.0, 1181386289.0, 1181990860.0, 1182979573.0, 1183326862.0]
```
I can easily turn this list of timestamps into datetime objects using:
```
[dt.datetime.fromtimestamp(int(i)) for i in timestamps]
```
From there I can probably write quite a lengthy code where the first day/month is kept and a check is done to see if the next item in the list is of the same day/month. If it is I look at the times, get the first and last from the day and store the interval + day/month in a dictionary.
As I am fairly new to Python I was wondering what is the best way to do this in this programming language without the abusive use of if/else statements.
Thank you in advance
|
2015/02/19
|
[
"https://Stackoverflow.com/questions/28606124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3104960/"
] |
You can use [`collections.defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict). It's amazingly handy when you're trying to build a collection without inital estimates on size and members.
```
from collections import defaultdict
# Initialize default dict by the type list
# Accessing a member that doesn't exist introduces that entry with the deafult value for that type
# Here, when accessing a non-existant member adds an empty list to the collection
intervalsByDate = defaultdict(list)
for t in timestamps:
dt = dt.datetime.fromtimestamp(t)
myDateKey = (dt.day, dt.month, dt.year)
# If the key doesn't exist, a new empty list is added
intervalsByDate[myDateKey].append(t)
```
From this, `intervalsByDate` is now a `dict` with values as a list timestamps sorted based on the calendar dates. For each date you can sort the timestamps and get the total intervals. Iterating the `defaultdict` is identical to a `dict` (being a sub-class of `dict`s).
```
output = {}
for date, timestamps in intervalsByDate.iteritems():
sortedIntervals = sorted(timestamps)
output[date] = sortedIntervals[-1] - sortedIntervals[0]
```
Now `output` is a map of dates with intervals in miliseconds as the value. Do with it as you will!
---
**EDIT**
>
> Is it normal that the keys are not ordered? I have keys from different months mixed togheter.
>
>
>
Yes, because (hash)maps & `dicts` [are essentially unordered](https://docs.python.org/3/library/stdtypes.html#typesmapping)
>
> How would I be able to, for example, select the first 24 days from a month and then the last
>
>
>
If I was very adamant on my answer, I'd maybe look at [this, which is an Ordered default dict.](https://stackoverflow.com/questions/6190331/can-i-do-an-ordered-default-dict-in-python). However, you could modify the datatype of `output` to something which isn't a `dict` to fit your needs. For example a `list` and order it based on dates.
|
35,837,369 |
I am installing opentaps on my system and error is-
```
[java] 2016-03-07 11:32:37,428 (main) [ TransactionUtil.java:345:INFO ] [TransactionUtil.rollback] transaction rolled back
[java] 2016-03-07 11:32:37,428 (main) [ EntityDataLoader.java:218:ERROR]
[java] ---- exception report ----------------------------------------------------------
[java] [install.loadData]: Error loading XML Resource "file:/home/oodles/work/skulocity/custom-erp-crm/opentaps/amazon/data/AmazonDemoSetup.xml"; Error was: A transaction error occurred reading data
[java] Exception: org.xml.sax.SAXException
[java] Message: A transaction error occurred reading data
[java] ---- cause ---------------------------------------------------------------------
[java] Exception: org.ofbiz.entity.GenericDataSourceException
[java] Message: SQL Exception occurred on commit (Commit can not be set while enrolled in a transaction)
[java] ---- cause ---------------------------------------------------------------------
[java] Exception: java.sql.SQLException
[java] Message: Commit can not be set while enrolled in a transaction
[java] ---- stack trace ---------------------------------------------------------------
[java] java.sql.SQLException: Commit can not be set while enrolled in a transaction
[java] org.apache.commons.dbcp.managed.ManagedConnection.commit(ManagedConnection.java:214)
[java] org.ofbiz.entity.jdbc.SQLProcessor.commit(SQLProcessor.java:145)
[java] org.ofbiz.entity.jdbc.SQLProcessor.close(SQLProcessor.java:196)
[java] org.ofbiz.entity.datasource.GenericDAO.select(GenericDAO.java:493)
[java] org.ofbiz.entity.datasource.GenericHelperDAO.findByPrimaryKey(GenericHelperDAO.java:80)
[java] org.ofbiz.entity.GenericDelegator.storeAll(GenericDelegator.java:1424)
[java] org.ofbiz.entity.util.EntitySaxReader.writeValues(EntitySaxReader.java:286)
[java] org.ofbiz.entity.util.EntitySaxReader.parse(EntitySaxReader.java:265)
[java] org.ofbiz.entity.util.EntitySaxReader.parse(EntitySaxReader.java:222)
[java] org.ofbiz.entity.util.EntityDataLoader.loadData(EntityDataLoader.java:214)
[java] org.ofbiz.entityext.data.EntityDataLoadContainer.start(EntityDataLoadContainer.java:389)
[java] org.ofbiz.base.container.ContainerLoader.start(ContainerLoader.java:101)
[java] org.ofbiz.base.start.Start.startStartLoaders(Start.java:273)
[java] org.ofbiz.base.start.Start.startServer(Start.java:323)
[java] org.ofbiz.base.start.Start.start(Start.java:327)
[java] org.ofbiz.base.start.Start.main(Start.java:412)
[java] --------------------------------------------------------------------------------
[java]
[java] 2016-03-07 11:32:37,428 (main) [ EntitySaxReader.java:221:INFO ] Beginning import from URL: file:/home/oodles/work/skulocity/custom-erp-crm/opentaps/amazon/data/AmazonDemoData.xml
[java] 2016-03-07 11:32:37,428 (main) [ EntitySaxReader.java:259:INFO ] Transaction Timeout set to 2 hours (7200 seconds)
[java] 2016-03-07 11:32:37,466 (main) [ EntitySaxReader.java:278:INFO ] Finished 13 values from file:/home/oodles/work/skulocity/custom-erp-crm/opentaps/amazon/data/AmazonDemoData.xml
[java] 2016-03-07 11:32:37,466 (main) [EntityDataLoadContainer.java:404:INFO ] =-=-=-=-=-=-= Here is a summary of the data load:
[java] 2016-03-07 11:32:37,466 (main) [EntityDataLoadContainer.java:406:INFO ] 00024 of 00024 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/security/data/SecurityData.xml
[java] 2016-03-07 11:32:37,466 (main) [EntityDataLoadContainer.java:406:INFO ] 00023 of 00047 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/CommonSecurityData.xml
[java] 2016-03-07 11:32:37,466 (main) [EntityDataLoadContainer.java:406:INFO ] 00095 of 00142 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/CommonTypeData.xml
[java] 2016-03-07 11:32:37,466 (main) [EntityDataLoadContainer.java:406:INFO ] 00724 of 00866 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/CountryCodeData.xml
[java] 2016-03-07 11:32:37,466 (main) [EntityDataLoadContainer.java:406:INFO ] 00169 of 01035 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/CurrencyData.xml
[java] 2016-03-07 11:32:37,466 (main) [EntityDataLoadContainer.java:406:INFO ] 00279 of 01314 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData.xml
[java] 2016-03-07 11:32:37,466 (main) [EntityDataLoadContainer.java:406:INFO ] 00016 of 01330 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_AU.xml
[java] 2016-03-07 11:32:37,466 (main) [EntityDataLoadContainer.java:406:INFO ] 00056 of 01386 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_BG.xml
[java] 2016-03-07 11:32:37,466 (main) [EntityDataLoadContainer.java:406:INFO ] 00053 of 01439 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_BR.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00066 of 01505 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_CN.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00066 of 01571 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_CO.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00032 of 01603 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_DE.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00138 of 01741 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_ES.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00428 of 02169 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_FR.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00220 of 02389 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_IT.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00070 of 02459 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_IN.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00064 of 02523 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_IRL.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00026 of 02549 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_NL.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00172 of 02721 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_UK.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00240 of 02961 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/GeoData_US.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00433 of 03394 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/LanguageData.xml
[java] 2016-03-07 11:32:37,467 (main) [EntityDataLoadContainer.java:406:INFO ] 00236 of 03630 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/UnitData.xml
[java] 2016-03-07 11:32:37,468 (main) [EntityDataLoadContainer.java:406:INFO ] 00007 of 03637 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/PeriodData.xml
[java] 2016-03-07 11:32:37,468 (main) [EntityDataLoadContainer.java:406:INFO ] 00012 of 03649 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/common/data/CommonPortletData.xml
[java] 2016-03-07 11:32:37,468 (main) [EntityDataLoadContainer.java:406:INFO ] 00008 of 03657 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/service/data/ScheduledServiceData.xml
[java] 2016-03-07 11:32:37,468 (main) [EntityDataLoadContainer.java:406:INFO ] 00003 of 03660 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/service/data/ServiceSecurityData.xml
[java] 2016-03-07 11:32:37,468 (main) [EntityDataLoadContainer.java:406:INFO ] 00012 of 03672 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/entityext/data/EntityExtTypeData.xml
[java] 2016-03-07 11:32:37,468 (main) [EntityDataLoadContainer.java:406:INFO ] 00003 of 03675 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/entityext/data/EntityExtSecurityData.xml
[java] 2016-03-07 11:32:37,468 (main) [EntityDataLoadContainer.java:406:INFO ] 00001 of 03676 from file:/home/oodles/work/skulocity/custom-erp-crm/framework/bi/data/BiTypeData.xml
```
BUILD FAILED
/home/oodles/work/skulocity/custom-erp-crm/build.xml:510: Java returned: 99
```
$java -version
Java(TM) SE Runtime Environment (build 1.6.0_45-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.45-b01, mixed mode)
opentaps=> select version();
version
----------------------------------------------------------------------------------------------------------------
PostgreSQL 9.2.15 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52), 64-bit
(1 row)
$ant -version
Apache Ant(TM) version 1.9.3 compiled on April 8 2014
```
I have followed all steps mentioned on installation doc.
On executing "ant run-install" it created 1015 table but failed at the end.Can anybody help me..?
|
2016/03/07
|
[
"https://Stackoverflow.com/questions/35837369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4349887/"
] |
In my case $JAVA\_HOME was pointing to JDK1.7 and java -version command was showing JDK1.6,So i changed $JAVA\_HOME to 1.6 and this is working fine.
|
13,520,279 |
I've written a script that opens up a file, reads the content and does some operations and calculations and stores them in sets and dictionaries.
How would I write a unit test for such a thing? My questions specifically are:
1. Would I test that the file opened?
2. The file is huge (it's the unix dictionary file). How would I unit test the calculations? Do I literally have to manually calculate everything and test that the result is right? I have a feeling that this defeats the whole purpose of unit testing. I'm not taking any input through stdin.
|
2012/11/22
|
[
"https://Stackoverflow.com/questions/13520279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680441/"
] |
That's not what unit-testing is about!
1. Your file doesn't represent an UNIT, so no you don't test the file or WITH the file!
2. your unit-test should test every single method of your functions/methods which deals with the a)file-processing b) calculations
3. it's not seldom that your unit-tests exceeds the line of code of your units under test.
Unit-test means (not complete and not the by-the-book definition):
* minimalistic/atomic - you split your units down to the most basic/simple unit possible; an unit is normally a callable (method, function, callable object)
* separation of concern - you test ONE and only ONE thing in every single test; if you want to test different conditions of a single unit, you write different tests
* determinism - you give the unit something to process, with the beforehand knowledge of what it's result SHOULD be
* if your unit-under-test needs a specific enviroment you create a fixture/test-setup/mock-up
* unit-tests are (as a rule of thumb) blazingly fast! if it's slow check if you violated another point from above
* if you need to test somethin which violates somethin from above you may have made the next step in testing towards integration-tests
* you may use unit-test frameworks for not unit-testings, but don't call it unit-test just because of the use of the unittest-framework
This guy (Gary Bernhardt) has some interesting [practical examples](https://www.youtube.com/watch?v=RAxiiRPHS9k) of what testing and unit-testing means.
**Update** for some clarifications:
"1. Would I test that the file opened?"
Well you could do that, but what would be the "UNIT" for that? Keep in mind, that a test has just two solutions: pass and fail. If your test fails, it should (ideally must) have only one reason for that: Your unit(=function) sucks! But in this case your test can fail, because:
\* the file doesn't exist
\* is locked
\* is corrupted
\* no file-handles left
\* out of memeory (big file)
\* moon- phase
and so on.
so what would a failing (or passing) "unit" test say about your unit? You don't test your unit alone, but the whole surrounding enviroment with it. That's more a system-test!
If you would like to test nontheless for successful file-opening you should at least mock a file.
"2 ... How would I unit test the calculations? Do I literally have to manually calculate everything and test that the result is right?"
No. You would write test for the corner- and regular-cases and check the expected outcome against the processed one. The amount of tests needed depends on the complexity of your calculations and the exceptions to the rule.
e.g.:
```
def test_negative_factor(self):
assert result
def test_discontinuity(self):
assert raise exception if x == undefined_value
```
I hope i made myself clearer!
|
36,153,880 |
I have an absolutely placed div which uses the CSS as such:
```
.overlay {
position:absolute;
margin:0.5%;
z-index:100;
}
.topRightOverlay {
top:0;
right:0;
}
```
My body and HTML both have a min-height and width. However when I reduce the browser window to below the min size, the absolute div does not stick to the far top right, instead it follows the viewport in and then stays positioned as I scroll (not following the viewport back).
How can I ensure this div stays suck to the top right of the HTML/body, even if that means being off screen until scrolled to?
Here is the HTML Structure:
```
<html lang="en">
<body>
<form runat="server">
<div class="overlay topRightOverlay">
<!-- overlay content -->
</div>
<!-- content placeholder for content pages -->
</form>
</body>
</html>
```
And the HTML, Body CSS:
```
body, html {
height: 100%;
min-height:600px;
min-width:800px;
overflow:hidden;
}
html {overflow:auto;}
```
```css
body,
html {
height: 100%;
min-height: 600px;
min-width: 800px;
overflow: hidden;
}
html {
overflow: auto;
}
form {
height: 100%;
}
.overlay {
position: absolute;
margin: 0.5%;
z-index: 100;
}
.topRightOverlay {
top: 0;
right: 0;
}
```
```html
<html lang="en">
<body>
<form runat="server">
<div class="overlay topRightOverlay nonInteractive">
This is an overlay
</div>
<!-- content placeholder for content pages -->
</form>
</body>
</html>
```
|
2016/03/22
|
[
"https://Stackoverflow.com/questions/36153880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5907840/"
] |
If I understand you correctly:
You have to give body `position: relative` and add some javascript to keep the `offset()` of the `absolute` element.
Have a look yourself
```js
$(document).ready(function(){
var posY;
document.onscroll = function(){
posY = 100 + $(window).scrollTop();//locate needed Y position
$("#absDiv").offset({top: posY}); //Apply position
};
})
```
```css
body{
margin:0;
padding:0;
width: 100%;
position: relative;
}
section {
height: 1500px;
width:100%;
background-color: #2ecc71;
}
#absDiv {
width: 80px;
padding: 5px;
line-height: 17px;
position:absolute;
right:0;
top:100px;
background-color: #d35400;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="absDiv">
I'm pretty fixed to this place...
</div>
<section>
</section>
</body>
```
Hope I got you right and helped :)
Cheers,
Evoc
|
23,493,527 |
I'm new to Android and therefore faced such problem.
How can I change layout from:

To:

XML fragment\_main:
```
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.snbgearassistant.MainActivity$PlaceholderFragment" >
<TextView
android:id="@+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
```
So I need these tabs having grid layout with different content.
|
2014/05/06
|
[
"https://Stackoverflow.com/questions/23493527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3027431/"
] |
You must use a GridView inside the ViewPager. So, in your `MainActivity`, you would have this layout.
Create the activity\_main.xml layout
------------------------------------
This is the main layout. Everything will live inside of it, including your fragments and tabs.
```
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.myapp.gridview.MainActivity" />
```
Create your MainActivity.java class
-----------------------------------
```
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener
{
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Here we load the xml layout we created above
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
{
@Override
public void onPageSelected(int position)
{
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
{
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
@Override
public Fragment getItem(int position)
{
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return new PlaceholderFragment();
}
@Override
public int getCount()
{
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
switch (position)
{
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
}
```
>
> Don't forget to create your strings for these `R.string.title_section1, ...` strings on your code, or you will have an error.
>
>
>
Now we must create a layout for the fragment (the page that will be displayed inside the tab), and it must contain a `GridView`.
Create a fragment\_main.xml layout
----------------------------------
```
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2" />
</FrameLayout>
```
Now let's define the fragment class that will take care of inflating this layout and handling the views.
Create a fragment to inflate the GridView layout: PlaceHolderFragment.java
--------------------------------------------------------------------------
```
/**
* A placeholder fragment containing a the gridview
*/
public class PlaceholderFragment extends Fragment
{
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Here we inflate the layout we created above
GridView gridView = (GridView) rootView.findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(MainActivity.this.getApplicationContext()));
return rootView;
}
}
```
Now we must create an adapter class to handle each item of the `GridView`, this way you can manage the behavior of each one.
Create the Adapter to support the GridView items: MyAdapter.java
----------------------------------------------------------------
As you can see here, we are adding some items to the GridView by adding them to an `ArrayList` of the type `Item` defined in the end of the adapter class.
```
private class MyAdapter extends BaseAdapter
{
private List<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;
public MyAdapter(Context context)
{
inflater = LayoutInflater.from(context);
items.add(new Item("Image 1", Color.GREEN));
items.add(new Item("Image 2", Color.RED));
items.add(new Item("Image 3", Color.BLUE));
items.add(new Item("Image 4", Color.GRAY));
items.add(new Item("Image 5", Color.YELLOW));
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int i)
{
return items.get(i);
}
@Override
public long getItemId(int i)
{
return items.get(i).colorId;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup)
{
View v = view;
ImageView picture;
TextView name;
if(v == null)
{
v = inflater.inflate(R.layout.gridview_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)getItem(i);
picture.setBackgroundColor(item.colorId);
name.setText(item.name);
return v;
}
private class Item
{
final String name;
final int colorId;
Item(String name, int drawableId)
{
this.name = name;
this.colorId = drawableId;
}
}
}
```
Now to make the `GridView` items keep with the correct width, aligned side by side, we use a custom class to define the measured dimension.
Why this needs to be done? According to [@kcoppock's answer](https://stackoverflow.com/a/15264039/399459):
>
> Basically, in Android's `ImageView` class, there's no way to simply specify "hey, keep a square aspect ratio (width / height) for this view" unless you hard code width and height. You could do some manual adjustment of `LayoutParams` in the adapter's getView, but frankly, it's much simpler to let `ImageView` handle all the measurements, and just override the results to say "Whatever the width ends up being, make my height stay the same". You never have to think about it, it's always square, and it just works as expected. Basically this is the easiest way to keep the view square.
>
>
>
Create a class SquareImageView.java
-----------------------------------
```
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class SquareImageView extends ImageView
{
public SquareImageView(Context context)
{
super(context);
}
public SquareImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
```
Now we must define the XML layout for the `GridView` items.
Create a XML layout gridview\_item.xml
--------------------------------------
As you can see, here we add two items to the layout. One is a element of the type `SquareImageView` (the class we created above) and the `TextView` which is a label for each image.
```
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.myapp.gridview.SquareImageView
android:id="@+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
/>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:layout_gravity="bottom"
android:textColor="@android:color/white"
android:background="#55000000"
/>
</FrameLayout>
```
And here it is, I tested the code and this is the final result. Of course you would change those colors for your images, but this is the approach you should follow.
**Note:** To set images instead of colors to the `GridView` item, in your `getView()` method of the `MyAdapter` class use [`setImageResource(int)`](http://developer.android.com/reference/android/widget/ImageView.html#setImageResource(int)) instead of `setBackgroundColor(int)`.

|
70,673,656 |
I state that I am not an expert in Python and I started very recently with Kivy! I would like to know if it is possible, and if it makes sense, to add widgets such as buttons or labels while the app is running. For example a button that each time it is pressed adds a new button to a screen. I don't know if I've been clear enough.
|
2022/01/11
|
[
"https://Stackoverflow.com/questions/70673656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This example illustrates the process by creating a new `Button` each time another `Button` is pressed, you can also delete (remove) the created buttons.
```py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
class CustomBox(BoxLayout):
def add_buttons(self, *args):
"""Method for creating new Button."""
i = len(self.ids.inner_box.children) # Just to distinguish the buttons from one another.
btn = Button(
text = f"Button {i+1}",
size_hint_y = None,
height = "64dp",
)
self.ids.inner_box.add_widget(btn) # Referencing container by its 'id'.
Builder.load_string("""
<CustomBox>:
orientation: "vertical"
spacing: dp(2)
Button:
size_hint_y: 0.5
text: "Add Button"
color: 0, 1, 0, 1
on_release: root.add_buttons()
ScrollView: # To see and add all the buttons in progress.
BoxLayout: # Button's container.
id: inner_box
orientation: "vertical"
spacing: dp(5)
padding: dp(5)
size_hint_y: None # Grow vertically.
height: self.minimum_height # Take as much height as needed.
Button:
size_hint_y: 0.5
text: "Delete Button"
color: 1, 0, 0, 1
on_release: inner_box.remove_widget(inner_box.children[0]) if inner_box.children else None # Here '0' means last added widget.
""")
class MainApp(App):
def build(self):
return CustomBox()
if __name__ == '__main__':
MainApp().run()
```
|
26,341,304 |
i can't import zxlolbot.py
have problem...
>
> No handlers could be found for logger "zxlolbot"
>
>
>
[](https://i.stack.imgur.com/fjvCc.png)
|
2014/10/13
|
[
"https://Stackoverflow.com/questions/26341304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4134833/"
] |
Reading your last comment I conclude you just need to get the `ReadLine` out of the loop:
```
for (i = 0; i < 5; ++i)
{
Console.WriteLine("Welcome, Kindly enter your Name: ");
EmployeeName[i] = Console.ReadLine();
string TimeofArr = DateTime.Now.ToString();
Console.WriteLine(TimeofArr);
}
Console.ReadLine();
```
|
42,646,747 |
I am trying to insert data from edit texts to a live database but the app crashes when i press the button which should send data.
```
public class MainActivity extends Activity {
Button add_btn,view_btn;
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add_btn=(Button)findViewById(R.id.add_btn);
view_btn=(Button)findViewById(R.id.view_btn);
txt=(TextView)findViewById(R.id.textView1);
ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
if(networkInfo!=null && networkInfo.isConnected()){
txt.setVisibility(View.INVISIBLE);
}
else
{
add_btn.setEnabled(false);
view_btn.setEnabled(false);
txt.setVisibility(View.VISIBLE);
}
}
public void add_user(View view){
startActivity(new Intent(this,Add_user.class));
}
public void view_user(View view){
}
}
public class Add_user extends Activity {
EditText name,username,pass;
Button add_user;
String name1,username1,pass1,method;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
name=(EditText)findViewById(R.id.username);
username=(EditText)findViewById(R.id.name);
pass=(EditText)findViewById(R.id.pass);
add_user=(Button)findViewById(R.id.button1);
}
public void add(View view){
name1=name.getText().toString();
username1=username.getText().toString();
pass1=pass.getText().toString();
BackgroundTask backgroundTask=new BackgroundTask();
backgroundTask.execute(name1,username1,pass1);
finish();
}
class BackgroundTask extends AsyncTask<String, Void, String> {
String url;
@Override
protected void onPreExecute() {
url="http://douxtoile.com/add_user.php";
Toast.makeText(getApplicationContext(), url,Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(String... params) {
String name=params[1];
String username=params[2];
String pass=params[3];
Toast.makeText(getApplicationContext(), name+""+username+""+pass,Toast.LENGTH_LONG).show();
try {
URL url1=new URL(url);
HttpsURLConnection httpsURLConnection=(HttpsURLConnection)url1.openConnection();
httpsURLConnection.setRequestMethod("POST");
httpsURLConnection.setDoOutput(true);
OutputStream os=httpsURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String data=URLEncoder.encode("user","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"+
URLEncoder.encode("pass","UTF-8")+"="+URLEncoder.encode(pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream is=httpsURLConnection.getInputStream();
is.close();
httpsURLConnection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(NullPointerException e){
Toast.makeText(getApplicationContext(), e.toString(), 0).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Success";
}
@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
}
```
Here is my Error log.
```
Stacktrace:
03-07 16:05:34.324: E/AndroidRuntime(24090): FATAL EXCEPTION: AsyncTask #2
03-07 16:05:34.324: E/AndroidRuntime(24090): Process: com.example.demo_online_db, PID: 24090
03-07 16:05:34.324: E/AndroidRuntime(24090): java.lang.RuntimeException: An error occured while executing doInBackground()
03-07 16:05:34.324: E/AndroidRuntime(24090): at android.os.AsyncTask$3.done(AsyncTask.java:300)
03-07 16:05:34.324: E/AndroidRuntime(24090): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-07 16:05:34.324: E/AndroidRuntime(24090): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-07 16:05:34.324: E/AndroidRuntime(24090): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-07 16:05:34.324: E/AndroidRuntime(24090): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-07 16:05:34.324: E/AndroidRuntime(24090): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-07 16:05:34.324: E/AndroidRuntime(24090): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-07 16:05:34.324: E/AndroidRuntime(24090): at java.lang.Thread.run(Thread.java:818)
03-07 16:05:34.324: E/AndroidRuntime(24090): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
03-07 16:05:34.324: E/AndroidRuntime(24090): at com.example.demo_online_db.Add_user$BackgroundTask.doInBackground(Add_user.java:54)
03-07 16:05:34.324: E/AndroidRuntime(24090): at com.example.demo_online_db.Add_user$BackgroundTask.doInBackground(Add_user.java:1)
03-07 16:05:34.324: E/AndroidRuntime(24090): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-07 16:05:34.324: E/AndroidRuntime(24090): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-07 16:05:34.324: E/AndroidRuntime(24090): ... 4 more
03-07 16:05:35.985: E/OpenGLRenderer(24090): SFEffectCache:clear(), mSize = 0
```
I have not included any external jars actually i am new to this so dont know exactly if i am doing this the right way or wrong.
Php script is fine i have tested it statically.
|
2017/03/07
|
[
"https://Stackoverflow.com/questions/42646747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5832243/"
] |
Get your string values in this way...
```
String name=params[0];
String username=params[1];
String pass=params[2];
```
|
56,269,102 |
I am new to Apache Beam. I am reading the Word Count and Mobile Gaming tutorials. For Word Count, the commands to run the pipelines are given. However, there is no commands given in the tutorial to run Mobile Gaming.
<https://beam.apache.org/get-started/wordcount-example/>
<https://beam.apache.org/get-started/mobile-gaming-example/>
There are comments in the code, which help me figure out how to run the first two batch pipelines. However, I am not sure the commands about the last two streaming pipelines.
The comments also mentioned to use Injector to generate Pub/Sub data. I suppose it may have several steps to successfully run these streaming pipelines. Such as, create BigQuery table, generate pubsub data, run commands in terminal, ...
Would someone please help show me how to do this? Thanks!
I have tried the first two batch pipelines using the following command on Google Cloud Shell.
```
mvn compile exec:java -Dexec.mainClass=org.apache.beam.examples.complete.game.UserScore
-Dexec.args="--runner=DataflowRunner
--project=MY_PROJECT_NAME
--tempLocation=gs://MY_BUCKET_NAME/tmp
--output=gs://MY_BUCKET_NAME/userScore" -Pdataflow-runner
```
|
2019/05/23
|
[
"https://Stackoverflow.com/questions/56269102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3444226/"
] |
You just need to change Contact Form 7 Custom DOM Event, Use wpcf7mailsent instead of wpcf7submit.
***wpcf7mailsent β Fires when an Ajax form submission has completed successfully, and mail has been sent.***
```
function cf7_footer_script() { ?>
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( '7084' == event.detail.contactFormId ) {
var lpLocation = document.getElementById( "careers" ).value;
if ( lpLocation == "Hire better employees" ) {
location = 'url1';
} else if ( lpLocation == "I want to match people to the best careers" ) {
location = 'url2';
} else if( lpLocation == "I want to learn more about both" ) {
location = 'url3';
}
}
}, false );
</script>
<?php }
add_action( 'wp_footer', 'cf7_footer_script' );
```
|
8,152,528 |
I am using a [Nivo Slider](http://nivo.dev7studios.com/)-based Joomla 1.5 image slider module.
The slider works perfectly fine on FireFox and IE, as can be seen on [our website](http://www.openmindprojects.org/training/).
It used to work fine on Chrome, too but it doesn't anymore and I don't have a clue why.
The module is jQuery based for sure and I am using jQuery 1.6.3 for this one.
|
2011/11/16
|
[
"https://Stackoverflow.com/questions/8152528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1049698/"
] |
You are loading jQuery twice, once with:
```
<script type="text/javascript" src="http://www.openmindprojects.org/iframe/js/jquery.js"></script>
```
and again
```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js" type="text/javascript"></script>
```
Not to mention the fact you have `mootools.js` loading, this is a start to your conflicting problems.
Make sure that
1. You don't have any JavaScript errors. I spot 2.
2. You aren;t loading jquery twice, and if mootools is running, run jQuery in conflict mode
3. The order of your Javascript files are fine. i.e. you are loading a library before a call, not a call after a library.
|
33,903 |
---
*NB: In our company's [internal lexicon](https://pm.stackexchange.com/questions/33903/how-to-integrate-devops-people-into-a-scrum-team/33906#comment42367_33905), "DevOps" is a role set by our company that means "infrastructure and operations person" rather than standard DevOps. I know it's more of a culture thing but I missed clarifying it in my original question due to company speech blindness.*
---
Reading through [Should a designer or a devops be a member of a Scrum team?](https://pm.stackexchange.com/questions/33335/should-a-designer-or-a-devops-be-a-member-of-a-scrum-team) + [Including UX in Scrum](https://pm.stackexchange.com/questions/10508/including-ux-in-scrum) there seems to be a general consensus that UX/Infra/Ops people should be full scrum team members.
Our teams currently have 2-3 backend developers, 2-3 frontend developers, and 1 infrastructure/operations person.
Trying to accomplish that in our team we face issues during the planning phase of a sprint:
* Most of our User Stories don't require Ops/Infra work, which leads to issues when planning a sprint for the whole team.
* There are Ops/Infra tasks/stories that have no relation to development stories for example: "update library/service X on beta"
This leads to issues where frontend devs are not happy because they have to estimate "server stuff" and Infra/Ops are not happy because they have to estimate "refactor JS service XY" during Sprint Planning.
I think the ideal long term solution would be to have all people on the team learn and expand their knowledge but that is just not the current state. I'm not sure if everyone in the company is committed on making everyone capable of working on all tasks.
Should we just accept the "overhead" that exists in those meetings until enough knowledge is shared or should we plan ops/infra tasks outside the Sprint? Should maintenance stuff be separate, or are there any other practical solutions for this?
|
2022/04/20
|
[
"https://pm.stackexchange.com/questions/33903",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/49603/"
] |
There's no such thing as "DevOps people".
DevOps is an organizational culture. Like how Agile brought the business and developers into a close, collaborative relationship, DevOps is about a close and collaborative relationship between development and operations, with the end goal of making it faster and easier to make a change and put that change into production, while ensuring the overall quality of a system. The result of a shift to a DevOps culture is the elimination of silos and hand-offs between a development organization, who is responsible for eliciting requirements and building a system, and an operations organization, who is responsible for putting changes into production and supporting (monitoring, maintaining) the system.
Just like in development, there are many roles associated with operations. A few examples of operations roles include help desk or technical support staff, network administrators, database administrators, network architects, various security and incident management roles, among others.
From a team's perspective, good teams moving toward agility should be trending toward being cross-functional. That means that the team, to the extent possible, has the knowledge necessary to take on work from start to end in the workflow. But some skills are highly specialized or not needed on a day-to-day basis, so it may be more about teaching the basic skills to multiple members of the team while making sure that there are sufficient experts to support the teams as needed. It doesn't necessarily mean that each team has an expert in every possible subject matter area.
There's no one-size-fits all answer. In the immediate term, you need to support the teams with the people that you have. For the longer term, you need to decide which skills will be embedded on the team and which skills will exist in a shared pool available upon request. You can also identify people who may be interested in developing new skills, and how the existing experts can serve as teachers so teams can have some knowledge internally and rely on the shared pool of experts for more difficult tasks.
|
27,951,944 |
Following Spring docs, I've created a maven project with the following dependencies :
```
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1102-jdbc41</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
```
I'd like to know if Repository data abstraction "goes through" hibernate or not.
|
2015/01/14
|
[
"https://Stackoverflow.com/questions/27951944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853780/"
] |
TLDR; the issue is: the RTC plugin isn't properly installed.
The [OP](https://stackoverflow.com/users/3230201/user3230201) adds [in the comments](https://stackoverflow.com/questions/27951941/pull-in-rpt-scripts-in-to-rtc-by-making-rpt-8-5-1-3-and-rtc-4-0-6-connection-for/27952088#comment44344370_27952088):
>
> The client version of the [**IBM Installation Manager**](http://www-01.ibm.com/support/knowledgecenter/SSDV2W/im_family_welcome.html) was lower enough to not update the RTC/RPT Source control (Jazz source control).
>
> Hence updating Instal manager and then modifying the Jazz source control resolved this.
>
>
>
---
Original answer (for illustrating the symptoms)
From what I can see of the white paper "[Integrate Rational Team Concert and Rational Performance Tester for collaborative script development, version control, and process management](http://www.ibm.com/developerworks/rational/library/09/integraterationalteamconcertandrationalperformancetester/)", you don't need to enter an Host and repo path "for RTP" (RTP being the "[IBM Rational Performance Tester](http://www.ibm.com/developerworks/downloads/r/rpt/)").
The only step where you need to enter that kind of data is strictly for RTC (RTC being the "[IBM Rational Team Concert](http://www-03.ibm.com/software/products/en/rtc)", an [ALM tool](https://stackoverflow.com/a/8490883/6309)):

If you see any other "connection" windows on the "Share project" step, that means you selected the wrong Version Control tool on that step.
So if you see one for CVS:

That just means you didn't click the right line (which should be "Jazz source Control"):

|
2,792,365 |
Given
$$A = \begin{bmatrix}
-9 & 4 & 4\\
-8 & 3 & 4 \\
-16 & 8 & 7
\end{bmatrix}$$
I calculated eigenvalues $\lambda= -1,-1,3$. The algebraic multiplicity (AM) and geometric multiplicity (GM) of $\lambda=-1$ are $2$, which tells us that there will be two linearly independent eigenvectors.
I am not sure how to find the eigenvectors. Usually, I take one variable and equate it to $t$ and then solve it for the other two. I am not quite sure how to find eigenvectors when we have two free variables.
Steps:
$$(A-\lambda I)=0$$
$$\begin{bmatrix}
-8 & 4 & 4\\
-8 & 4 & 4 \\
-16 & 8 & 8
\end{bmatrix} \begin{bmatrix}
x \\
y \\
z \end{bmatrix}=\begin{bmatrix}
0\\
0 \\
0
\end{bmatrix}$$
$$\begin{bmatrix}
8 & -4 & -4\\
0 & 0 & 0 \\
0 & 0 & 0
\end{bmatrix} \begin{bmatrix}
x \\
y \\
z \end{bmatrix}=\begin{bmatrix}
0\\
0 \\
0
\end{bmatrix}$$
$$2x-y-z=0$$
I don't know how to proceed from here.
|
2018/05/23
|
[
"https://math.stackexchange.com/questions/2792365",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/519543/"
] |
so
$x=\lbrace\frac{y}{2}+\frac{z}{2} $
let be
$y=1$, $z=0$, then
$v1=\begin{bmatrix}\frac {1}{2} \\ {1}\\ {0} \end{bmatrix}$
let be
$y=0$, $z=1$, then
$v2=\begin{bmatrix}\frac {1}{2} \\ {0}\\ {1} \end{bmatrix}$
later, you only substitute $\lambda (i)$ and $v1$,$v2$ in the equations
$\ (A-\lambda I)v1=0$
and $\ (A-\lambda I)v2=0$
|
67,193,397 |
I'm using FASTApi and trying to implement an endpoint, which starts a job. Once the job is started, the endpoint shall be "locked" until the previous job finished. So far its implemented like this:
```
myapp.lock = threading.Lock()
@myapp.get("/jobs")
def start_job(some_args):
if myapp.lock.acquire(False):
th = threading.Thread(target=job,kwargs=some_args)
th.start()
return "Job started"
else:
raise HTTPException(status_code=400,detail="Job already running.")
```
So, when the job gets started, a thread will be created using the method job:
```
def job(some_args):
try:
#doing some stuff, creating objects and writing to files
finally:
myapp.lock.release()
```
So far so good, the endpoint is working, starts a job and locks as long as the job is running.
But my problem is that the thread is still alive although the job "finished" and released the lock. I was hoping that the thread would close itself after execution. Maybe the problem is that myapp is keeping it alive? How can I stop it?
|
2021/04/21
|
[
"https://Stackoverflow.com/questions/67193397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995201/"
] |
Approximately,
```
G(m) = lg(m)
```
and
```
F(1) = c
F(n) = F(n-1) + G(f(n)) = F(n-1) + n.
```
because `f(n) = 2^n`.
|
23,885,166 |
I got table called users as the following
```
New Old Different
Jack Sam Jack
smith Smith Anna
Sam
Anna
```
which got columns new old different I need to compare between new / old if name exist in new and not in old then insert in different
any tips for this statement
|
2014/05/27
|
[
"https://Stackoverflow.com/questions/23885166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/898454/"
] |
Try this>>>
```
Class Order < ActiveRecord::Base
....
attr_accessor :card_number, :card_verification
validate :validate_card, :on => :create
private
def validate_card
unless credit_card.valid?
errors.add(:credit_card, "your message")
end
end
end
```
|
31,977,248 |
I have a date (see dateValue variable) returned from the ajax response. Parsing that value works in chrome but not in IE 9.
Am I missing anything? Any help / suggestion is appreciated.
```js
var dateValue = "2015-08-12T16:31:51.68";
$('#result').text(Date.parse(dateValue));
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="result"></label>
```
|
2015/08/12
|
[
"https://Stackoverflow.com/questions/31977248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872454/"
] |
ISO-8601 date parsing was added in ES5, so not all browsers support it.
Check [this](https://github.com/csnover/js-iso8601) github project for an implementation that might work for you.
Or you could use a library like [moment.js](http://momentjs.com/docs/#/parsing/string/) for better cross browser capability.
```
var dateValue = "2015-08-12T16:31:51.68";
$('#result').text(moment(dateValue););
```
|
843,110 |
I understand that the default encoding of an HTTP Request is ISO 8859-1.
Am I able to use Unicode to decode an HTTP request given as a byte array?
If not, how would I decode such a request in C#?
**EDIT:** I'm developing a server, not a client.
|
2009/05/09
|
[
"https://Stackoverflow.com/questions/843110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
As you said the default encoding of an HTTP POST request is ISO-8859-1. Otherwise you have to look at the Content-Type header that might then look like `Content-Type: application/x-www-form-urlencoded; charset=UTF-8`.
Once you have read the posted data into a byte array you may decide to convert this buffer to a string (remember all strings in .NET are UTF-16). It is only at that moment that you need to know the encoding.
```
byte[] buffer = ReadFromRequestStream(...)
string data = Encoding
.GetEncoding("DETECTED ENCODING OR ISO-8859-1")
.GetString(buffer);
```
And to answer your question:
>
> Am I able to use Unicode to decode an
> HTTP request given as a byte array?
>
>
>
Yes, if unicode has been used to encode this byte array:
```
string data = Encoding.UTF8.GetString(buffer);
```
|
2,716,284 |
I have Windows Application (.EXE file is written in C and built with MS-Visual Studio), that outputs ASCII text to stdout. Iβm looking to enhance the ASCII text to include limited HTML with a few links. Iβd like to invoke this application (.EXE File) and take the output of that application and pipe it into a Browser. This is not a one time thing, each new web page would be another run of the Local Application!
The HTML/java-script application below has worked for me to execute the application, but the output has gone into a DOS Box windows and not to pipe it into the Browser. Iβd like to update this HTML Application to enable the Browser to capture that text (that is enhanced with HTML) and display it with the browser.
```
<body>
<script>
function go() {
w = new ActiveXObject("WScript.Shell");
w.run('C:/DL/Browser/mk_html.exe');
return true;
}
</script>
<form>
Run My Application (Window with explorer only)
<input type="button" value="Go"
onClick="return go()">
</FORM>
</body>
```
|
2010/04/26
|
[
"https://Stackoverflow.com/questions/2716284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326293/"
] |
1. Have the executable listen on a port following the HTTP protocol.
2. Then have the web page make AJAX-style HTTP requests to the local port with JAvascript.
3. The executable returns text.
4. The web page updates itself through DOM manipulation in Javascript.
Yes, this works. It is happening 5 feet away from me right now in another cubicle.
|
51,347,349 |
I'm making a form that have a group selected dropdown that consist of string stored from database (i did a @foreach loop through database via eloquent model to assign the dropdown value lists), on the below of the dropdown i have 3 disable inputs that are the column from database that have a correlation with the value of dropdown. I want that placeholder of disable input automatically change the value to be same as the record with the dropdown value's record from database once i select a value from dropdown. What should i do? What JS script should i use for?
[](https://i.stack.imgur.com/ySCua.png)
**blade.php**
```
<form class="form-horizontal">
<fieldset>
<div class="control-group">
<label class="control-label" for="selectError2">Plat Nomor</label>
<div class="controls">
<select data-placeholder="Pilih Nomor Polisi" id="selectError2" data-rel="chosen">
<option value=""></option>
@foreach ($park as $p)
<option value="{{$p->id}}">{{$p->nopol}}</option>
@endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="disabledInput">Jenis Kendaraan</label>
<div class="controls">
<input class="input-large disabled" id="disabledInput" type="text" placeholder="{{$p->jenis}}" disabled="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="disabledInput">Kategori Kendaraan</label>
<div class="controls">
<input class="input-large disabled" id="disabledInput" type="text" placeholder="{{$p->kategori}}" disabled="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="disabledInput">Waktu Masuk</label>
<div class="controls">
<input class="input-large disabled" id="disabledInput" type="text" placeholder="{{$p->created_at}}" disabled="">
</div>
</div>
```
|
2018/07/15
|
[
"https://Stackoverflow.com/questions/51347349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7162428/"
] |
You are joining the `team_info` table using only `venue_id`. This way every row from `match` will be joined with every team in `team_info`. You should add the condition `i.team_id = m.home_team_id` to limit the JOIN to the home team only:
```
SELECT m.venue_id,
MIN(m.venue_attendance) AS min_attendance,
MAX(m.venue_attendance) AS max_attendance,
SUM(m.venue_attendance) AS venue_sum,
v.name AS venue_name,
ROUND(AVG(m.venue_attendance), 2) AS average,
-- v.capacity, -- no such column in sample data
t.name AS team_name
FROM `match` m
INNER JOIN venue v ON v.id = m.venue_id
INNER JOIN team_info i
ON i.venue_id = m.venue_id
AND i.team_id = m.home_team_id -- this is the fix
INNER JOIN team t ON t.id = i.team_id
WHERE m.round_id = 28
GROUP BY m.venue_id, t.name
ORDER BY average DESC
```
Result:
```
| venue_id | min_attendance | max_attendance | venue_sum | venue_name | average | team_name |
|----------|----------------|----------------|-----------|----------------------|---------|------------------|
| 10 | 4500 | 4500 | 4500 | Stadiumi Loro BoriΓ§i | 4500 | Vllaznia ShkodΓ«r |
| 10 | 300 | 6000 | 31600 | Stadiumi Loro BoriΓ§i | 1858.82 | SkΓ«nderbeu KorΓ§Γ« |
```
Fiddle: <http://sqlfiddle.com/#!9/9aaf7c9/1>
But you can probably just skip the `team_info` table and join the `team` table directly to `match`:
```
SELECT m.venue_id,
MIN(m.venue_attendance) AS min_attendance,
MAX(m.venue_attendance) AS max_attendance,
SUM(m.venue_attendance) AS venue_sum,
v.name AS venue_name,
ROUND(AVG(m.venue_attendance), 2) AS average,
-- v.capacity, -- no such column in sample data
t.name AS team_name
FROM `match` m
INNER JOIN venue v ON v.id = m.venue_id
INNER JOIN team t ON t.id = m.home_team_id -- this is the fix
WHERE m.round_id = 28
GROUP BY m.venue_id, t.name
ORDER BY average DESC
```
The result is the same.
|
43,556,918 |
I have a study item that states: Write a function bestShow that accepts an object and returns the value of the title property from that object.
Hint provided:
console.log(bestShow({ genre: 'comedy', title: 'Seinfeld' }));
//Should print: Seinfeld
I've tried so many different things. Here is one iteration, where I finally gave up.
```
function bestShow(genre, title)
{
this.genre = genre;
this.title = title;
}
var show = new bestShow(βcomedyβ, βSeinfeldβ);
console.log(show.bestShow.title);
```
|
2017/04/22
|
[
"https://Stackoverflow.com/questions/43556918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5732420/"
] |
This ES6 fat arrow function will do:
```
let title = (data) => data.title;
```
**Pre ES6 version**:
We will define a function, which accepts `{genre: "comedy", title: "Sienfeld"}` which is in-turn a valid JS object with properties `genre` and `title`. So all that is left there to do is to return the value of `title` property of our `data` parameter. Then we are just calling our function and using the result as an input for `console.log`.
```
function title(data) {
return data.title;
}
console.log(title({ genre: 'comedy', title: 'Seinfeld' }));
```
|
52,586 |
I am new to QGIS, OpenStreetmap and Spatialite. I'm trying to get the (OSM) map data into a (SQLite) compact form I can eventually use for realtime reverse geocoding in a vehicle. Quantum is just for exploring the data, at this point.
I've downloaded the Saskatchewan highway layer from CloudMade (<http://downloads.cloudmade.com/americas/northern_america/canada/saskatchewan>) and converted it to Spatialite using
```
spatialite_osm_raw -o saskatchewan.highway.osm -d SK_Hi.sqlite
```
and
```
spatialite_osm_net -o saskatchewan.highway.osm -d SK_hi_net.sqlite -T Roads
```
Both processes run to completion, although there are lots of unresolved nodes while building the network. Neither map layer can be opened in QGis. In either case I am getting a "Failure exploring tables from: Z:/GIS/OpenStreetMap/SK/sk\_hi\_net.sqlite. no such column: type" when I try to connect to the database.
I am able to browse the db using the Quantum DB Manager, and I see that a number of the tables are empty. Specifically "geometry\_columns\_field\_infos" all of the views\_geometry tables and virts\_geometry tables.
Is this a problem with the datasource, the toolchain, or my understanding (in increasing order of likelihood)?
|
2013/02/21
|
[
"https://gis.stackexchange.com/questions/52586",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/15344/"
] |
I think you've chosen the wrong tools.
From [the documentation](https://www.gaia-gis.it/fossil/spatialite-tools/wiki?name=OSM%20tools):
>
> spatialite\_osm\_map
>
>
> ...
>
>
> The intended goal of this tool is the one to produce a DB-file suited to be immediately used with some appropriate GIS application (e.g. QGIS).
>
>
>
and
>
> spatialite\_osm\_raw
>
>
> ...
>
>
> The intended goal of this tool is not at all to produce a DB-file usable by GIS applications: it's instead the one to get a DB-file you can use in order to gather statistical infos, to support some post-processing task and so on.
>
>
>
The easiest way forward is to work through the [spatialite\_osm\_map example](https://www.gaia-gis.it/fossil/spatialite-tools/wiki?name=spatialite_osm_map), then try it with with your data set, then introduce QGIS.
You probably don't need the spatialite\_osm\_net part, unless you're trying to construct a routing system.
|
1,767 |
Any Bitcoin wallet holds several bitcoin addresses. Such addresses are either generated manually from the GUI addressbook or automatically collecting the ["change"](https://bitcoin.stackexchange.com/questions/1629/why-does-bitcoin-send-the-change-to-a-different-address) of a "Send" transaction. The total balance is the sum of the credit of all addresses.
Why does the Bitcoin software not tell me ADDRESS1 holds 1 BTC while ADDRESS2 has 5BTC?
The standard Bitcoin client automatically selects an address to send from. (From the comments, I learned that there [exits a patch](https://bitcoin.stackexchange.com/questions/437/how-can-i-find-out-the-address-my-payment-will-come-from/453#453), which allows a user to choose an address to sent from.)
Does the behaviour of the standard client described here have any advantages over letting the user choose?
|
2011/10/27
|
[
"https://bitcoin.stackexchange.com/questions/1767",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/350/"
] |
Having different addresses in the client is intended for increasing anonymity and for you to be able to identify different senders. It is not intended to be used as different "accounts". The concept of accounts actually *does* exist in bitcoind but it is not currently used in the client. It wouldn't be too hard to add, so it is possible that it will be added in the future if there is demand for it.
Normally a user is not interested in the details of specifying what address to send funds from. The client does a good job of choosing what input addresses to use and will for example use older ones first in order to reduce fees.
|
97,351 |
I am working for a small finance firm as a Web Application Developer. Our company has an interal website coded in PHP and running on Apache. Recently our server went down and the website was down for several days causing severe problems.
I have been asked to setup two more servers for serving the website. So we want three Apache Web/App servers running on three different machines. When a user logs into the website, he must be servered by one of the three servers depending on the load. Also if one or two of the servers go down, the server which is up must handle the website requests.
I just know creating a website in PHP and hosting it on an Apache server. I dont have any knowledge of networking. Please tell me what I need to learn for creating the above mentioned system.
I am not expecting to be spoon fed. Just need a pointer to what I have to learn to achieve my goal. I'm Googling simultaneously but have asked this question here as I am in hurry to implement it.
|
2009/12/25
|
[
"https://serverfault.com/questions/97351",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] |
A common approach is to develop web-applications that are aware of clustering. You'll probably need to remake your site's basics that's related to database, sessions, shared and dynamic data. I'm sure my question will make you interested: [Cloud/cluster solutions for scalable web-services](https://serverfault.com/questions/84715/nix-cloud-cluster-solutions-for-scalable-web-services). To make a website 'scalable' you'll need to create a scalable design. Alas, there's no button with "Make it faster" written below :)
A simple way is to replicate all data between these servers (you may use [GlusterFS](http://en.wikipedia.org/wiki/GlusterFS) for files, and replicate your MySQL/whatever between these servers) and ensure all sessions are available from all of them! It's not the best suggestion, but you won't have to remake your code :)
Load-balancing can be easily implemented with Round-Robin DNS: just add several 'A' records that point to different servers and they'll be picked randomly by clients. For instance, Google has this feature:
```
$ host -t a google.com
google.com has address 74.125.87.147
google.com has address 74.125.87.103
google.com has address 74.125.87.104
google.com has address 74.125.87.99
google.com has address 74.125.87.105
```
|
63,507,901 |
i have a python script that create a json and i have a nodejs script that read the json:
* python script
```
with open("music.json", "w") as write_file:
json.dump(music_found, write_file, indent=4)
```
*music\_found is an array of object*
* nodejs
```
import fs from 'fs'
import { cwd } from 'process';
let rawdata = fs.readFileSync(`${cwd()}/music.json`);
let music = JSON.parse(rawdata)
console.log(music);
```
**i get the message unexpected end of json input**
* json example
```
[
{
"user": "some_user1",
"file": "@@enlbq\\_Music\\Infected Mushroom\\Return to the Sauce [2017] [HMCD94]\\09 - Infected Mushroom - Liquid Smoke.flac",
"size": 42084572,
"slots": true,
"speed": 1003176
},
{
"user": "some_user2",
"file": "@@xfjpb\\Musiikkia\\Infected Mushroom\\Return to the Sauce\\09 Infected Mushroom - Liquid Smoke.flac",
"size": 24617421,
"slots": true,
"speed": 541950
},
{
"user": "some_user3",
"file": "@@rxjpv\\MyMusic\\Infected Mushroom\\Infected Mushroom - Return To The Sauce (2017) [CD FLAC]\\09 - Liquid Smoke.flac",
"size": 41769608,
"slots": true,
"speed": 451671
}
]
```
my json is well formatted no ? i'm on that since 4hours and im stuck on it... very annoying ^^ hope somehone help
|
2020/08/20
|
[
"https://Stackoverflow.com/questions/63507901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4476248/"
] |
[readFileSync](https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options)
>
> If the encoding option is specified then this function returns a
> string. Otherwise it returns a buffer.
>
>
>
You need to either set the encoding or use the buffer's [.toString(](https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end)) method
|
68,506,902 |
I intend to use an array to insert into my database, but only the first data have been inserted into the database and did not insert the other value, below is my code.
```
$orderID=mysqli_insert_id($con);
$query2="INSERT INTO user_order(orderID, productName,productPrice, Quantity) VALUES (?,?,?,?)";
$stmt=mysqli_prepare($con,$query2);
mysqli_stmt_bind_param($stmt,"isii", $orderID, $productName, $productPrice, $Quantity);
foreach($_SESSION['cart'] as $key => $values)
{
$productName = $values['Item_Name'];
$productPrice = $values['Price'];
$Quantity = $values['Quantity'];
mysqli_stmt_execute($stmt);
}
```
|
2021/07/24
|
[
"https://Stackoverflow.com/questions/68506902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15408227/"
] |
You can try:
```
foreach ($records as $row) {
$fieldVal1 = mysql_real_escape_string($records[$row][0]);
$fieldVal2 = mysql_real_escape_string($records[$row][1]);
$fieldVal3 = mysql_real_escape_string($records[$row][2]);
$query ="INSERT INTO programming_lang (field1, field2, field3) VALUES ( '". $fieldVal1."','".$fieldVal2."','".$fieldVal3."' )";
mysqli_query($conn, $query);
}
```
|
417,096 |
I have a 128 GB SSD Managed disk in Linux - CentOS 7.3. The root partition now shows 30 GB approx and is mounted under "/", ie root. lsblk shows the remaining - So we are good for now.
My requirement is that I need 20 GB under "/" and the remaining 108 GB approx in /opt. Please be careful - the machine is running on Azure.
The root partition is partitioned as XFS. It's a physical partition - meaning no LVM. Please help.
Thanks in advance.
|
2018/01/14
|
[
"https://unix.stackexchange.com/questions/417096",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/270238/"
] |
@Lambo-Fan 128 GB SSD is your Data disk, you cannot merge data disk to OS disk. you need to expand OS disk seperatly, Microsoft Azure have a functionality to increase OS disk. Please follow the below steps to increase OS disk for CentOS/RHEL/Ubuntu
Follow the following steps from the Azure Portal:
1. Login portal.azure.com open the VM and Go to the VM Overview pane and stop the VM
2. Once the VM is Stopped (deallocated) state, go to the Disks pane
3. Click on the OS disk link
4. Enter the new size in the Size text box and click on Save
5. Once the operation is completed, go back to the VM Overview pane and click on Start
For Red Hat 7.x / CentOS 7.x :
1) Login to the VM using SSH, we can check the size of the disk by using:
lsblk
=====
2) To proceed with the partition resize, we will use:
sudo fdisk /dev/sda
===================
type: **p**
this will show both partitions /dev/sda1 and /dev/sda2 which are basically partitions 1 and 2
type: **d** then 2 (to delete partition 2)
type: **n** then p, 2 (to recreate partition 2) you can accept the default values
type: **w** (to save the new partition)
type: **q** (to exit fdisk)
sudo reboot (to reboot the VM so the partition is updated)
3) To finalize the resize, after the reboot, execute the command:
For Red Hat 7.3 and CentOS 7.3:
sudo xfs\_growfs /dev/sda2
==========================
4) Use the command: df -h to verify its size:
Filesystem Size Used Avail Use% Mounted on
/dev/sda2 100G 1.6G 98G 2% /
Below document will help more inforation to increase the OS Disk
**How to: Resize Linux osDisk partition on Azure**
<https://blogs.msdn.microsoft.com/linuxonazure/2017/04/03/how-to-resize-linux-osdisk-partition-on-azure/>
|
64,936,872 |
I'm trying to render an XML file when pointing to [www.example.com/sitemap.xml](http://www.example.com/sitemap.xml). Since the project was developed using Next.js, the routing works with the js files stored in the pages directory:
* example.com/help -> help.js
* example.com/info -> info.js
So, is there any way to achieve this by avoiding accessing the backend?
|
2020/11/20
|
[
"https://Stackoverflow.com/questions/64936872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14678133/"
] |
**JS Version**
/pages/sitemap.xml.jsx
```
import React from 'react'
class Sitemap extends React.Component {
static async getInitialProps({ res }) {
res.setHeader('Content-Type', 'text/xml')
res.write(`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
...
</urlset>`)
res.end()
}
}
export default Sitemap
```
**TS Version**
/pages/sitemap.xml.tsx
```
import { GetServerSideProps } from 'next'
import React from 'react'
const Sitemap: React.FC = () => null
export const getServerSideProps: GetServerSideProps = async ({ res }) => {
if (res) {
res.setHeader('Content-Type', 'text/xml')
res.write(`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
</urlset>`)
res.end()
}
return {
props: {},
}
}
export default Sitemap
```
**API Version**
/pages/api/sitemap.xml.tsx
```
import type { NextApiRequest, NextApiResponse } from 'next'
import { getAllContentPagesQuery, getAllShopProductsQuery } from './utils/requests'
export default async (req: NextApiRequest, res: NextApiResponse<string>) => {
const pages = await getAllContentPagesQuery()
const products = await getAllShopProductsQuery()
const frontUrl = "https://localhost:3000"
const pagesAndSlugs = [...pages, ...products].map(url => ({
url: `${frontUrl}${'Variations' in url ? '/product/' : '/'}${url.slug}`, // -> /page1, /product/myproduct...
updatedAt: url.updatedAt,
}))
const urls = pagesAndSlugs.map(
({ url, updatedAt }) => `
<url>
<loc>${url}</loc>
<lastmod>${new Date(updatedAt).toISOString()}</lastmod>
</url>
`
)
.join('')
res
.setHeader('Content-Type', 'text/xml')
.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
)
.status(200)
.send(`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls}
</urlset>`)
}
```
:D
|
10,628,786 |
Alright guys, so I have a script set up to turn off the "require password on wake" function when I am at home. It pings my phone to see if I am connected to the network, and if not turns on lock to wake. So:
```
try
do shell script "ping -c2 X.X.X.X"
set theResult to the result
if theResult contains " 2 packets received," then
tell application "System Events"
tell security preferences
get properties
set properties to {require password to wake:false, require password to unlock:false}
end tell
end tell
end if
on error
tell application "System Events"
tell security preferences
get properties
set properties to {require password to wake:true, require password to unlock:true}
end tell
end tell
end try
end
```
This works just fine, however it asks to authenticate. I don't really want to use the enter text & return route, nor the clipboard route, because I don't want the password in the script... so is there a way to avoid the authentication?
|
2012/05/17
|
[
"https://Stackoverflow.com/questions/10628786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1392321/"
] |
If your goal is to enable/disable "password on wake" rather than to run that particular script without authentication, use either
```
tell application "System Events"
set require password to wake of security preferences to true
end tell
```
or
```
do shell script "defaults write com.apple.screensaver -int 1"
```
and the same with "to false" and "-int 0" to turn the setting off. None of these require authentication, as they're simply changing a user-level preference (stored in
```
~/Library/Preferences/com.apple.screensaver.plist
```
on my system, though this is an implementation detail you shouldn't rely on).
What triggers the authentication dialog in your script is the other property, "require password to unlock", equivalent to the "Require an administrator password to access locked preferences" option in the "Advanced..." part of Security Preferences. Under the hood, *this* option is equivalent to changing a number of settings in the Authorization Services database,
```
/private/etc/authorization
```
controlling whether various *system-wide* preferences may be left unlocked for unauthenticated changes.
System Events does appear to have a (less serious) bug, however: on my systems, setting "require password to unlock" has no effect, whether I authenticate as an admin or not.
|
313,929 |
I have a bunch of mp3s I've organised into a playlist for a party. What I'd like to be able to do is easily rename these files so that they start with the position in the playlist:
```
001.Track.mp3
002.Track.mp3
.
.
.
```
Then they can simply be played in alphabetical order. Is this possible without just doing it manually?
|
2013/06/28
|
[
"https://askubuntu.com/questions/313929",
"https://askubuntu.com",
"https://askubuntu.com/users/48602/"
] |
You could try something like this:
I'm not sure if it needs something more but this should work.
```
cat playlist.m3u | I=1 while read file; do
mv $file $I.$file.mp3;
I=$I + 1;
done;
```
Edit: You could need I=`expr $I + 1'; instead of I=$I + 1;
|
41,122,536 |
I'm working on UWP version of the application which currently in the Store but for Windows Phone 8. The WP8 version have some local data which I need to convert to new format when UWP version starting. How can I debug that process ?
I've tried to associate UWP version with same store app name and then deployed package on the device where WP8 version was. But new version has not replaced old one.
I see one way: create fake app in the store, upload old package, install on device, then upload new package and update. But it too painfull...
|
2016/12/13
|
[
"https://Stackoverflow.com/questions/41122536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2639219/"
] |
You can create an Advanced filter that combines the relevant parts for you:
[](https://i.stack.imgur.com/PC3qx.png)
The output would be `/article/edit` or `/article/add`, with everything and anything between those removed.
**EDIT**:
If you just want everything, regardless of `/edit`, `/add`, `/12341/edit`, `/7305/add`, `/whatever/edit`, to show up just as `/article`, then you can just change your filter like this:
`Field A`: Request URI = (/article)/.\*
`Output to`: Request URI = $A1
This will convert the following examples:
* /article/123/edit -> /article
* /article/2345/add -> /article
* /article/anything -> /article
|
38,185,620 |
I tried following steps to build V8 for Android.
1.Install depot\_tools
```
git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git
export PATH=`pwd`/depot_tools:"$PATH"
```
2. run βfetch v8β to download the code and all dependencies.
3. cd to v8 and run βmake ia32.releaseβ to build.
4. make android\_arm.release -j16 android\_ndk\_root=[full path to ndk]
Step 3 build successfully and got the libraries.
While 4 failed because can't find some standard headers.
```
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' file not found
#include_next <stdio.h>
^
In file included from ../src/api.cc:5:
In file included from .././src/api.h:8:
In file included from .././include/v8-testing.h:8:
In file included from ../include/v8.h:20:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' file not found
#include_next <stdio.h>
^
In file included from ../src/asmjs/asm-wasm-builder.cc:5:
In file included from .././src/v8.h:8:
In file included from .././include/v8.h:20:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' file not found
#include_next <stdio.h>
^
In file included from ../src/asmjs/typing-asm.cc:5:
In file included from .././src/asmjs/typing-asm.h:8:
In file included from .././src/allocation.h:8:
In file included from .././src/globals.h:11:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/ostream:138:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/ios:215:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/iosfwd:90:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/wchar.h:119:15: fatal error: 'wchar.h' file not found
#include_next <wchar.h>
^
In file included from ../src/accessors.cc:5:
In file included from .././src/accessors.h:8:
In file included from .././include/v8.h:20:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' file not found
#include_next <stdio.h>In file included from
../src/assembler.cc: ^35
:
In file included from .././src/assembler.h:38:
In file included from .././src/allocation.h:8:
In file included from .././src/globals.h:11:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/ostream:138:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/ios:215:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/iosfwd:90:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/wchar.h:119:15: fatal error: 'wchar.h' file not found
#include_next <wchar.h>
^In file included from
../src/arguments.cc:5:
In file included from .././src/arguments.h:8:
In file included from .././src/allocation.h:8:
In file included from .././src/globals.h:11:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/ostream:138:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/ios:215:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/iosfwd:90:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/wchar.h:119:15: fatal error: 'wchar.h' file not found
#include_next <wchar.h>
^
In file included from ../src/api-experimental.cc:9:
In file included from .././src/api-experimental.h:8:
In file included from .././src/handles.h:8:
In file included from .././include/v8.h:20:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' file not found
#include_next <stdio.h>
^
In file included from ../src/address-map.cc:5:
In file included from .././src/address-map.h:8:
In file included from .././src/assert-scope.h:9:
In file included from .././src/base/macros.h:8:
In file included from .././src/base/compiler-specific.h:8:
.././include/v8config.h:14:11: fatal error: 'TargetConditionals.h' file not found
# include <TargetConditionals.h>
^
In file included from ../src/allocation.cc:5:
In file included from .././src/allocation.h:8:
In file included from .././src/globals.hIn file included from :../src/asmjs/asm-types.cc11::
5In file included from :
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/ostreamIn file included from :.././src/v8.h138::
8In file included from :
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/iosIn file included from :.././include/v8.h215::
20In file included from :
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/iosfwd:/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/stdio.h90::
108:15/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/wchar.h:: 119:15:fatal error : fatal error'stdio.h': file 'wchar.h'not filefound not
found
#include_next <stdio.h>
^
#include_next <wchar.h>
^
In file included from ../src/assert-scope.ccIn file included from ../src/ast/ast-expression-rewriter.cc:5:
In file included from .././src/ast/ast.h:8:
In file included from .././src/ast/ast-value-factory.h:31:
In file included from .././src/api.h:8:
In file included from .././include/v8-testing.h:8:
In file included from ../include/v8.h:20:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' file not found
#include_next <stdio.h>
^
:5:
In file included from .././src/assert-scope.h:9:
In file included from .././src/base/macros.h:8:
In file included from .././src/base/compiler-specific.h:8:
.././include/v8config.h:14:11: fatal error: 'TargetConditionals.h' file not foundIn file included from
../src/api-arguments.cc:5:
In file included from .././src/api-arguments.h:8:
In file included from .././src/api.h:8:
In file included from .././include/v8-testing.h:8:
In file included from ../include/v8.h:20:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' # include <TargetConditionals.h>file
not ^found
#include_next <stdio.h>
^In file included from
../src/asmjs/asm-js.cc:5:
In file included from .././src/asmjs/asm-js.h:9:
In file included from .././src/allocation.h:8:
In file included from .././src/globals.h:11:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/ostream:138:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/ios:215:
In file included from /Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/iosfwd:90:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/wchar.h:119:15: fatal error: 'wchar.h' file not found
#include_next <wchar.h>
^
In file included from ../src/allocation-site-scopes.cc:5:
In file included from .././src/allocation-site-scopes.h:8:
In file included from .././src/ast/ast.h:8:
In file included from .././src/ast/ast-value-factory.h:31:
In file included from .././src/api.h:8:
In file included from .././include/v8-testing.h:8:
In file included from ../include/v8.h:20:
/Users/philip/v8/third_party/llvm-build/Release+Asserts/bin/../include/c++/v1/stdio.h:108:15: fatal error: 'stdio.h' file not found
#include_next <stdio.h>
^
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/allocation.o] Error 1
make[2]: *** Waiting for unfinished jobs....
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/asmjs/asm-types.o] Error 1
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/address-map.o] Error 1
1 error generated.
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/arguments.o] Error 1
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/api-natives.o] Error 1
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/api-arguments.o] Error 1
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/api-experimental.o] Error 1
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/allocation-site-scopes.o] Error 1
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/ast/ast-expression-rewriter.o] Error 1
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/assert-scope.o] Error 1
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/accessors.o] Error 1
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/asmjs/asm-js.o] Error 1
1 error generated.
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/asmjs/asm-wasm-builder.o] Error 1
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/asmjs/typing-asm.o] Error 1
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/assembler.o] Error 1
1 error generated.
make[2]: *** [/Users/philip/v8/out/android_arm.release/obj.host/v8_base/src/api.o] Error 1
make[1]: *** [android_arm.release] Error 2
make: *** [android_arm.release] Error 2
```
|
2016/07/04
|
[
"https://Stackoverflow.com/questions/38185620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3126678/"
] |
Finaly i have find a simple answer, i just removed the permalink from costum post
adding this 2 settings
```
'public' => false,
'show_ui' => true,
```
Now all it seems to be ok.
Thank you for help.
|
27,370,116 |
I hv two tables which are tbl\_product1 and tbl\_product2.
**tbl\_product1 :**
```
model_name
lot_num
status_prod1
datecreated
date_received
```
**tbl\_product2:**
```
model_name
lot_num
status_prod2
last_date
```
I want to combine model\_name between this two table and lot\_num as well in one column. Then join status\_prod1, datecreated, date\_received from tbl\_prod1 and status\_prod2, last\_date.
**My sql query :**
```
$query = "SELECT c.model_name, c.lot_num, c.s1, c.s2, c.datecreated, c.date_received, c.last_date
FROM (SELECT model_name, lot_num, status_prod1 AS s1, NOT NULL AS s2, datecreated, date_received, NULL AS last_date FROM tbl_product1 WHERE status_prod1 = 'sent' UNION SELECT model_name, lot_num, NOT NULL AS s1, status_prod2 AS s2, NULL AS datecreated, NULL AS date_received, last_date FROM tbl_product2 WHERE status_prod2 = 'sent')c
ORDER BY model_name, lot_num ASC";
```
But the result is not as my expectation. When I run this query, it display double lot\_num and model\_name. I dont know how to explain.
For example when i running my code this output will display :
```
model_name | lot_num | status_prod1 | status_prod2
---------------------------------------------------
magic1 | 001 | sent |
magic1 | 001 | | sent
sss | 100 | sent |
ddd | 222 | sent |
ddd | 222 | | sent
```
**Supposely the table should like this :**
```
model_name | lot_num | status_prod1 | status_prod2
---------------------------------------------------
magic1 | 001 | sent | sent
sss | 100 | sent |
ddd | 222 | sent | sent
```
|
2014/12/09
|
[
"https://Stackoverflow.com/questions/27370116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408496/"
] |
What you need to do is use the removeClass() function on the other elements where you are adding the class in your directive.
As an example, if all other are anchor tags you could use the following code:-
```
element.parent().find("a").removeClass("active-tab"); //add this to remove class from other elements
element.addClass("active-tab"); //you already have this
```
Check out this plnkr:-Β <http://plnkr.co/edit/Re6EAL6XRsKHqqHPq5kw?p=preview>
As for your border problem, as skv said in his answer, you have set the border on both the element and hover styles. Just remove the border from hover and it'll work as you expect it to.
|
67,829,474 |
I have a very, very simple React application. When I run npm start I receive this error.
```
Compiling...
C:\Users\DawsonSchaffer\node_modules\react-scripts\scripts\start.js:19
throw err;
Compiling...
C:\Users\DawsonSchaffer\node_modules\react-scripts\scripts\start.js:19
throw err;
Compiling...
C:\Users\DawsonSchaffer\node_modules\react-scripts\scripts\start.js:19
throw err;
Compiling...
C:\Users\DawsonSchaffer\node_modules\react-scripts\scripts\start.js:19
throw err;
^
[Error: ENOENT: no such file or directory, stat 'C:\Users\DawsonSchaffer\Documents\My Music'] {
errno: -4058,
code: 'ENOENT',
syscall: 'stat',
path: 'C:\\Users\\DawsonSchaffer\\Documents\\My Music'
}
Compiling...
C:\Users\DawsonSchaffer\node_modules\react-scripts\scripts\start.js:19
throw err;
Compiling...
C:\Users\DawsonSchaffer\node_modules\react-scripts\scripts\start.js:19
throw err;
Compiling...
C:\Users\DawsonSchaffer\node_modules\react-scripts\scripts\start.js:19
throw err;
Compiling...
C:\Users\DawsonSchaffer\node_modules\react-scripts\scripts\start.js:19
throw err;
^
[Error: ENOENT: no such file or directory, stat 'C:\Users\DawsonSchaffer\Documents\My Music'] {
errno: -4058,
code: 'ENOENT',
syscall: 'stat',
path: 'C:\\Users\\DawsonSchaffer\\Documents\\My Music'
}
```
Here is my package.json
```
{
"name": "create-react-app-example",
"version": "0.1.0",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"dependencies": {
"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-scripts": "3.2.0"
},
"devDependencies": {
"react-cosmos": "^5.0.0-beta.15"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
```
I'm not sure why it's showing My Music directory but that's probably unrelated. I have installed, reinstall (globally): webpack, webpack-dev, and react-scripts. I have cleared the cache severl time to no avail. I happy to provide more detail, but as of now I'm not sure what else to look for or add. Any help would be greatly appreciated.
Thanks
Dawson
|
2021/06/03
|
[
"https://Stackoverflow.com/questions/67829474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13546751/"
] |
You never operate on the original list. In each loop iteration, you create a new list (`lst[1:]`) derived from the previous value, and then assign that to your local variable `lst`.
If you want to change the original list, then use list-altering methods, such as
```
lst.pop()
```
|
35,225 |
I'm currently working through a research paper on beam forming. In this paper a magnitude compensation is introduced to compensate for frequency dependency. Due to other calculations low frequencies are lower in magnitude than high frequencies.
To compensate for the frequency dependency they multiply the signal with:
$$
\frac{1}{(j \omega)^n}
$$
I know when $n = 1$, the formula is just a simple integrator. But I don't understand what happens when $n$ is higher, and how I should implement it in MATLAB.
|
2016/11/01
|
[
"https://dsp.stackexchange.com/questions/35225",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/24545/"
] |
Since the Bilateral Filter is Spatial Invariant and Non Linear (The output is linear combination of the data, yet the weights depends on the data in Non Linear fashion) it can't be formulated as a Spatially Invariant Filter / Convolution.
So the Low Pass / High Pass concept in it classic form doesn't hold here.
Yet you can still employ the Image Pyramid concept here with your operator being the Bilateral filter and everything will work perfectly (Namely perfect reconstruction).
It is actually very effective.
|
108,100 |
I have been facing the following "problems" with my department head at an undergraduate institute. I joined it just under a year ago and am already facing (what appears to be) a lot of negativity from her. Here are my main problems:
1) Last semester, she would always come to me/email me telling me what a couple of students said/complained about me - mostly being that I am tough and expecting them to study more - well, it is Physics, you can't just enter the classroom as if you are entering a cinema and expect entertainment - one has to be prepared! Anyhow, I am pretty sure she was asking students "how is the new guy?" which encouraged this behaviour from students - she implied it once during lunch.
2) Towards the end, she failed to put an end to disruptive (and borderline racist) behaviour from one of the students in spite of my complaints, but kept on encouraging it instead of nipping it in the bud when it happened first.
3) Moreover, I am continuously discouraged in collaborating with another department - I haven't had any problems with them so far.
4) A few months ago, when I sent in the new syllabus for this semester (it has to pass through the Dept Head before being posted on the website), she said she wasn't OK with it - it didn't have anything unusual!
5) And now, when I wanted to add points for interaction in the syllabus for the next semester - as positive reinforcement (instead of penalising students), she gave a straight no, and asked me to give her a scientific paper proving that it is effective! I mean.. really?
6) To be in students' good books and get good feedback, she is encouraging a manipulative student - she helps him in doing homework and he will be taking a summer "reading course" with her. So, now this student doesn't have to sit in my course or pass it, and yet complains all the time which is encouraged by her.
I know these things are pretty vague but are definitely giving me a lot of negative vibes... Any advice as of how to face this situation? It looks like she is building a way to get my lose this job or make me go... Or am I just being too "sensitive" about it?
PS - She pretty much has the regular Dept Chair power -- my annual performance review should pass through her, teaching assignments pass through her, etc.
PPS - The disruptive student's concern was that the grade on the website wasn't correct where as everything was as it is supposed to be - she acted like a middle-man everytime he was trying to cause trouble instead of either directing him directly to me or atleast recommending that or telling him that disruptive behaviour is not OK. The manipulative student gets a slap on the wrist for blatantly lying about grades, quiz, etc, she helps him in getting his homework done - he is supposed to do it on his own!
|
2018/04/13
|
[
"https://academia.stackexchange.com/questions/108100",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/91361/"
] |
Department chairs should solicit feedback from students and they should insist that teaching practices be based on evidence. That's normal. But it sounds like this department chair is using these mechanisms to be a bully. That's bad.
My advice would be:
1. Document everything.
2. Consult your university's omsbudsperson.
3. Study up on your institutions procedures. There may be something that keeps the department chair accountable, such as an election. We do not know your institutions specific regulations.
4. Develop good relationships with the dean and other faculty in your department. The chair often has little power on their own.
5. Look for a new job.
6. Keep in mind that department chairs often have no training for the job and may not like being chair. Do not be surprised if they are bad at their job.
|
35,323,332 |
I have two queries that are similar:
```
StoreQuery.group(:location).count(:name)
```
vs
```
StoreQuery.group(:location).select('DISTINCT COUNT(name)')
```
I was expecting the results to be exactly the same but they're not. What is the difference between the two?
|
2016/02/10
|
[
"https://Stackoverflow.com/questions/35323332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443582/"
] |
The difference is that the first query counts all names, and the second query counts unique names, ignoring duplicates. They will return different numbers if you have some names listed more than once.
|
20,424,070 |
I'm simply loading an image on button click via url , i want progress bar to show downloadin done,0-100 now i had changed the code not showing the progress updation but only progress bar
kindly help. XML has a button [downloadbtn], and a progressbar, imageview and a quit button
mainfest.xml has acsess permission internet
-------------------------------------------
code:
```
*
package com.example.t4;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ProgressBar prgs;
ProgressTask task = new ProgressTask();
Button showProgressBtn;
Button stopProgressBtn;
ImageView img;
Bitmap bmp ;
TextView tv1;
int filesize,filedyn;
public void startdownload(){
try { URL url;
url = new URL("http://whywedoit.files.wordpress.com/2009/04/smile.jpg");
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
filesize = urlConnection.getContentLength();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.tv1);
img = (ImageView) findViewById(R.id.imageView1) ;
stopProgressBtn = (Button) findViewById(R.id.btnCancel);
prgs = (ProgressBar) findViewById(R.id.progress);
showProgressBtn = (Button) findViewById(R.id.btn);
prgs.setVisibility(View.INVISIBLE);
img.setVisibility(View.INVISIBLE);
tv1.setVisibility(View.INVISIBLE);
final ProgressTask pgt = new ProgressTask();
showProgressBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(pgt.getStatus()==Status.RUNNING){Toast.makeText(getApplicationContext(), "Status"+pgt.getStatus(), Toast.LENGTH_SHORT).show();}
if(pgt.getStatus()==Status.FINISHED||pgt.getStatus()==Status.PENDING){
Toast.makeText(getApplicationContext(), "Status"+pgt.getStatus(), Toast.LENGTH_SHORT).show();
prgs.setVisibility(View.VISIBLE);
task.execute(10);
tv1.setVisibility(View.VISIBLE);
}}
});
stopProgressBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
stopProgress();
}
});
}
private class ProgressTask extends AsyncTask<Integer,Integer,Void>{
protected void onPreExecute() {
super.onPreExecute();
prgs.setMax(100); // set maximum progress to 100.
}
protected void onCancelled() {
prgs.setMax(0); // stop the progress
Log.v("Progress","Cancelled");
finish();
}
protected Void doInBackground(Integer... params) {
startdownload();
//for(int j=0;j<=filesize;j++){
publishProgress((int) ((filedyn / (float) filesize) * 100));
//}
Log.v("Progress","Downloading");
return null;
}
protected void onProgressUpdate(Integer... values) {
prgs.setProgress(0);
Log.v("Progress","Updating");
}
protected void onPostExecute(Void result) {
img.setVisibility(View.VISIBLE);
tv1.setVisibility(View.INVISIBLE);
img.setImageBitmap(bmp);
prgs.setVisibility(View.INVISIBLE);
Log.v("Progress", "Finished");
}
}
public void stopProgress() {
task.cancel(true);
}
}
*
```
|
2013/12/06
|
[
"https://Stackoverflow.com/questions/20424070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2496474/"
] |
For starters, it's pretty standard to post explain plans to <http://explain.depesz.com> - that'll add some pretty formatting to it, give you a nice way to distribute the plan, and let you anonymize plans that might contain sensitive data. Even if you're not distributing the plan it makes it a lot easier to understand what's happening and can sometimes illustrate exactly where a bottleneck is.
There are countless resources that cover interpreting the details of postgres explain plans (see <https://wiki.postgresql.org/wiki/Using_EXPLAIN>). There are a lot of little details that get taken in to account when the database chooses a plan, but there are some general concepts that can make it easier. First, get a grasp of the page-based layout of data and indexes (you don't need to know the details of the page format, just how data and indexes get split in to pages). From there, get a feel for the two basic data access methods - full table scans and index scans - and with a little thought it should start to become clear the different situations where one would be preferred to the other (also keep in mind that an index scan isn't even always possible). At that point you can start looking in to some of the different configuration items that affect plan selection in the context of how they might tip the scale in favor of a table scan or an index scan.
Once you've got that down, move on up the plan and read in to the details of the different nodes you find - in this plan you've got a lot of hash joins, so read up on that to start with. Then, to compare apples to apples, disable hash joins entirely ("set enable\_hashjoin = false;") and run your explain analyze again. Now what join method do you see? Read up on that. Compare the estimated cost of that method with the estimated cost of the hash join. Why might they be different? The estimated cost of the second plan will be higher than this first plan (otherwise it would have been preferred in the first place) but what about the real time that it takes to run the second plan? Is it lower or higher?
Finally, to address this plan specifically. With regards to that sort that's taking a long time: distinct is not a function. "DISTINCT(id)" does not say "give me all the rows that are distinct on only the column id", instead it is sorting the rows and taking the unique values based on all columns in the output (i.e. it is equivalent to writing "distinct id ..."). You should probably re-consider if you actually need that distinct in there. Normalization will tend to design away the need for distincts, and while they will occasionally be needed, whether they really are super truly needed is not always true.
|
26,517,713 |
I'm getting a `NullPointerException`, when my `submittedAnswers()` method calls the `countAnswers()` method, but I have checked my `HashMap` and it contains the correct information. What am I doing wrong?
```
if (database.get(i).equals('A'))
```
error starts at ^^
```
private int countA, countB, countC, countD; // counters for the different answers
HashMap<Integer, Character> database = new HashMap<Integer, Character>();
public void countAnswers()
{
while(!database.isEmpty())
{
for(int i = 0; i < database.size(); i++)
{
if (database.get(i).equals('A'))
{
countA++;
}
if (database.get(i).equals('B'))
{
countB++;
}
if (database.get(i).equals('C'))
{
countC++;
}
if(database.get(i).equals('D'))
{
countD++;
}
}
}
}
/*
* checks if the student has submitted or not, if the student
* has then it removes the student and submits the new submittion,
* if not than just submits the student. then calls to counts the submitted answers
*/
public void sumbittedAnswers(int studentID, char answer)
{
if(database.containsKey(studentID))
{
database.remove(studentID);
database.put(studentID, answer);
}
else
database.put(studentID, answer);
countAnswers();
}
```
|
2014/10/22
|
[
"https://Stackoverflow.com/questions/26517713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3646746/"
] |
```
import java.util.ArrayList;
public class EliminateDuplicates {
//This is called Generics, It'll be a little later in your studies
public static <E> ArrayList<E> eliminateDuplicates(ArrayList<E> list) {
ArrayList<E> newList = new ArrayList<>(list.size());
for (E aList : list) { // for (int i = 0; i <= list.lenght; i++){
if (!newList.contains(aList)) {
newList.add(aList);
}
}
return newList;
}
public static void main(String[] args) {
ArrayList<Integer> tenNumbers = new ArrayList<Integer>();
tenNumbers.add(14);
tenNumbers.add(24);
tenNumbers.add(14);
tenNumbers.add(42);
tenNumbers.add(25);
tenNumbers.add(24);
tenNumbers.add(14);
tenNumbers.add(42);
tenNumbers.add(25);
tenNumbers.add(24);
ArrayList<Integer> newList = eliminateDuplicates(tenNumbers);
System.out.print("The distinct numbers are: " + newList);
}
}
```
|
46,054,147 |
I am trying to replicate the code and issue from below stack overflow question [`Sankey diagram in R`](https://stackoverflow.com/questions/34571899/sankey-diagram-in-r)
Adding some sample data
```
head(links) #Data.frame
Source Target Weight
Fb Google 20
Fb Fb 2
BBC Google 21
Microsoft BBC 16
head(nodes)
Fb
BBC
Google
Microsoft
```
Code for building a sankey transition flow
```
sankeyNetwork(Links = links,
Nodes = nodes,
Source = "Source",
Target = "Target",
Value = "value",
fontSize = 12,
nodeWidth = 30)
```
The above mentioned stack overflow posts mentions that the source and target should be indexed at 0. However if I try the same syntax, I get NA's in my Source and Target. What could be causing this error?
|
2017/09/05
|
[
"https://Stackoverflow.com/questions/46054147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6019081/"
] |
You should add another event for the checkbox, so the values will update if the checked state changes.
```
$(document).ready(function(){
$('#a1').keyup(calculate);
$('#a2').keyup(calculate);
$('#a3').keyup(calculate);
$(".checkbox_check").change(calculate);
});
```
|
3,487,854 |
I am having trouble proving that product of two coprime $a$ and $b$ can never generate a number multiple of some greater number which is coprime to both $a$ and $b$.
|
2019/12/26
|
[
"https://math.stackexchange.com/questions/3487854",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/338544/"
] |
Yep! Consider $f(x)=-(x+1)^3$. There are five real roots to $f(x)=f^{-1}(x)$. [](https://i.stack.imgur.com/cVsam.png)
|
40,812,787 |
I am trying to deploy an asp.net core app on a server. I have done the following steps.
first thing is first, this is an Windows Server 2012 r2 environment that is a brand new virtual machine.
1. build the VM
2. update all ms updates
3. add iis role
4. insure asp.net 3.5 and 4.5 are installed on machine
5. insure http redirection and static content is installed
6. install .net core bundle
7. publish self contained app from Visual Studio (project name Web)
8. add this to a folder on server.
9. try running from web.exe
I get the console app opens says now listening on: <http://localhost:5000>
10. I go to <http://localhost:5000> from chrome on this machine and get a 404 not found.
I do steps 7 8 9 and 10 on local machine which is windows 10 i get my application.
**project.json**
```
{
"dependencies": {
"AutoMapper": "5.1.1",
"EntityFramework": "6.1.3",
"Microsoft.ApplicationInsights.AspNetCore": "1.0.0",
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
},
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
},
"tools": {
"BundlerMinifier.Core": "2.0.238",
"Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"net452": {
"dependencies": {
"DataAccess": {
"target": "project"
},
"Models": {
"target": "project"
}
}
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"publishOptions": {
"include": [
"wwwroot",
"Views",
"Areas/**/Views",
"appsettings.json",
"web.config"
]
},
"runtimes": {
"win10-x64": {},
"osx.10.11-64": {}
},
"scripts": {
"prepublish": [ "bower install", "dotnet bundle" ],
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
```
**configure from startup.cs**
```
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
Mapper.Initialize(config =>
{
/*View Models*/
config.CreateMap<Permit, PermitViewModel>().ReverseMap();
config.CreateMap<PermitType, PermitTypeViewModel>().ReverseMap();
config.CreateMap<Property, PropertyViewModel>().ReverseMap();
config.CreateMap<Region, RegionViewModel>().ReverseMap();
config.CreateMap<State, StateViewModel>().ReverseMap();
config.CreateMap<User, UserViewModel>().ReverseMap();
/*Dtos*/
config.CreateMap<Permit, PermitDto>().ReverseMap();
config.CreateMap<Property, PropertyDto>().ReverseMap();
config.CreateMap<Region, RegionDto>().ReverseMap();
config.CreateMap<State, StateDto>().ReverseMap();
config.CreateMap<User, UserDto>().ReverseMap();
});
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
```
**program.cs**
```
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
```
my goal is to have this run on iis.
**UPDATE**
>
> Software: Microsoft Internet Information Services 8.5
> =====================================================
>
>
> Version: 1.0
> ============
>
>
> Date: 2016-12-06 23:49:44
> =========================
>
>
> Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus
> ===================================================================================================================================
>
>
> sc-win32-status time-taken 2016-12-06 23:49:44
> fe80::9c6d:a91b:42c:82ea%12 OPTIONS / - 80 -
> fe80::c510:a062:136b:abe9%12 DavClnt - 200 0 0 1139 2016-12-06
> 23:49:47 fe80::9c6d:a91b:42c:82ea%12 OPTIONS /website - 80 -
> fe80::c510:a062:136b:abe9%12 Microsoft-WebDAV-MiniRedir/10.0.14393 -
> 200 0 0 46 2016-12-06 23:49:47 fe80::9c6d:a91b:42c:82ea%12 PROPFIND
> /website - 80 - fe80::c510:a062:136b:abe9%12
> Microsoft-WebDAV-MiniRedir/10.0.14393 - 404 0 2 62 2016-12-06 23:49:47
> fe80::9c6d:a91b:42c:82ea%12 PROPFIND /website - 80 -
> fe80::c510:a062:136b:abe9%12 Microsoft-WebDAV-MiniRedir/10.0.14393 -
> 404 0 2 62
>
>
>
this is the log message that i get
**web.config**
```
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>
</configuration>
```
|
2016/11/25
|
[
"https://Stackoverflow.com/questions/40812787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5197739/"
] |
Please check `"platform": "anycpu"` in platform part:
```
"Microsoft.NETCore.App": {
"version": "1.0.0",
"type": "platform"
},
```
and
```
"buildOptions": {
"platform": "anycpu",
"emitEntryPoint": true,
"preserveCompilationContext": true
},
```
|
364,914 |
I recently migrated a WordPress install from a shared managed host (cPanel) to a VPS. I first installed WordPress on the new server, then installed Migrate Guru and then migrated the install over to the new server.
Everything worked really well, there is just one issue. When I look at the "Site Health" tab I get the following "Critical Issue":
"A plugin has prevented updates by disabling wp\_version\_check()."
This is the only critical issue the WordPress install shows and it wasn't there before the migration.
What I tried so far to fix it without success:
1. Cleared the install and repeat the migration
2. Deactivated all plugins
3. Deleted all plugins
4. Switched to a basic twenty theme
5. Installed "Health Check & Troubleshooting" and activated the troubleshooting feature
None of this helped, it still shows them same error. My new host looked into it and said that they've cross checked the possible logs and syntax of the web application in regards with the error shown in the site health tab but weren't able to find any error based on the event.
**EDIT:**
I added the plugin WP Control to see if I can run wp\_version\_check() manually and I couldn't. Other cron events like wp\_update\_plugins also "Failed to execute" when I tried running them manually.
I added the following line to the wp-config file:
define('ALTERNATE\_WP\_CRON', true)
Now running those cron events manually worked. However, the initial site health issue still persists.
Next I removed the above line from the wp-config file and now the critical site health issue is gone, but two new critical site health issues show:
"The REST API encountered an error"
and
"Your site could not complete a loopback request"
Both show the following error in the description:
"Error: cURL error 28: Operation timed out after 10000 milliseconds... (http\_request\_failed)"
EDIT:
Now, without changing anything the two new Site Health issues disappear and the old one is back:
"A plugin has prevented updates by disabling wp\_version\_check()."
|
2020/04/24
|
[
"https://wordpress.stackexchange.com/questions/364914",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/183362/"
] |
This might not be the issue, but I would install the All In One WP Security & Firewall plugin by "Tips and Tricks HQ" and use that plugin the check your file and directory permissions. Often times file permissions or also file ownership gets messed up in migrations. Seeing as you have deleted all plugins and are running the stock twenty something theme, it might be giving you a false error. Also, you could try reinstalling WP Core. That might help too. Just a thought.
|
71,286,257 |
I have a `DataFrame`
```
df = DataFrame(a = [1,1,2,2,2])
5Γ1 DataFrame
Row β a
β Int64
ββββββΌβββββββ
1 β 1
2 β 1
3 β 2
4 β 2
5 β 2
```
and I want to filter for the groups with let's say 2 rows - ideally with using `Chain` und potentially using `DataFramesMeta` - and I cannot get it to work.
It does work when first creating a separate column for this like so
```
@chain df begin
groupby(:a)
@transform(:rows = length(:a))
@subset(:rows .== 2)
end
2Γ2 DataFrame
Row β a rows
β Int64 Int64
ββββββΌββββββββββββββ
1 β 1 2
2 β 1 2
```
But it doesn't work when doing the same calculating it within `@subset()`. Anyone got a clever solution?
|
2022/02/27
|
[
"https://Stackoverflow.com/questions/71286257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7210250/"
] |
Instead of `subset`, use `filter` for this:
```
julia> @chain df begin
groupby(:a)
filter(:a => a -> length(a) == 2, _)
end
GroupedDataFrame with 1 group based on key: a
First Group (2 rows): a = 1
Row β a
β Int64
ββββββΌβββββββ
1 β 1
2 β 1
julia> # OR:
julia> @chain df begin
groupby(:a)
filter(_) do subdf
length(subdf.a) == 2
end
end
GroupedDataFrame with 1 group based on key: a
First Group (2 rows): a = 1
Row β a
β Int64
ββββββΌβββββββ
1 β 1
2 β 1
```
|
48,792,310 |
My model function:
```
def admin_user
users.where('roles @> ARRAY[?]::varchar[]', ['admin']).first
end
```
My admin configuration:
```
config.model 'Team' do
list do
field :admin_user
end
end
```
It shows up like this:
[](https://i.stack.imgur.com/IJ1NG.png)
How can I make it link to the User admin view?
|
2018/02/14
|
[
"https://Stackoverflow.com/questions/48792310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5129131/"
] |
The reason it shows `#<User:0x0....>` is because your `admin_user` returns an instance of ActiveRecord. When RailsAdmin outputs it calls its `#to_s` method, which, by default returns that output above. You can either override that method to look something like this:
```
# User class
def to_s
name
end
```
or you could modify your `admin_user` to return a properly formatted string instead of ActiveRecord if you prefer.
In order to 'make it link to the User admin view' a bit more configuration is required in your `config.model`. You need to define a `pretty_value` for it and override default rendering.
```
config.model 'Team' do
pretty_value do
# user's active record
user = bindings[:object]
# path to its RailsAdmin 'show' page
path = bindings[:view].show_path(model_name: 'User', id: bindings[:object].id)
# <a href...> tag to it
bindings[:view].tag(:a, href: path) << user.admin_user
end
end
```
remember that `user.admin_user` in the last line assumes it returns a string that you want in your link or `User` that has a properly defined `#to_s`.
Here is a link to the official documentation <https://github.com/sferik/rails_admin/wiki/Custom-list-fields-as-HTML-tags>
|
32,230,183 |
I am trying to add form fields to a form before submitting it using JQuery. I've already tried the following stackoverflow questions and they have not worked:
[How to add additional fields to form before submit?](https://stackoverflow.com/questions/17809056/how-to-add-additional-fields-to-form-before-submit)
[jQuery - add additional parameters on submit (NOT ajax)](https://stackoverflow.com/questions/2530635/jquery-add-additional-parameters-on-submit-not-ajax)
If I don't add any parameters to the form, the submit works:
```
$('.submit_button').click(function(){
$('#quote_form').submit();
});
```
The code above works. Once I try to add a field, however, the form does not get submitted. It is not reaching the server. Here is the code I am using:
```
$('.submit_button').click(function(){
console.log('1');
$("#quote_form").submit( function(eventObj) {
console.log('2');
$(this).append('<input type="hidden" name="dog" value="rover" /> ');
return true;
});
});
```
The first console.log appears in the console but the second does not. How do I get this code to work?
|
2015/08/26
|
[
"https://Stackoverflow.com/questions/32230183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1959050/"
] |
Use a regex to split on the commas outside of the quotes like so:
```
var names = Regex.Split(Properties.Resources.first_names, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
```
Then loop over each entry and remove the quotes like so:
```
for (int i = 0; i < names.Length; i++)
{
names[i] = names[i]Replace("\"", "");
}
```
|
7,319,952 |
I have a ListBox with an ItemsPanel
```
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel x:Name="ThumbListStack" Orientation="Horizontal" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
```
I am wanting to move the Stack Panel along the X-axis using a TranslateTransform in code behind.
Problem is, I can't find the Stack Panel.
```
ThumbListBox.FindName("ThumbListStack")
```
Returns nothing.
I want to use it in:
```
Storyboard.SetTarget(x, ThumbListBox.FindName("ThumbListStack"))
```
How do I get the Stack Panel so I can then use it with the TranslateTransform
Thanks
|
2011/09/06
|
[
"https://Stackoverflow.com/questions/7319952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/859945/"
] |
You can use the `Loaded` event for the `StackPanel` that is in the `ItemsPanelTemplate`
```
<Grid>
<Grid.Resources>
<Style TargetType="ListBox">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel x:Name="ThumbListStack" Orientation="Horizontal"
Loaded="StackPanel_Loaded" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<ListBox />
</Grid>
```
*And then in code behind*
```
private StackPanel m_itemsPanelStackPanel;
private void StackPanel_Loaded(object sender, RoutedEventArgs e)
{
m_itemsPanelStackPanel = sender as StackPanel;
}
```
Another way is to traverse the Visual Tree and find the `StackPanel` which will be the first child of the `ItemsPresenter`.
```
public void SomeMethod()
{
ItemsPresenter itemsPresenter = GetVisualChild<ItemsPresenter>(listBox);
StackPanel itemsPanelStackPanel = GetVisualChild<StackPanel>(itemsPresenter);
}
private static T GetVisualChild<T>(DependencyObject parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
```
|
375,232 |
How to show that:
>
> If $R\supset S$ are integral domains, $R$ is integral over $S$, $K$ and $L$ the fraction fields of $R$ and $S$ respectively, then $K/L$ is a finite extension of fields.
>
>
>
|
2013/04/28
|
[
"https://math.stackexchange.com/questions/375232",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/74837/"
] |
You can't hope to get a finite field extension as long as there are algebraic field
extensions which are not finite, e.g. $\mathbb Q\subset\mathbb Q(\sqrt 2,\sqrt[4] 2,\sqrt[8] 2,\dots)$. Instead one can prove that $L\subset K$ is *algebraic*.
Let $x\in K$, where $K$ is the field of fractions of $R$. We want to prove that $x$ is algebraic over $L$ (the field of fractions of $S$). But $x=a/b$ with $a,b\in R$. Since $a,b$ are integral over $S$ they are algebraic over $L$, so their quotient is algebraic over $L$.
|
17,451,896 |
I have been doing my research, but I feel as if I am missing something.
I have an app with a login. Each time you open the app, you should be forced through that login page. You should never be able to resume onto any activity other than the login.
In the manifest I have
```
android:clearTaskOnLaunch="true"
```
on the main activity I wish to use as the login activity,
and
```
android:finishOnTaskLaunch="true"
```
as well as
```
android:excludeFromRecents="true"
```
on the rest of the activities.
The problamatic situation occurs when you go from the login to another activity, hit home, and relaunch the app via the icon. It should jump back to the login page, but it doesnt. Any idea?
I have also been installing as a regular apk, not via eclipse as I know that there is an issue with eclipse and some of the manifest attributes.
Perhaps if there is a way to detect that the activity launch came from the app icon press, I could manage it that way, but I dont think that is possible either.
|
2013/07/03
|
[
"https://Stackoverflow.com/questions/17451896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1117029/"
] |
In either `onResume` or `onRestart` you could check a series of flags, such as a login timeout, then force the user back to the login activity using an `Intent`, while at the same time finishing the original activity.
I like this method in favor or just finishing the app in either `onPause` or `onStop` because it gives you a chance to make some checks before blindly closing the application.
Or, you could try using the `android:noHistory` tag in your manifest file.
>
> A value of "true" means that the activity will not leave a historical trace. It will not remain in the activity stack for the task, so the user will not be able to return to it.
>
>
>
There are also other tags such as, `android:finishOnTaskLaunch`
>
> Whether or not an existing instance of the activity should be shut down (finished) whenever the user again launches its task (chooses the task on the home screen) β "true" if it should be shut down, and "false" if not. The default value is "false".
>
>
>
More information here: <http://developer.android.com/guide/topics/manifest/activity-element.html>
|
14,383,668 |
I'm using wordpress 3.5 and create menu with submenus. It's structured like this:
```
<ul class="menu">
<li id="menu1">Menu 1</li>
<li id="menu2">Menu 2</li>
<li id="menu3" style="z-index:100;">
Menu 3
<ul class="submenu">
<li id="submenu1">submenu1</li>
<li id="submenu2">submenu2</li>
<li id="submenu3">submenu3</li>
</ul>
</li>
</ul>
```
The problem is the menu with submenus, it's automatically attached a z-index with value 100. I don't want it to be like that because it gives me trouble on adding lavalamp effect to those menus.
I tried to edit the z-index by using jquery just after the menu is created using wp\_nav\_menus simply like this:
```
jQuery(document).ready(function(){
jQuery("#menu3").css("z-index", "0");
});
```
But unfortunately, it doesn't work. How can I remove that inline css style?
|
2013/01/17
|
[
"https://Stackoverflow.com/questions/14383668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1799794/"
] |
Use the [`removeAttribute`](https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute) method, if you want to delete all the inline style you added manually with javascript.
```
element.removeAttribute("style")
```
|
210,237 |
Let's say that you have a commercially/privately-operated jet aircraft. It's not something that's going to be used by a single pilot, or someone making mail runs, or a bush pilot; it's more of the type of thing that would be run by a commercial airline, or a UPS-style delivery company. You will see why.
Now, unlike most jet aircraft, this one runs on a [nuclear jet engine](https://en.wikipedia.org/wiki/Nuclear-powered_aircraft); specifically, a fission model, and one of the [indirect air cycle](https://en.wikipedia.org/wiki/Aircraft_Nuclear_Propulsion#Indirect_Air_Cycle) variety, in which the reactor is not exposed to the inside of the engine but instead heats it via a series of fluid loops (likely liquid metal or sodium).
Advantages to this include:
* time aloft is no longer limited by fuel supply; instead, it is limited by crew endurance
* an absence of greenhouse gas emissions
* the reactor can be used to provide electricity for the rest of the aircraft
* a vehicle with this type of propulsion can operate in zero-oxygen atmospheres, as it does not rely on a hydrocarbon-oxygen combustion reaction
However, this model of aircraft is commercially owned and operated. That means that, instead of it being some kind of experimental vehicle piloted only by test pilots, there are going to be thousands of the things, and they're not going to be exclusively flying over test ranges anymore.
Also, these things are pretty big - imagine, say, a [737](https://en.wikipedia.org/wiki/Boeing_737), with the absolute bare-minimum size being something like a [DC-3](https://en.wikipedia.org/wiki/Douglas_DC-3).
**Given that this aircraft runs on a fission engine, which is radioactive if breached, as well as that it runs on fuel that is probably quite valuable to any hijacker, what safety features or operational standards would it require in order to become commercially-viable?**
|
2021/08/17
|
[
"https://worldbuilding.stackexchange.com/questions/210237",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/87100/"
] |
The nuclear engine would have to be in a black box.
---------------------------------------------------
Normally used to store flight recorders, the (not actually black) black box is very durable and extensively tested against hostile conditions.
>
> Now to the testing, which is insanely intensive:
>
>
>
>
> 1. The black box gets shot out of an air cannon at 3,400 times the force of gravity (or 3,400 Gs, if youβre cool/still like to quote Top Gun). It hits an aluminum target at about the force of a jumbo jet hitting the earth.
>
>
>
>
> 2. For five brutal minutes, itβs crushed with 5,000psi (pounds per square inch) of pressure to ensure it can withstand a sustained impact.
>
>
>
>
> 3. To test it against fire, the box sits inside a 2,000 degree fireball for an hour. Without sunscreen.
>
>
>
>
> 4. Then, testers do a full-on Jacques Cousteau and drop it into a pressurized saltwater tank, simulating the water pressure at 20,000ft below the surface. For 24 hours. In a slightly less-pressurized environment, it must then survive 30 days completely submerged in saltwater.
>
>
>
>
> 5. And if all that wasn't enough, a 500lb weight with a quarter-inch pin sticking out is dropped on the box from 10ft up to make sure it wonβt puncture.
>
>
>
>
> If all that goes well, then the unit is run through a series of diagnostic tests to see if it still works.
>
>
>
The nuclear power engine would need similar testing, to ensure that the plane could fall out of the sky and crash and the nuclear material not leak.
It should also be made very hard for someone to steal the waste. A safecracker could do it in time, but not quickly.
The weight requirements would be significant, but the extra power should let you run more powerful engines, so it balances out.
The waste design and flight path would need to be such that it was less vulnerable to terrorism.
------------------------------------------------------------------------------------------------
Some risk is understandable. Hospitals and industry people already use a lot of radioactive material and have crappy security, and we haven't had a dirty bomb made yet.
That said, the flight pattern and waste disposal should be done to minimize the risk. They shouldn't fly over countries that might abduct them, and shouldn't land in countries that might have people attack them. They should make sure the waste is stored in ceramics or vitrified glass form, making it hard to weaponize it into a dirty bomb.
|
25,599,540 |
i am very new in Laravel,currently working with Laravel4.I am trying to add a multiple column search functionality in my project.I can do single column eloquent search query,But honestly i have no idea how to do multiple column eloquent search query in laravel.I have **two drop down menu**
1.Locatiom
2.blood group.
i want to search an **user** having certain **blood group** against certain **location**.That is, user will select a **location** and **blood group** from those two drop down menu at a time and hit the search button.
In my database,i have two column, one contains the **location** and another contains the **blood group** of a certain user. Now,what should be the eloquent query for such a search?
|
2014/09/01
|
[
"https://Stackoverflow.com/questions/25599540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2971215/"
] |
Simply chain `where` for each field you need to search through:
```
// AND
$results = SomeModel::where('location', $location)->where('blood_group', $bloodGroup)->get();
// OR
$results = SomeModel::where('location', $location)->orWhere('blood_group', $bloodGroup)->get();
```
You can make it easier to work with thanks to the scopes:
```
// SomeModel class
public function scopeSearchLocation($query, $location)
{
if ($location) $query->where('location', $location);
}
public function scopeSearchBloodGroup($query, $bloodGroup)
{
if ($bloodGroup) $query->where('blood_group', $bloodGroup);
}
// then
SomeModel::searchBloodGroup($bloodGroup)->searchLocation($location)->get();
```
Just a sensible example, adjust it to your needs.
|
14,482,370 |
I am developing 2 Windows services, one of them will send pictures and word files to other and other service will give a string answer. That services are in same computer.
I will develop same program's Linux version also.
Which way is the best for communication between services in Linux and Windows.
By the way I am developing that services with C++.
|
2013/01/23
|
[
"https://Stackoverflow.com/questions/14482370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1790679/"
] |
you should give this a try:
```
jQuery(document).ready(function(){
var $items = jQuery(".introPara").css("visibility", "hidden");
var $outer = jQuery('.introTextCont')
$outer.animate({height: 100}, {
duration: 2000,
step: function(){
if($items.length){
var $test = $items.first();
if($outer.height() > $test.offset().top + $test.outerHeight()){
$test.css("visibility", "");
$items = $items.slice(1);
}
}
}
});
});
```
[demo](http://jsfiddle.net/WzC3g/3/)
**EDIT** minor code update for the undefined $test, would update jsFiddle but the site seems unresponsive to me :(
|
4,784,410 |
I'm looking to make a statement in PHP like this:
`if(preg_match("/apples/", $ref1, $matches)) OR if(preg_match("/oranges/", $ref1, $matches)) {
Then do something }`
Each of those above by themselves work just fine, but I can't figure out how to make it so that if either of them is true, then to perform the function I have beneath it.
|
2011/01/24
|
[
"https://Stackoverflow.com/questions/4784410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/484812/"
] |
Use the `|` to select one value or the other. You can use it multiple times.
```
preg_match("/(apples|oranges|bananas)/", $ref1, $matches)
```
**EDIT:** This post made me hungry.
|
732,662 |
After studying the problem, I found that the sum of the root is $-p$ and the product of them is $-330p$. Does this help?
|
2014/03/30
|
[
"https://math.stackexchange.com/questions/732662",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/132522/"
] |
The sum of the roots is $-p$. Suppose the positive root is $a$, then the negative root is $-p-a$
The product of the roots is $-a(p+a)=-330p$
Now either $p|a$ or $p|(p+a)$ (because $p$ is prime) which also implies $p|a$ so let $a=pb$ then $$pb(pb+p)=330p$$ so that $$pb(b+1)=330$$
And you can go from there ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.