qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
sequence | response
stringlengths 0
115k
|
---|---|---|---|---|
17,006,512 | I have a simple table layout, in the one of the row, I have time for sun rise in a text view and I am trying to have sun with purple colour for the row as background. How can I achieve this? I tried creating an image 1000px x 500px with sun and purple background, However, it does not look good on different screen sizes. What is the solution for this?
Here is an image of what I am trying to achieve ![](https://i.imgur.com/rcjhYSE.png) | 2013/06/09 | [
"https://Stackoverflow.com/questions/17006512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2122179/"
] | You can set it programmatically by
```
[textField setSecureTextEntry:YES];
```
or in IB (secured checkbox at the bottom)
![enter image description here](https://i.stack.imgur.com/G8u20.png) |
59,938,330 | I'm using a jsonb field in my Rails application and have installed the [gem attr\_json](https://github.com/jrochkind/attr_json). Is there a way to receive the defined json\_attributes programmatically? With a "normal" rails attribute, I would just do @instance.attribute\_names. But with attr\_json is there any way how to have the json\_attributes returned?
```
class Vehicle < Item
include AttrJson::Record
attr_json :licence_plate, :string, container_attribute: "custom_attributes_indexed"
attr_json :brand, :string, container_attribute: "custom_attributes_indexed"
attr_json :serial_number, :string, container_attribute: "custom_attributes_indexed"
attr_json :inventory_number, :string, container_attribute: "custom_attributes_indexed"
end
```
For this code I would like to do something like @vehicle.json\_attribute\_names and have the following returned
```
["licence_plate", "brand", "serial_number", "inventory_number"]
``` | 2020/01/27 | [
"https://Stackoverflow.com/questions/59938330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3748376/"
] | I think you should clear your previous model inside loop so you could use this function which is keras.backend.clear\_session().From <https://keras.io/backend/>:
This will be solved your problem. |
5,578,250 | As I am writing my first grails webflow I am asking myself if there is anyy tool or script what can visualize the flow?
Result can be a state diagram or some data to render in a graph tool like graphviz. | 2011/04/07 | [
"https://Stackoverflow.com/questions/5578250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172590/"
] | There's no tool around currently that will do this for you I'm afraid. I've implemented something myself before, but this was very simple and was not automated in any way. It was a simple template where the model was a step number:
```
<g:render template="flowVisualiser" model="[step: 2]" />
```
You would have to put this in every view of the webflow, changing the number for whatever step it was. The template itself just had a row of images for each of the steps, and there was some gsp logic in the style of each image so that if the model passed in was step 2 (for instance) or above then this particular image would have opacity 1:
```
<li>
<div class="${step >= 2 ? 'step-completed' : 'step-todo'}">
<img src="${resource(dir:'images',file:'2.png')}" />
<h4>Do this step</h4>
</div>
</li>
...
```
I know it's not fancy and it's a bit of manual labor but it worked just fine for me :) |
26,377,384 | I want adding background image with css but it did not work.Browser show me a blank page.
my application.css
```
home-body {
background-image: url('/home.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
```
file home.jpg located in a directory /public/home.jpg.
How fix? | 2014/10/15 | [
"https://Stackoverflow.com/questions/26377384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059461/"
] | Please use this code. Use background instead of background-image and make sure that you have inserted the correct image path in url().
```
html, body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.home-body {
background: url('/home.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
``` |
1,817,508 | I have a vector class that has addition, multiplication, subtraction, division, etc operators. I'm trying to optimize my program (which does a lot of vector operations) and I'm realizing that about 50% of the time spent is in constructing and destructing vectors. I understand that this is because every time I call a non-compound mathematical operator for a vector, a new vector is constructed. Is there a way to prevent this without using compound operators or expanding vector operations?
If I have:
```
Vector a = Vector(x, y, z);
Vector b = Vector(a, b, c);
Vector c = a + b;
```
I can't use += because c is a completely new vector. I know I can speed it up with this:
```
c.x = a.x + b.x;
c.y = a.y + b.y;
c.z = a.z + b.z;
```
but that doesn't seem as clean as just using an operator. | 2009/11/30 | [
"https://Stackoverflow.com/questions/1817508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/217546/"
] | >
> I understand that this is because
> every time I call a non-compound
> mathematical operator for a vector, a
> new vector is constructed. Is there a
> way to prevent this without using
> compound operators or expanding vector
> operations?
>
>
>
Well, the nature of adding two things together to produce a third thing *requires* you to construct a third thing...so how is what you're asking even logically possible?
That being said, if you're concerned about the temporaries created by using the addition operator, these may be optimized out by the compiler if your compiler supports return value optimization. Alternatively, if your compiler doesn't support this and you really want to cut back on temporaries but keep the `+` operator, you may want to look into emulating C++0x move semantics, and provide your vector with a rvalue move constructor, which will be invoked when it returns a temporary by value. See the Section titled "Moving Objects" in [this article](http://www.ddj.com/cpp/184403806) for information on implementing move semantics in C++03. Once C++0x comes out, you can just replace these hacks with real move constructors using the `&&` operator for rvalue references. |
234,979 | I maintain a set of command line bioinformatics tools which we distribute as source and binaries for Linux, Windows, and OS X. Currently the binary distribution for OS X is just a zip file containing directories for the binaries and the documentation. Our install guide directs the user to unzip the archive, copy the binaries to the desired location, and update their PATH to point to the binaries. That's fine for the command line savvy users, but some users have never heard of /usr/local/bin let alone PATH. We'd love to have an installer that's in more of the OS X idiom.
Creating an application bundle doesn't seem to do the trick because our tools are strictly command line and they'll need a terminal session to use them. It seems like we could have used PackageMaker to create an installer, but that's now deprecated.
Is there a current standard installer for command line tools on OS X, preferably one with CPACK support? | 2016/04/14 | [
"https://apple.stackexchange.com/questions/234979",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/7226/"
] | The standard package format is the "pkg" format. It's not often used for applications, but it's fine for a terminal-only utility.
* My go-to tool for creating packages is called [Packages](http://s.sudre.free.fr/Software/Packages/about.html).
* I haven't used it myself, but it looks like CMake [supports PackageMaker](https://cmake.org/Wiki/CMake:CPackPackageGenerators#PackageMaker_.28OSX_only.29), which is a third party tool for creating OS X packages.
* There's also the built-in [pkgbuild](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/pkgbuild.1.html#//apple_ref/doc/man/1/pkgbuild) utility.
Just make sure you don't touch anything outside the [standard paths](https://support.apple.com/en-au/HT204899) (`/Library`, `/Applications`, or `/usr/local/`) and you'll be fine. |
13,358,503 | a gem intends to support gems `a` or `b` as alternatives for a functionality.
In code I check with `defined?(A)` if I fall back to `b` that's fine.
But as a gem developer how to specify these dependencies?
1) what do I put in the Gemfile.
```
group :development, :test do
gem 'a', :require => false
gem 'b', :require => false
end
```
This allows `Bundle.require(:test)` not to auto-require a,b?
2) How can explicitly require `a` and `b` separately to mimic (or mock) the scenario when we fall back to `b` in my tests?
3) Also how do I specify that either `a` or `b` is prerequisite for the gem.
thanks | 2012/11/13 | [
"https://Stackoverflow.com/questions/13358503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641672/"
] | Don't include the `a` gem in your dependencies, but `require` it anyway. If that fails, it will raise `LoadError`, from which you can rescue.
```
begin
require 'a'
rescue LoadError
# The 'a' gem is not installed
require 'b'
end
```
---
I believe this is the best way to use and test this setup:
1. Define an interface for your backend and allow a custom implementation to be easily plugged in.
```
module YourGem
class << self
attr_accessor :backend
def do_something_awesome
backend.do_something_awesome
end
end
end
```
2. Implement the `a` and `b` backends.
```
# your_gem/backends/a.rb
require 'a'
module YourGem::Backends::A
def self.do_something_awesome
# Do it
end
end
# your_gem/backends/b.rb
require 'b'
module YourGem::Backends::B
def self.do_something_awesome
# Do it
end
end
```
3. Set the one you want to use.
```
begin
require 'your_gem/backends/a'
Gem.backend = YourGem::Backends::A
rescue LoadError
require 'your_gem/backends/b'
Gem.backend = YourGem::Backends::B
end
```
This will use `YourGem::Backend::A` even if `b` is installed.
4. Before testing, make sure both `a` and `b` gems are installed, `require` both backends in the test code, run the tests with one backend, then run the tests again with the other backend. |
18,939,332 | Does anyone know what Facebook uses for their blurred toolbar?
![enter image description here](https://i.stack.imgur.com/RTmVf.png)
Now, I **KNOW** there are already countless threads about iOS 7 blur. They all come to these same solutions:
1. Use a UIToolbar with translucent set to YES, and then set its barTintColor property. The problem with this approach is that it significantly increases the lightness of the color. This is the approach that [AMBlurView](https://github.com/JagCesar/iOS-blur) uses. The nav bar in the Facebook app remains dark blue even when it's above white content. (with AMBlurView it becomes pastel blue)
2. Render the underlying view's in a graphic context, then blur that context, output it as a UIImage and use that as background view, repeat 30 times per second. (which hurts performance pretty bad). This is the approach that [FXBlurView](https://github.com/nicklockwood/FXBlurView) uses. It doesn't seem like Facebook is using that either.
I've read at length in the Apple Dev Forums and it seems like this is a technical challenge even for Apple engineers. With Facebook nailing the real-time blur with something else than the two approaches I described. Any idea? | 2013/09/22 | [
"https://Stackoverflow.com/questions/18939332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87158/"
] | Apparently the trick here is to insert the translucent layer as a sublayer of the navigation bar. I take no credit for finding this, and the following snippet has been taken [**from this gist**](https://gist.github.com/alanzeino/6619253).
```
UIColor *barColour = [UIColor colorWithRed:0.13f green:0.14f blue:0.15f alpha:1.00f];
UIView *colourView = [[UIView alloc] initWithFrame:CGRectMake(0.f, -20.f, 320.f, 64.f)];
colourView.opaque = NO;
colourView.alpha = .7f;
colourView.backgroundColor = barColour;
self.navigationBar.barTintColor = barColour;
[self.navigationBar.layer insertSublayer:colourView.layer atIndex:1];
``` |
54,558,029 | Here is my original df:
```
my_df_1 <- data.frame(col_1 = c(rep('a',5), rep('b',5), rep('c', 5)),
col_2 = c(rep('x',3), rep('y', 9), rep('x', 3)))
```
I would like to group by `col_1` and return 1 if `col_2` for given group contains `x`, and 0 if not.
Here is how final result is supposed to look:
```
my_df_2 <- data.frame(col_1 = c(rep('a',5), rep('b',5), rep('c', 5)),
col_2 = c(rep('x',3), rep('y', 9), rep('x', 3)),
col_3 = c(rep(1,5), rep(0,5), rep(1, 5)))
```
I would prefer to get it done with `dplyr`, if possible. This is kind of `count if` predicate, but cannot find it. | 2019/02/06 | [
"https://Stackoverflow.com/questions/54558029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1700890/"
] | What about this?
```
do <- as.data.frame(do.call(rbind, lapply(my.stuff, as.vector)))
do <- cbind(my.var=rownames(do), do)
do[do == "NULL"] <- NA
```
***Result***
```
> do
my.var my.col1 my.col2 my.col3 my.col4
AA AA 1 4 NA NA
BB BB NA NA NA NA
CC CC 13 8 2 10
DD DD NA NA -5 7
```
### *Edit:*
If we don't want lists as column objects as @akrun reasonably suggests, we could do it this way:
```
u <- as.character(unlist(my.stuff, recursive=FALSE))
u[u == "NULL"] <- NA
do <- matrix(as.integer(u), nrow=4, byrow=TRUE,
dimnames=list(NULL, names(my.stuff[[1]])))
do <- data.frame(my.var=names(my.stuff), do, stringsAsFactors=FALSE)
```
***Test:***
```none
> all.equal(str(do), str(desired.object))
'data.frame': 4 obs. of 5 variables:
$ my.var : chr "AA" "BB" "CC" "DD"
$ my.col1: int 1 NA 13 NA
$ my.col2: int 4 NA 8 NA
$ my.col3: int NA NA 2 -5
$ my.col4: int NA NA 10 7
'data.frame': 4 obs. of 5 variables:
$ my.var : chr "AA" "BB" "CC" "DD"
$ my.col1: int 1 NA 13 NA
$ my.col2: int 4 NA 8 NA
$ my.col3: int NA NA 2 -5
$ my.col4: int NA NA 10 7
[1] TRUE
``` |
161,836 | I'm using Oracle 11g database in which I have more than 12 schema's consisting of many tables. I've created sequences for primary keys to these tables. I've also created synonyms to refer my application from the main schema.
My issue is,
while i try to export(using expdp) the schema's from DB in 1 server and import(impdp) the dump file to db installed in another server, sequence values only for some tables are getting changed. Even if i try to remap the table space or schemas, the value of sequence shows a lesser value than rows in their respective tables. Due to which when i access the application it throws an error while saving the data.
I am confused and don't getting an idea to solve this. Please advise.
Is their any method to solve this issue?
Thanks in advance. | 2017/01/21 | [
"https://dba.stackexchange.com/questions/161836",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/104331/"
] | If you run export command against live database without parameters like `flashback_scn` or `flashback_time` which ensures consistency during the export, then this can be an expected behavior because these objects are exported in different time and one can become inconsistent with another.
For example, if the sequence object is exported before the table and the application has inserted new records using the sequence and exported later then table and sequence can be out of sync.
Stopping application before starting the export process or using `expdp`parameters like `flashback_time`(this may not export all the transactions made after the time specified in this parameter unless you stop the application) can prevent this situation. Or you can adjust the sequence value after the import by recreating it. |
43,053,550 | I want to change the default login validation error message like:
```
Username & Password doesn't match
```
instead of
```
these credentials do not match our records
```
How to do this ? | 2017/03/27 | [
"https://Stackoverflow.com/questions/43053550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7394739/"
] | You can change this message to another one in this file:
```
resources/lang/en/auth.php
```
This is the line:
```
'failed' => 'These credentials do not match our records.',
``` |
4,378,067 | I need to find the GUID for an existing USB device attached to my Windows XP system. How can this be done using WMI or the registry? Or, is there another avenue that I should explore? Thanks.
**Additional Information:**
I need to find the GUID for a specific known device; it is not expected to change. If I need to write a little program, use some tool, or look somewhere in the Windows system to find this information, it's all the same to me. | 2010/12/07 | [
"https://Stackoverflow.com/questions/4378067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214296/"
] | For a specific known device, the easiest way I've found is to open the .inf file for that device's driver (if you have the driver); it should be clearly indicated there.
You can probably also poke around under HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Enum\USB. |
12,104,391 | I am trying to instantiate the [StdRandom](http://algs4.cs.princeton.edu/stdlib/StdRandom.java.html) class (see below) in my own Java program so that I can generate random integers by calling it's *uniform* method. However, I kept getting this error during compilation:
>
> MyProgram.java:43: StdRandom() has private access in StdRandom
>
> StdRandom random = new StdRandom();
>
> 1 error
>
>
>
I noticed this line in the code which is preventing me from instantiating the StdRandom class:
```
// singleton pattern - can't instantiate
private StdRandom() { }
```
My questions are: how am I supposed to instantiate this class and use the methods in this class in my own programs? Why was the above singleton pattern included in this code? Should I just comment the pattern out and use it? Or is there another way to access this class's methods in my Java programs?
```
/*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
* Precondition: array entries are nonnegative and their sum equals 1.
*/
public static int discrete(double[] a) {
double EPSILON = 1E-14;
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]);
sum = sum + a[i];
}
if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON)
throw new IllegalArgumentException("sum of array entries not equal to one: " + sum);
double r = uniform();
sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Uniformly sample (without replacement) M of the N items from the array a[].
* To make it work with an Object[] argument and return an array of the
* underlying argument type requires some Java minutiae, e.g., using static
* generics and Arrays.copyOf().
*/
public static String[] sample(String[] a, int M) {
int N = a.length;
if (M < 0 || M > N)
throw new RuntimeException("Illegal number of samples");
String[] b = new String[M];
for (int i = 0; i < N; i++) {
int r = uniform(i+1); // between 0 and i
if (r < M) {
if (i < M) b[i] = b[r];
b[r] = a[i];
}
}
return b;
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
String[] a = "A B C D E F G".split(" ");
for (String s : a)
StdOut.print(s + " ");
StdOut.println();
String[] b = StdRandom.sample(a, 3);
for (String s : b)
StdOut.print(s + " ");
StdOut.println();
}
}
``` | 2012/08/24 | [
"https://Stackoverflow.com/questions/12104391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225998/"
] | All methods are static, you don't need to create an instance of that class to use it. To use e.g. the `random()` method, use `StdRandom.random()` |
13,121,850 | I have used will\_paginate in my rails application but i come across a situation where i need to use to will\_paginate inside a block where the page should not reload when i click the pagination number, could anyone help me saying how to integrate will\_paginate with ajax to avoid page reloading......? | 2012/10/29 | [
"https://Stackoverflow.com/questions/13121850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917833/"
] | I have a pagination javascript file
So in my index.html.erb file I addded
```
<%=javascript_include_tag "pagination.js"%>
```
In pagination.js file
```
$(function(){
$(".pagination a").live("click", function() {
$.get(this.href, null, null, "script");
return false;
});
});
```
I fetched the model data like this in the index action.
```
@employees = Employee.where("!is_deleted=?",1).paginate(:page=>params[:page] ,:per_page => 20)
```
and added this in the index.js.erb file
```
$("#employee_table").html("<%= escape_javascript(render("employees")) %>");
```
Here employee\_table is the id of the div where im displaying the data.
I have a file name will\_paginate\_array\_fix.rb in the config/initializers.
This file will look like this
```
require 'will_paginate/array'
```
Thats why even though i use where it works because it supports for arrays also. |
8,322,550 | I've installed XAMPP on my Windows XP. I started the XAMPP control panel and it shows apache and mysql are running.
When I check the status by going to `localhost/xampp` it shows:
```
mysql : deactivated
```
When I run php files that access the mysql database, it shows the following errors:
```
Warning: mysql_connect() [function.mysql-connect]: [2002] No connection could
be made because the target machine actively refused it. (trying to connect
via tcp://localhost:3306) in C:\xampp\htdocs\Elo_algorithm.php on
line 18
```
I've been through the XAMPP troubleshooting page and FAQ but I don't understand what to do. The XAMPP control panel shows mysql is running, but xampp status shows: `deactivated`.
What is going on here? | 2011/11/30 | [
"https://Stackoverflow.com/questions/8322550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029133/"
] | OK I got this issue resolved in my case, hopefully will help you too. Problem was system itself. If you run Vista, Win7, win8 you probably have permission issue. Simple go to XAMPP root and find mysql\_start.bat and run it. Immediately after clicking your firewall will appear with message asking for permission. All you have to do is to allow permission (for private networks such a home or work network).
MySQL database ACTIVATED - and that's what matters ;)
I hope that helps to all of you who did not get an answer so far.
Cheers! |
22,690,091 | I need to create simple icon in css like this - about 32x32 px.
![Icon](https://i.stack.imgur.com/8I2qy.png)
I'd like to make it as simple as it could be (html - no unnecessary divs). The text should be vertically and horizontally aligned to the center of each half.
The text displayed will be short (about 9 chars max, font-size about 10px). It should have static height and width. ALSO The text has to be written in tags (like or ) so it'd be accessible by CMS.
Here is my solution, which I find wrong, because the height and width is not static:
jsfiddle.net/s2DRr/1/ | 2014/03/27 | [
"https://Stackoverflow.com/questions/22690091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3151531/"
] | What's Going On
---------------
I use the `i` element to create icons. Normally with an image, or more recently an icon font, but we can adapt for your needs. (Originally the `i` element wasn't used for icon, and it is debatable whether it's semantically correct. However, it's used in many icon fonts, and in some major websites.) Since you need to be able to dynamically place the content in the HTML, we can use the `i` as a wrap, and a `div` inside to make the second color.
Code
----
[**Working Fiddle**](http://jsfiddle.net/hyJLz/)
### HTML:
```
<i>Top<div>Bottom</div></i>
```
### CSS:
```
i {
height:32px;
width:32px;
display:inline-block;
position:relative;
color:white;
font-size:10px;
background:lightgreen;
text-align:center;
font-style:normal;
}
i div {
background:orange;
position:absolute;
bottom:0;
height:50%;
width:100%;
}
```
Screenshot
----------
![enter image description here](https://i.stack.imgur.com/CNLCF.png) |
3,439,265 | I have installed oracle 10g express edition and I did not find the option to
create schema..
Is there a option to create schema in oracle 10g express edition
or else I have to install other oracle 10g..?
To create schema which oracle 10g
I have to install... what? | 2010/08/09 | [
"https://Stackoverflow.com/questions/3439265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396486/"
] | You don't need to explicitly create schema, Oracle automatically creates a schema when you create a user (see **[`CREATE USER`](http://download.oracle.com/docs/cd/B13789_01/server.101/b10759/statements_8003.htm#i2065278)** documentation).
If you really want, you can use [**`CREATE SCHEMA`**](http://download.oracle.com/docs/cd/B13789_01/server.101/b10759/statements_6013.htm) statement and issue it through Oracle Express web interface or from SQL prompt. |
46,328,375 | I have been following Gorail's tutorial to deploy on DigitalOcean. [See Here](https://gorails.com/deploy/ubuntu/16.04#capistrano) and [Here also](https://www.youtube.com/watch?time_continue=467&v=WBPV4vjzcjQ).
I've reached the part where I am using the cap production deploy in the command line, but I am getting the following error below, I am not understanding how this error is occuring:
```
luis@luis-Inspiron-7559:~/Desktop/mls2$ cap production deploy --trace
cap aborted!
LoadError: cannot load such file -- capistrano/rbenv
/usr/local/lib/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
/usr/local/lib/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
/home/luis/Desktop/mls2/Capfile:31:in `<top (required)>'
/usr/lib/ruby/vendor_ruby/rake/rake_module.rb:28:in `load'
/usr/lib/ruby/vendor_ruby/rake/rake_module.rb:28:in `load_rakefile'
/usr/lib/ruby/vendor_ruby/rake/application.rb:689:in `raw_load_rakefile'
/usr/lib/ruby/vendor_ruby/rake/application.rb:94:in `block in load_rakefile'
/usr/lib/ruby/vendor_ruby/rake/application.rb:176:in `standard_exception_handling'
/usr/lib/ruby/vendor_ruby/rake/application.rb:93:in `load_rakefile'
/usr/lib/ruby/vendor_ruby/rake/application.rb:77:in `block in run'
/usr/lib/ruby/vendor_ruby/rake/application.rb:176:in `standard_exception_handling'
/usr/lib/ruby/vendor_ruby/rake/application.rb:75:in `run'
/usr/lib/ruby/vendor_ruby/capistrano/application.rb:15:in `run'
/usr/bin/cap:3:in `<main>'
```
This is my cap file:
```
# Load DSL and set up stages
require "capistrano/setup"
# Include default deployment tasks
require "capistrano/deploy"
# Load the SCM plugin appropriate to your project:
#
# require "capistrano/scm/hg"
# install_plugin Capistrano::SCM::Hg
# or
# require "capistrano/scm/svn"
# install_plugin Capistrano::SCM::Svn
# or
# require "capistrano/scm/git"
# install_plugin Capistrano::SCM::Git
# Include tasks from other gems included in your Gemfile
#
# For documentation on these, see for example:
#
# https://github.com/capistrano/rvm
# https://github.com/capistrano/rbenv
# https://github.com/capistrano/chruby
# https://github.com/capistrano/bundler
# https://github.com/capistrano/rails
# https://github.com/capistrano/passenger
#
# require "capistrano/rvm"
require "capistrano/rbenv"
set :rbenv_type, :user
set :rbenv_ruby, '2.4.1'
require "capistrano/bundler"
require 'capistrano/rails'
# require "capistrano/chruby"
# require "capistrano/rails/assets"
# require "capistrano/rails/migrations"
# require "capistrano/passenger"
# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }
```
and my production.rb :
```
set :production
server 'xxx.xxx.xxx.xxx', user: 'USER', roles: %w{app db web}
```
and my gemfile, i've already added the capistrano gems in the development group as suggested in the video:
```
...
group :development do
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '~> 3.0.5'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
gem 'capistrano', '~> 3.9', '>= 3.9.1'
gem 'capistrano-rails', '~> 1.3'
gem 'capistrano-passenger', '~> 0.2.0'
gem 'capistrano-rbenv', '~> 2.1', '>= 2.1.1'
end
...
``` | 2017/09/20 | [
"https://Stackoverflow.com/questions/46328375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7438959/"
] | You need to install [that dependency](https://github.com/capistrano/rbenv) by adding it to your `Gemfile`:
```
gem 'capistrano-rbenv'
```
Then `bundle install`.
Capistrano has started to shunt some of the lesser used features to optional modules lately. |
4,313,867 | What does `performSelector` do? What is the difference between creating a new `NSThread` and the `performSelector` method?
How it works and where should we use it? | 2010/11/30 | [
"https://Stackoverflow.com/questions/4313867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202735/"
] | All of these perform the same task, that is make the `doStuff` method on `anObject` execute synchronously on the **current** thread:
```
// 1
[anObject doStuff];
// 2
[anObject performSelector:@selector(doStuff)];
// 3
objc_msgSend(anObject, @selector(doStuff));
// 4
IMP imp = [anObject methodForSelector:@selector(doStuff)];
imp(anObject, @selector(doStuff));
```
1. Is how you normally should go about to do stuff.
2. Is for dynamically dispatching a message. Use if the selector is unknown, or provided by a client, for example if you implement an target-action pattern. or if the class of `anObject` is unknown, usually used by first asking if the object has the method with `-[NSObject respondsToSelector:]`.
3. Is what no 1. is actually compiled down to. Usually never any real need to do this.
4. Cached the actual `IMP` *(implementation)* for a method, and then call it directly. Can sometimes be faster than 1. if used in a tight loop. Just remember; *premature optimization is evil*.
What you need to grasp is that in Objective-C methods are more important than classes/interfaces. Usually you do not query an object if it belongs to a particular class, or conforms to any protocol, that is for the compiler to complain about. At run-time you instead query for specific methods.
In short: **It does not matter what you are, just what you can do.**
As a convenience `NSObject` also have several siblings to `performSelector` that are asynchronios. Most notably:
* `performSelector:withObject:afterDelay:` - To execute the method on the current thread after a delay.
* `performSelectorInBackground:withObject:` - To execute the method on a new background thread.
* `performSelectorOnMainThread:withObject:waitUntilDone:` - To execute the method on the main thread.
* `performSelector:onThread:withObject:waitUntilDone:` - To execute the method on any thread.
The asynchronous performers all depend on a `NSRunLoop` to function. This is not something you need to worry about unless you spawn a thread yourself. If you do then you need to also run the new threads run loop. Just skip that for now. |
173,361 | With regards to Thermal Radiation, given a stable body initially at 300 Kelvin placed in isolation, after continuous Thermal Radiation will it's temperature gradually reduce to 0 kelvin asymptotically? If so, does this mean that the body is now devoid of any Thermal Energy? And does it imply that the only energy it can possibly have is (now) due to it's electronic structure? | 2015/03/31 | [
"https://physics.stackexchange.com/questions/173361",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/76641/"
] | In practice, no. In theory, also no.
The Universe is filled with photons with an energy distribution corresponding to $2.73\,\mathrm{K}$, called the [cosmic microwave background (CMB)](http://en.wikipedia.org/wiki/Cosmic_microwave_background). Every $\mathrm{cm}^3$ of space holds [around 400](https://physics.stackexchange.com/q/196366/70207) of them, so each second one $\mathrm{cm}^2$ is hit by roughly one hundred billion of these photons. That means that if you place your "stable body" in an ever-so-isolated box, the box itself will never come below $2.73\,\mathrm{K}$, and neither will the body inside. It will asymptotically go towards thermal equilibrium at $T = 2.73\,\mathrm{K}$.
Even if you magically removed everything else in the Universe but the body$^\dagger$, $0\,\mathrm{K}$ can never be reached. The reason is that this would imply zero motion of the atoms of the body, which is [forbidden by law](http://en.wikipedia.org/wiki/Uncertainty_principle).
In practice, it *is* actually possible to have temperatures lower than the 2.73 K of the CMB. When a gas expands, it cools, and if it expands faster than it can be heated by the CMB, it can temporarily reach lower temperatures. This is the case for the [Boomerang Nebula](http://en.wikipedia.org/wiki/Boomerang_Nebula), which has a temperature of 1 K. The nebula will probably be heated to the temperature of the CMB in around 10,000 years or so.
---
$^\dagger$Or waited billions of years for the CMB to cool. |
6,363,710 | I am new to Objective C. On one of the developers documentation, I found the following statemenet.
**The following statement invokes the lockFocusIfCanDraw method and assigns the return value to
flag. It does not generate a compiler warning unless there is a mismatch between the type for flag
and the method’s return type. Nonetheless, this pattern is strongly discouraged.**
```
flag = aView.lockFocusIfCanDraw;
```
In addition to the one above, I can think of many situations of this kind. For instance I might want to capture the display text from a box and assign it to a local string etc.
I am just wondering, if the above statement is discouraged, what is the recommended way of handling such situation? | 2011/06/15 | [
"https://Stackoverflow.com/questions/6363710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402814/"
] | The dot syntax for calling methods should only be used for properties (i.e. when calling accessors). Since `lockFocusIfCanDraw` is not an accessor method, you should use the regular square brackets syntax, i.e. `flag = [aView lockFocusIfCanDraw];` instead. |
9,855,673 | It's an interesting problem, really, for all you Devise masters you there.
We have Devise setup with OmniAuth, but the issue happens regardless if you are logged in via Facebook, or logged in via a normal username. What happens is we have a Flash game embedded on our website. When you finish playing the game, the game will submit your score to the Rails backend:
```
request = new URLRequest("http://mydomain.com:2012/games/1/leaderboards/13/submitLeaderboardStatistic");
request.method = URLRequestMethod.POST;
var loader : URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
var variables : URLVariables = new URLVariables();
variables.game_value = aScore;
variables.game_id = 1;
variables.unique_identifier = "com.onecoolgameaday.highscores";
variables.time_stamp = new Date();
request.data = variables;
loader.addEventListener(Event.COMPLETE, on_complete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
loader.load(request);
```
The URL is sent out to our URL. The Controller (Leaderboards are nested underneath Games) gets the url information in the submitLeaderboardStatistic method. This method deals with the information. In this method, I call `current_user` to get the current User, the one who submitted the actual score. Problem is, current\_user returns nil.
Apparently, what is happening, is once the game Launches that URL POST request, devise invalidates the session (or something), so I cannot tell who submitted the score.
Why is the current signed in user being "kicked off" once the Flash Game send the URL? How do I fix this so I can say "user XXX submitted this score."
Thank you!
Rails: 3.2.2
Ruby: 1.9.2
Devise: 1.5.3 | 2012/03/24 | [
"https://Stackoverflow.com/questions/9855673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200567/"
] | Does the form you are submitting have a valid CSRF token? I think Devise calls reset\_session if the csrf token is invalid or doesn't exist. |
40,581,405 | I'm working on this procedure which is supposed to return a list of pairs from 2 given lists. So for example (pairs '(1 2 3) '(a b c)) should return **'((1.a) (2.b) (3.c))**.
This is my logic so far. I would take the first element of each list and recursively call the procedure again with cdr as the new arguments. My result is returning a list such as this: **(1 a 2 b 3 c)**
Where is my logic going wrong? I know there is a list missing somewhere, but I'm not an expert at Scheme.
Any suggestions?
```
(define pairs
(lambda (x y)
(if (or (null? x) (null? y))
'()
(cons (car x)
(cons (car y)
(pairs (cdr x)(cdr y)))))))
(pairs '(1 2 3) '(a b c))
``` | 2016/11/14 | [
"https://Stackoverflow.com/questions/40581405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/505278/"
] | Notice that you produce a value that prints as `(1 . 3)` by evaluating `(cons 1 3)`. However in your program you are doing `(cons 1 (cons 3 ...))` which will prepend 1 and 3 to the following list.
In other words: Instead of `(cons (car x) (cons (car y) (pairs ...))`
use `(cons (cons (car x) (car y) (pairs ...))`. |
21,494,338 | I have some images in my Photo Album. I have already retrieved the asset urls of all of them.. I want to get a particular image using the asset url... below code gave me asset url..
```
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *URL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
```
Now using this url, how can I get the image(UIImage)? | 2014/02/01 | [
"https://Stackoverflow.com/questions/21494338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1394304/"
] | Get Url by this,
```
NSURL *url= (NSURL*) [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:[[[asset valueForProperty:ALAssetPropertyURLs] allKeys] objectAtIndex:0]];
```
And get image from url like below.
```
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
@autoreleasepool {
CGImageRef iref = [rep fullScreenImage];
if (iref) {
UIImage *image = [UIImage imageWithCGImage:iref];
self.loadedImage = image;
dispatch_async(dispatch_get_main_queue(), ^{
//UIMethod trigger...
});
iref = nil;
}
}
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(@"Can't get image - %@",[myerror localizedDescription]);
};
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:yourUrl
resultBlock:resultblock
failureBlock:failureblock];
``` |
51,482,091 | I couldn't find any working examples to test for whether an event was emitted and whether the emitted value is as expected.
Here is the class that emits messages and its parent:
```
const EventEmitter = require('events').EventEmitter;
class FileHandler extends EventEmitter {
constructor() {
super();
}
canHandle(filePath) {
emit('not super type');
}
parseFile(filePath) {
emit('supper parsing failed');
}
whoAmI() {
return this.emit('who',"FileHandler");
}
}
module.exports = FileHandler;
//diff file
const FileHandler = require('./FileHandler');
class FileHandlerEstedamah extends FileHandler {
constructor() {
super();
}
canHandle(filePath) {
this.emit('FH_check','fail, not my type');
}
parseFile(filePath) {
this.emit('FH_parse','success');
}
}
module.exports = FileHandlerEstedamah;
```
Here is my current test code:
```
var sinon = require('sinon');
var chai = require('chai');
const FileHandlerEstedamah = require("../FileHandlerEstedamah");
describe('FH_parse', function() {
it('should fire an FH_parse event', function(){
const fhe = new FileHandlerEstedamah();
var fhParseSpy = sinon.spy();
fhe.on('FH_parse',fhParseSpy);
fhe.parseFile("path");
//I tried a large number of variants of expect, assert, etc to no avail.
});
});
```
I expected this to be straightforward but somehow I am missing something.
Thank you,
Jens | 2018/07/23 | [
"https://Stackoverflow.com/questions/51482091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/595638/"
] | You can assert the spy was called once and called with expected arguments as below
```
sinon.assert.calledOnce(fhParseSpy);
sinon.assert.calledWith(fhParseSpy, 'success');
``` |
994,426 | I know it's not *exactly* what SU is about, but I didn't know where else to turn at this point. I'm trying to hook up a Samsung LA32S81B television to my/a computer using HDMI. This is a moderately old TV, 2007 era, non-smart.
Originally, I tried to hook it up to my laptop, to no avail. I'll save you the long story of all the bug hunting I did, but eventually I came to the discovery that it's not the computer(s) at fault, nor the cable: the TV itself is not recognizing any HDMI from either my laptop or my desktop. My laptop, running win10, and later Win8.1 (after reading in some places win10 and HDMI have known to not play nice) was unable to get a link to the TV, and my desktop is also not able to output to it, or even recognize a screen is connected. Oddly enough, if I hook up, say, a cable box, to the same HDMI ports on the TV, using the same cable, I do get output, and if I for instance use the same HDMI cable and plug it into one of my computer monitors, the computer picks it up fine. It's literally only PC to TV that will NOT work. I've tried onboard graphics, I've tried my GTX970, I've tried old drivers, new drivers, I've factory resetted the TV, it won't budge. Nothing is working. I've tried literally everything I can think of. The only thing I can imagine is happening is that maybe the PCs are all outputting some format the TV won't recognize (which already seems unlikely, especially through HDMI), but then at least I would still imagine my computer to at least *notice* a screen is connected.
Is there *anyone* who has *any* idea what the hell is going on?
further info: desktop is Win10 and is also running two other monitors off of the GTX970, both are connected through DVI. Laptop had Intel onboard graphics, | 2015/10/31 | [
"https://superuser.com/questions/994426",
"https://superuser.com",
"https://superuser.com/users/246510/"
] | In looking at the specs for that TV, it does not support 1080p. Likely, your PC is outputting a 1080p signal and the TV can't sync to it.
Try these things:
* Lower your display resolution to 1280x720 (that's the HDTV 720p spec).
* On the TV, make sure the HDMI input says PC as the source type (Samsungs in particular have undocumented behavior where they overscan/underscan an image depending on what the input type is set to).
* Most laptops have an `Fn`+ key combination to enable/disable/mirror an external display. Fiddle with that to see if it makes a difference.
* In Windows, make sure it understands that you have two screens, and that the "Extend my desktop onto this monitor" checkbox is selected for the TV.
Hope it helps. |
24,668,826 | Im new to ASP. can any body give the sample code for select all the checkbox while selecting one checkbox from the check box list.
Select All
A
B
C
once checking the select all check from the checkbox list all other items also should get selected. | 2014/07/10 | [
"https://Stackoverflow.com/questions/24668826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3823967/"
] | From you image it seems like you presented the ViewController using push
The `dismissViewControllerAnimated` is used to close ViewControllers that presented using modal
**Swift 2**
```
navigationController.popViewControllerAnimated(true)
```
**Swift 4**
```
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
``` |
57,012,262 | i want to use the optional arguments without `-` or `--`,
want to achive something like this:
```
scriptname install <other options>
scriptname uninstall <other options>
```
my code:
```
parser = argparse.ArgumentParser()
parser.add_argument("install","INSTALL",action='store_true',help="INSTALL SOMETHING",default="")
parser.add_argument("uninstall","UNINSTALL",action='store_true',help="UNINSTALL SOMETHING",default="")
args = parser.parse_args()
if args.install:
install logic
if args.uninstall:
uninstall logic
```
getting the error below
```
ValueError: invalid option string 'install': must start with a character '-'
``` | 2019/07/12 | [
"https://Stackoverflow.com/questions/57012262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8369163/"
] | You don't have to use Selenium when you can just extract the match stats right off the HTML:
```py
import re
from ast import literal_eval
url = 'https://www.whoscored.com/Matches/1294545/LiveStatistics/Germany-Bundesliga-2018-2019-Bayern-Munich-Hoffenheim'
res = requests.get(
url,
headers={
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0',
}
)
res.raise_for_status()
html = res.text
```
so far nothing special.
```py
match_data = re.search('var matchStats = ([^;]+)', html, flags=re.MULTILINE).group(1)
match_data_clean = re.sub(',,', ",'',", match_data_clean)
stats = literal_eval(match_data_clean)
```
when we inspect `match_data` we can see a bunch of arrays with invalid syntax, like this:
```
ams',,'yellow',,,21,328
```
so we clean that off with a bit of `re` magic by inserting empty strings between commas.
Printing `stats` gives us:
```
[[[37,
1211,
'Bayern Munich',
'Hoffenheim',
'24/08/2018 19:30:00',
'24/08/2018 00:00:00',
6,
'FT',
'1 : 0',
'3 : 1',
'',
'',
'3 : 1',
'Germany',
'Germany'],
[[[21, [], [['Kasim Adams', '', 'yellow', '', '', 21, 328428, 0]], 0, 1],
[23,
[['Thomas Müller',
'Joshua Kimmich',
'goal',
'(1-0)',
'',
23,
37099,
283323]],
[],
1,
0],
```
from here on, it's just finding the right indices that correspond to the data you're looking for. |
2,773,644 | I'd like to host a WCF web service in IIS. The service should keep a certain set of data all the time, it must never be lost.
My colleague told me this is impossible because IIS closes down the service after a certain time (I assume without any activity). Is that true? How do I prevent that behavior?
In case it matters, both IIS 6 and 7 are available. | 2010/05/05 | [
"https://Stackoverflow.com/questions/2773644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39590/"
] | By default, IIS recycles the worker process after a certain period of inactivity (20 mins if I recall correct). This causes your data to be lost.
You can turn off this behavior in the Properties page of the ApplicationPool under which your app is running.
EDIT: having said that, if it is *really* important that this data is never lost, I would consider storing it in a database or some other form of storage. |
74,360,884 | I deleted a category which is an f-key of the items table. Now the view has an error saying 'Attempt to read property "category\_name" on null'. How do I render a null foreign key?
I tried if-else:
```
@if({{$item->category->category_name}} === 'null')
<h2>no category</h2>
@else
{{ $item->category->category_name}}
@endif
``` | 2022/11/08 | [
"https://Stackoverflow.com/questions/74360884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17040377/"
] | Try this:
```
@if ($item->category)
{{ $item->category->category_name }}
@else
<h2>no category</h2>
@endif
```
Or simply
```
<h2>{{ $item->category?->category_name ?? 'no category' }}</h2>
``` |
53,301,678 | I am using post navigation for my blog. For this portion i wrote some css. It's working fine. But the problem is for the very latest post , it's showing blank space for next post link. Same thing is happened with oldest post, it's showing again bank space for previous post link. [![enter image description here](https://i.stack.imgur.com/SFMaK.png)](https://i.stack.imgur.com/SFMaK.png)
I add code snippet for this portion. Can i anyone suggest how can i modify my css for this portion. Following code is embedded in php file.
```
<div class="row justify-content-center">
<div class="sewl-more-posts">
<div class="previous-post">
<?php If(previous_post_link()){?>
<span class="post-control-link">Previous Article</span>
<span class="post-name"><?php previous_post_link(); ?></span>
<?php } ?>
</div>
<div class="next-post">
<?php If(next_post_link()){?>
<span class="post-control-link">Next Article</span>
<span class="post-name"><?php next_post_link(); ?></span>
<?php } ?>
</div>
</div>
</div>
``` | 2018/11/14 | [
"https://Stackoverflow.com/questions/53301678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10043462/"
] | First, output the divs only if they'll have content:
```
<div class="sewl-more-posts">
<?php if (previous_post_link()){?>
<div class="previous-post">
<span class="post-control-link">Previous Article</span>
<span class="post-name"><?php previous_post_link(); ?></span>
</div>
<?php } ?>
<?php if (next_post_link()){?>
<div class="next-post">
<span class="post-control-link">Next Article</span>
<span class="post-name"><?php next_post_link(); ?></span>
</div>
<?php } ?>
</div>
```
This way, if the previous-post or next-post div is missing, you'll be able to target the remaining one with the [`:only-child` pseudo class](https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child):
```
.sewl-more-posts > div:only-child {
text-align: center;
}
``` |
8,177,473 | ```
int array[10] = {1,2,3,4,5,6,7,8};
int *ptr = array;
std::cout<<*(ptr+ 2); => O/P = 3
int (*arr_ptr)[10] = &array;
std::cout<<*(*arr_ptr+2); => O/P = 3
```
Whats the difference between these 2. I know what they mean, but if they give same result why do we have 2 different notations? | 2011/11/18 | [
"https://Stackoverflow.com/questions/8177473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/996330/"
] | The first case is the normal case: `ptr` is a pointer to the first element of the array `array`, and it is indexed (using `*(ptr+2)`, which is a synonym for `ptr[2]`) to access the third element of that array.
The second case is contrived: `arr_ptr` is a pointer to the (enitre) array `array`. It is first dereferenced (with `*arr_ptr`) to yield the array itself, which is then used as an argument to binary `+`, which causes it to get implicitly converted to a (nameless) pointer to its first element, which is then indexed in the same way `*(<nameless pointer>+2)` and gives the same result.
Making those implicit conversions explicit, you could write
```
int *ptr = &array[0];
std::cout<<*(ptr+ 2);
int (*arr_ptr)[10] = &array;
std::cout<<*( &(*arr_ptr)[0] + 2 );
``` |
3,763,347 | I am trying to figure out the Taylor coefficient of $\exp\left\{\frac{z+1}{z-1}\right\}$. My idea is as follows:
$$f(z)=\exp\left\{\frac{z+1}{z-1}\right\}=\exp\left\{1+\frac{2}{z-1}\right\}=e\exp\left\{\frac{2}{z-1}\right\}.$$
Then we have $f(z)=e\sum\_{n=0}^{+\infty}\frac{w^n}{n!}$, where $w=\frac{2}{z-1}$. Clearly, we have
$$w^n=(-2)^n(1-z)^{-n}=(-2)^n\sum\_{k=0}^{+\infty}\frac{\Gamma(n+k)}{k!\Gamma(n)}z^k.$$
It follows that
$$f(z)=e\sum\_{n=0}^{+\infty}\frac{w^n}{n!}=e\sum\_{n=0}^{+\infty}\frac{(-2)^n}{n!}\sum\_{k=0}^{+\infty}\frac{\Gamma(n+k)}{k!\Gamma(n)}z^k=e\sum\_{k=0}^{+\infty}\sum\_{n=0}^{+\infty}\frac{(-2)^n}{n!}\frac{\Gamma(n+k)}{k!\Gamma(n)}z^k.$$
Namely, the $n$-th coefficient of $f$ is given by
$$\widehat{f}(k)=e\sum\_{n=0}^{+\infty}\frac{(-2)^n}{n!}\frac{\Gamma(n+k)}{k!\Gamma(n)}.$$
I have checked that $\widehat{f}(0)=f(0)$ and $\widehat{f}(1)=f'(0)$. Moreover, the fact that $f''(0)=0$ implies that $\widehat{f}(2)$ should be zero. But in our result it seems that
$$\widehat{f}(2)=e\sum\_{n=0}^{+\infty}\frac{(-2)^n}{n!}\frac{\Gamma(n+2)}{2!\Gamma(n)}\neq 0.$$
What is wrong with my formula? Could you help me figure our the problem and tfind out the Taylor coefficient of the $f$? Thank you! | 2020/07/20 | [
"https://math.stackexchange.com/questions/3763347",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/83239/"
] | Write
$$ f(z):=\exp{\big(\frac{z+1}{z-1}\big)} =\frac{1}{e}\exp{\big(\frac{2z}{z-1}\big)} $$
Use the generating function for the Laguerre polynomials to show
$$ f(z)=\frac{1}{e} \sum\_{n=0}^\infty L\_n^{(-1)}(2)z^n $$
Thus, using the 'coefficient of' operator
$$ [z^n] f(z) = \frac{1}{e} L\_n^{(-1)}(2) .$$
It is perhaps more convenient to look up the explicit construction of the Laguerre polynomial and write this as
$$ [z^n] f(z) = \frac{1}{e}\sum\_{m=0}^n(-1)^m\binom{n-1}{n-m}\frac{2^m}{m!} .$$ |
1,202,075 | I would like to update a table in mySql with data from another table.
I have two tables "people" and "business". The people table is linked to the business table by a column called "business\_id".
The necessary table structure, primary key is starred (Table: columns):
People: \*business\_id, \*sort\_order, email
Business: \*business\_id, email
I would like to update the business table email column with the email from the people table, something like this (I know I am missing something here):
```
UPDATE business b SET email = (SELECT email from People p where p.business_id = b.business_id AND sort_order = '1') WHERE b.email = '';
```
Does this make sense? Is it possible? | 2009/07/29 | [
"https://Stackoverflow.com/questions/1202075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54259/"
] | ```
UPDATE business b, people p
SET b.email = p.email
WHERE b.business_id = p.business_id
AND p.sort_order = '1'
AND b.email = ''
``` |
40,407,955 | I have component that renders jsx like this
```
<section>
<div>
<input type="text" class="hide" />
<button id={item.uniqueID}>show input</button>
</div>
<div>
<input type="text" class="hide" />
<button id={item.uniqueID}>show input</button>
</div>
<div>
<input type="text" class="hide" />
<button id={item.uniqueID}>show input</button>
</div>
</section>
```
I want this behavior, when I click the button in the first div, the input in the first div will show. Similarly, I click the button in the third div the input in third div will show.
How you do that in react? | 2016/11/03 | [
"https://Stackoverflow.com/questions/40407955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/455340/"
] | If it were me I would make a new component out of:
show input
Lets call it `<InputToggler/>`
and then it would have a state of inputHidden for its own input and use classes to determine if it should show or not and the button would have an onclick handler to toggle the state of hidden or shown. Here is a pen showing exactly that
<http://codepen.io/finalfreq/pen/VKPXoN>
```
class InputToggler extends React.Component {
constructor() {
super();
this.state = {
inputHidden: true
}
}
toggleInput = () => {
this.setState({
inputHidden: !this.state.inputHidden
})
};
render() {
const inputClass = this.state.inputHidden ? 'hide' : '';
const buttonLabel = this.state.inputHidden ? 'show input' : 'hide input'
return (
<span>
<input type="text" className={inputClass} />
<button onClick={this.toggleInput} id={this.props.item.uniqueID}>
{buttonLabel}
</button>
</span>
)
}
}
``` |
55,268,495 | In some discussions it's claimed that void\* is "pointer to void object" but in C standard 6.5.3.4, point 2 it is written:
"The sizeof operator yields the size (in bytes)....The size is determined from the type of the operand."
So it is stated that function sizeof() receives a type as arguments.
So the compiler considers void\* a type? or the use of \* it's only for semantical interpretation? | 2019/03/20 | [
"https://Stackoverflow.com/questions/55268495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10847083/"
] | A `void *` is a valid type that has a known size. What it points to is either some object whose type is not known or valid untyped memory (i.e. memory returned from `malloc`). As such `sizeof(void *)` is a valid expression.
Paragraph 1 of 6.5.3.4 states:
>
> **The `sizeof` operator shall not be applied to an expression that has
> function type or an incomplete type, to the parenthesized name
> of such a type**, or to an expression that designates a
> bit-field member. The
> `_Alignof` operator shall not be applied to a function type or an incomplete type.
>
>
>
Because `void *` is not an incomplete type, `sizeof(void *)` is valid. However, because `void` type is incomplete, `sizeof(void)` is invalid.
Addressing your comment about `void **`, that is also a valid type which points to an object of type `void *`.
Some compilers such as GCC implement an extension where `void` has a size of 1 , so `sizeof(void) == 1` and pointer arithmetic on a `void *` functions in a similar manner to arithmetic on a `char *`. This however goes against the standard. |
35,917,100 | I am developing an Android app. In my app I need to work with tabs. But when I add tabs to TabLayout in code, it is throwing error. What is wrong with my code?
This is my tablayout XML in custom action bar:
```
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:background="@color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/action_bar_padding_top"
android:paddingBottom="@dimen/action_bar_padding_bottom"
android:paddingLeft="@dimen/action_bar_padding_left"
android:paddingRight="@dimen/action_bar_padding_right">
<ImageButton
android:id="@+id/open_left_drawer_icon"
android:background="@drawable/nav_open"
android:layout_width="@dimen/nav_icon_width"
android:layout_height="@dimen/nav_icon_height" />
<TextView
android:layout_centerHorizontal="true"
android:text="@string/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/main_logo_text_size"/>
<ImageButton
android:layout_alignParentRight="true"
android:background="@drawable/wishlist_icon"
android:layout_width="@dimen/nav_icon_width"
android:layout_height="@dimen/nav_icon_height" />
</RelativeLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/main_tab_layout"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize" />
</LinearLayout> </LinearLayout>
```
How I set up tabs to tablayout in activity:
```
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = (TabLayout)findViewById(R.id.main_tab_layout);
setupTabs();
}
private void setupTabs() {
tabLayout.addTab(tabLayout.newTab().setTag(1).setText("TRENDY/HOT"));
tabLayout.addTab(tabLayout.newTab().setTag(2).setText("MEN"));
tabLayout.addTab(tabLayout.newTab().setTag(3).setText("WOMEN"));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()){
case 1:
break;
case 2:
break;
default:
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
switch (tab.getPosition()){
case 1:
break;
case 2:
break;
default:
break;
}
}
});
}
}
```
This is the error in logacat when I run the app:
```
03-10 12:52:12.610 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion W/dalvikvm: VFY: unable to resolve virtual method 496: Landroid/content/res/TypedArray;.getType (I)I
03-10 12:52:12.610 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
03-10 12:52:12.618 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_FOR_ALLOC freed 143K, 10% free 2617K/2892K, paused 3ms, total 4ms
03-10 12:52:12.670 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_FOR_ALLOC freed 21K, 10% free 2870K/3168K, paused 1ms, total 2ms
03-10 12:52:12.706 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_FOR_ALLOC freed 98K, 12% free 2992K/3392K, paused 3ms, total 3ms
03-10 12:52:12.710 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion I/dalvikvm-heap: Grow heap (frag case) to 4.121MB for 1127532-byte allocation
03-10 12:52:12.718 7428-7430/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_CONCURRENT freed <1K, 9% free 4093K/4496K, paused 2ms+1ms, total 7ms
03-10 12:52:12.722 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_FOR_ALLOC freed <1K, 9% free 4094K/4496K, paused 2ms, total 2ms
03-10 12:52:12.726 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion I/dalvikvm-heap: Grow heap (frag case) to 6.541MB for 2536932-byte allocation
03-10 12:52:12.734 7428-7430/com.blog.waiyanhein.mmfashion.mmfashion D/dalvikvm: GC_CONCURRENT freed 0K, 6% free 6571K/6976K, paused 1ms+1ms, total 4ms
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion D/AndroidRuntime: Shutting down VM
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa61d4908)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: FATAL EXCEPTION: main
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blog.waiyanhein.mmfashion.mmfashion/com.blog.waiyanhein.mmfashion.mmfashion.MainActivity}: java.lang.NullPointerException
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5041)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: Caused by: java.lang.NullPointerException
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.blog.waiyanhein.mmfashion.mmfashion.MainActivity.setupTabs(MainActivity.java:395)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.blog.waiyanhein.mmfashion.mmfashion.MainActivity.onCreate(MainActivity.java:98)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5104)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5041)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-10 12:52:12.774 7428-7428/com.blog.waiyanhein.mmfashion.mmfashion E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
03-10 12:52:12.778 396-407/system_process W/ActivityManager: Force finishing activity com.blog.waiyanhein.mmfashion.mmfashion/.MainActivity
03-10 12:52:12.898 396-407/system_process D/dalvikvm: GC_FOR_ALLOC freed 175K, 35% free 6244K/9560K, paused 16ms, total 16ms
03-10 12:52:12.898 396-407/system_process I/dalvikvm-heap: Grow heap (frag case) to 7.042MB for 856092-byte allocation
03-10 12:52:12.910 396-411/system_process D/dalvikvm: GC_FOR_ALLOC freed 4K, 32% free 7075K/10400K, paused 12ms, total 12ms
03-10 12:52:12.938 396-399/system_process D/dalvikvm: GC_CONCURRENT freed 7K, 31% free 7191K/10400K, paused 9ms+1ms, total 28ms
03-10 12:52:12.938 396-412/system_process D/dalvikvm: WAIT_FOR_CONCURRENT_GC blocked 4ms
```
Why cannot set tabs to TabLayout? But when I remove calling setUpTabs function in onCreate, app is running fine. | 2016/03/10 | [
"https://Stackoverflow.com/questions/35917100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4675736/"
] | Your id of TabLayout in your xml is `@+id/tab_layout"` but you're finding the view with id `main_tab_layout` in your Activity.
Line `tabLayout = (TabLayout)findViewById(R.id.main_tab_layout);`
It should be `tabLayout = (TabLayout)findViewById(R.id.tab_layout);` |
26,455,839 | I just came across this code:
```
array_filter(array_map('intval', $array));
```
It seems to return all entries of $array converted to int where the number is > 0.
However, I can't see on the manual page that this is defined. It is supposed to return the array value if the callback function evaluates to true. But there isn't any callback function defined here.
Confusing is also that the callback function is optional on [the manual page](http://php.net/manual/en/function.array-filter.php). | 2014/10/19 | [
"https://Stackoverflow.com/questions/26455839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123594/"
] | Removes empty or equivalent values from array:
```
$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => '',
5 => 0
);
print_r(array_filter($entry));
```
**Result**
```
Array
(
[0] => foo
[2] => -1
)
```
See the [original documentation](http://php.net/manual/en/function.array-filter.php#example-6190) from the manual:
**Example #2 array\_filter() without callback** |
329,336 | In my quest to better my experience in my windows 7 environment, I have installed cygwin and have started using mintty as my command line interface tool. This has been nice and takes me back to my more productive days in working in a unix environment.
There is one annoying thing however, that I can't seem to get working correctly. Batch files (i.e. \*.bat) will not auto complete on the command line, nor will they show up properly colored when ls --color is used. I've tracked this down (I think) to the fact that the bat files are showing up as rw-r--r--. I can do something like ./run\_my\_batch\_file.bat from the command line and the batch file will properly run, but I have to type the full filename or else auto complete will not pick it up.
I did try running 'chmod 750' (as well as various other file modes) to change the batch file to sport the 'x' bit, but their mode bits did not change. I'm pretty sure that I can attribute this to the fact that I am mounting my local drives with the 'noacl' option. Here is the relevant line from my fstab:
```
none /cygdrive cygdrive binary,posix=0,user,noacl 0 0
```
I put the 'noacl' in because without it, the file mode bits seems all screwed up. Here is an example listing without the 'noacl' parameter.
```
-r-x------+ 1 Administrators Domain Users 209K Jul 18 16:46 some.dll
-rwx------+ 1 Administrators Domain Users 867K Aug 22 11:21 binary_filea
-rwx------+ 1 Administrators Domain Users 736K Aug 28 18:02 binary_fileb
-rwx------+ 1 Administrators Domain Users 736K Aug 28 17:43 binary_filec
-rwx------+ 1 Administrators Domain Users 14K Jan 21 2010 cache_00.bak
-r-x------+ 1 Administrators Domain Users 354K Jun 6 22:42 cdb.exe
-rwx------+ 1 Administrators Domain Users 22 Mar 14 08:05 cleanup_scratch_folder.bat
drwx------+ 1 Administrators Domain Users 0 Mar 3 14:59 code
-rwx------+ 1 Administrators Domain Users 1.8K Aug 12 14:34 config.txt
-rwx------+ 1 Administrators Domain Users 52 Aug 28 19:05 console_history
-rwx------+ 1 Administrators Domain Users 3.8M Aug 23 09:46 copy_files.bat
```
(note that the directory listing above is from my /cygdrive/d drive - which is a local NTFS filesystem). That seemed pretty messed up so I went with the 'noacl' mount option to get me accurate file modes for the files in my directories.
One last note - I do have the full bash completion package installed. I briefly looked to see if I could modify one of the completion packages to get at least part of what I want (which is batch file auto completion), but I didn't find anything that would be relevant there.
So my questions can I properly change the batch file file modes to include 'x' so that I can get proper bash command line completion on them (as well as get proper directory coloring on them because they are executable files). Auto-complete is more important FWIW.
Thanks. | 2011/08/29 | [
"https://superuser.com/questions/329336",
"https://superuser.com",
"https://superuser.com/users/27663/"
] | I'm not sure of the answer to your question, but here are a few things that might help:
* Check that the `PATHEXT` environment variable includes `.BAT`.
* Read about the `noacl` option [here](http://www.cygwin.com/cygwin-ug-net/using.html). It seems that you might do better to remove `noacl`, and spend some time getting the real permissions right.
* Ask on the [cygwin mailing list](http://cygwin.com/lists.html#cygwin). There are many experts there who can almost certainly answer your question. |
63,595,089 | I'm trying to set chrome as default browser for launching jupyter notebook. For this i'm following the usual steps-
1. In anaconda prompt, i fired- `jupyter notebook --generate-config`
,a config file 'jupyter\_notebook\_config.py' is created.
2. Opened the file in notepad & change the line `# c.NotebookApp.browser = ''` to `c.NotebookApp.browser = u'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'`
3. Saved the file & run the file, got an error, PF the Screenshot-
[error](https://i.stack.imgur.com/ey2MB.png)
Traceback (most recent call last):
File "jupyter\_notebook\_config.py", line 99, in
c.NotebookApp.browser = u'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
NameError: name 'c' is not defined
Can anyone please let me know what is object c here, which class it invokes? | 2020/08/26 | [
"https://Stackoverflow.com/questions/63595089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13994287/"
] | In windows 10 - Goto file explorer - browse to C:\Users\your user name\AppData\Roaming\jupyter\runtime. Locate the nbserver-####-open.html files. Right click anyone of them. Select Properties (at bottom). With popup window, choose OPEN WITH: change button (at top) and select browser of your choice. |
52,220,105 | I want to format pagination in laravel like this:
```
api/posts?from=1&to=10
```
I tried:
```
$posts = new LengthAwarePaginator(Post::all(), 100, 10);
return $posts->toArray();
```
Which didn’t work at all :( Please help | 2018/09/07 | [
"https://Stackoverflow.com/questions/52220105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9764412/"
] | Try this
```
$x = array_search ('english', $request->all());
``` |
69,254,790 | I have a small issue with my application that I spotted when testing it. I have a `println` statement that should run to inform the user they have entered an invalid **product code**.
I have a **for-loop** that will run through an Array List of objects where an if statement will match each item in said Array List to a local variable named **searchTerm**.
The issue is that if the **searchTerm** does not match the item[0] with in the ArrayList then, the else statement will run more than once, thus executing the `println` statement multiple times.
```
static void searchProduct() {
System.out.print("Please enter product code to search: ");
String searchTerm = in.nextLine().toUpperCase();
for (int i = 0; i < report.size(); i++) {
if (report.get(i).code.equals(searchTerm)) {
System.out.println("****************************************************************************"
+ "\nPRODUCT SEARCH RESULTS"
+ "\n****************************************************************************");
System.out.println("PRODUCT CODE >> " + report.get(i).code);
System.out.println("PRODUCT NAME >> " + report.get(i).name);
System.out.println("PRODUCT CATERGORY >> " + report.get(i).category);
System.out.println("PRODUCT WARRANTY >> " + report.get(i).warranty);
System.out.println("PRODUCT PRICE >> " + report.get(i).price);
System.out.println("PRODUCT LEVEL >> " + report.get(i).stock);
System.out.println("PRODUCT SUPPLIER >> " + report.get(i).supplier);
System.out.println("****************************************************************************");
}
else {
// System.out.println("The product cannot be located. Invalid Product");
}
}
System.out.println("Enter (1) to launch menu or any other key to exit");
String opt2 = in.nextLine();
if (opt2.equals("1")) {
mainMenu.Menu();
}
else { System.exit(0); }
}
``` | 2021/09/20 | [
"https://Stackoverflow.com/questions/69254790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16740107/"
] | Separate out the printing from the looping:
Loop through the list until you find the item:
```
Report r = null;
for (int i = 0; i < report.size(); ++i) {
if (report.get(i).code.equals(searchTerm)) {
r = report.get(i);
break;
}
}
// or
for (Report rep : report) {
if (rep.code.equals(searchTerm)) {
r = rep;
break;
}
}
// or
Report r = report.stream().filter(rep -> rep.code.equals(searchTerm)).findFirst().orElse(null);
```
Now, `r` is only non-null if you found something, so, after the loop:
```
if (r != null) {
// Print stuff.
} else {
// Print message saying you didn't find it.
}
``` |
47,061,829 | I'm trying to get image format plugins working on Android.
My plan is to build this [APNG](https://github.com/Skycoder42/qapng) image format plugin, which closely follows the style of the official Qt extra [image format plugins](http://doc.qt.io/qt-5/qtimageformats-index.html). The answer to my problem will be the same for these too.
On desktop (windows) it works. So long as you put the plugin DLL into a `imageformats` subdirectory like this:
```
myapp/<all my binaries>
imageformats/qapng.dll
```
But on Android, it's another story;
First idea was to put `libqapng.so` into `libs` so that `qtcreator` bundles it up with all the others as part of an APK build. It goes in, but is not loaded by Qt at runtime.
So i look into how the existing qt image formats work;
turns out, rather than being in a subdirectory, they are named according to this pattern;
`libplugins_imageformats_libqapng.so`
So i rename `libqapng.so` to the above and put that into `libs`. Nice try, but it didn't work.
After a lot of head scratching, i discover there's a secret *resource* array that connects the logical location of plugins to the physical file names;
This lives in;
`res/values/libs.xml`
and looks like this:
```
<array name="bundled_in_lib">
...
<item>libplugins_imageformats_libqgif.so:plugins/imageformats/libqgif.so</item>
<item>libplugins_imageformats_libqicns.so:plugins/imageformats/libqicns.so</item>
<item>libplugins_imageformats_libqico.so:plugins/imageformats/libqico.so</item>
<item>libplugins_imageformats_libqjpeg.so:plugins/imageformats/libqjpeg.so</item>
<item>libplugins_imageformats_libqsvg.so:plugins/imageformats/libqsvg.so</item>
<item>libplugins_imageformats_libqtga.so:plugins/imageformats/libqtga.so</item>
<item>libplugins_imageformats_libqtiff.so:plugins/imageformats/libqtiff.so</item>
<item>libplugins_imageformats_libqwbmp.so:plugins/imageformats/libqwbmp.so</item>
<item>libplugins_imageformats_libqwebp.so:plugins/imageformats/libqwebp.so</item>
....
```
So, i just need to get my new plugin into that list.
Sure enough, if i **HACK** it in, it works! but how to add my plugin to this list properly as part of the build?
[this](http://doc.qt.io/qt-5/deployment-android.html) page on Qt Android deployment mentions a thing called `bundled_in_lib`, which is indeed what i need. But it unfortunately does not explain how to change this or to add to it.
I'm thinking there might be a secret magic spell i can add to my `qmake` `.pro` file to affect this `bundled_in_lib` resource.
How to do it? or is there a better way that I've not yet seen. There doesn't seem to be much about explaining these details for Android.
On a final note, an alternative might be to manually load the plugin in `main.cpp`. I've tried this and it doesn't work. Perhaps, they need to be loaded by the Qt image format plugin loader rather than just *loaded* at all. Maybe there's a way to do this. not sure?
using Qt5.9.1
Thanks for any help. | 2017/11/01 | [
"https://Stackoverflow.com/questions/47061829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1964167/"
] | Following @Felix answer, `ANDROID_EXTRA_PLUGINS` is correct, but how it works is a bit strange.
Following a discussion on the lack of doc for this feature [here](https://bugreports.qt.io/browse/QTBUG-60022), and some trial and error, i found that;
`ANDROID_EXTRA_PLUGINS` must specify a *directory*, not a file. So you point to a plugins directory of your own. Things below this directory (including subdirectories) get mangled as in my original question and explained below.
So, for my plugin `libqapng.so`, i have:
`ANDROID_EXTRA_PLUGINS += <some path>/plugins`
and my android plugin building .pro puts the output in;
`<some path again>/plugins/imageformats/libqapng.so`
The `.so` lib, then winds up mangled in (eg. for arm);
`android-build/libs/armeabi-v7a/libplugins_imageformats_libqapng.so`
and the resources get the entry;
`android-build/res/values/libs.xml`
```
<array name="bundled_in_lib">
...
<item>libplugins_imageformats_libqapng.so:plugins/imageformats/libqapng.so</item>
</array>
```
as required.
Thanks to @Felix for almost the answer, but i thought I'd write up the extra details here for the benefit of others. |
421,335 | So here's the question:
***We want to design a circuit that determines if a four-bit number is less than 10 and is also even.***
***a. (10 points) Write an expression of M such that M=1 if the four-bit number X (x3 x2 x1 x0) is less than 10
and is also even.***
Is this asking for the answer in POS form since it is using "M" instead of "m"? | 2019/02/09 | [
"https://electronics.stackexchange.com/questions/421335",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/212333/"
] | They probably want the simplest form. |
48,333,458 | I want to repeat data using div and in this div , I have one more repeatation using id value from first repeatation. So I want to pass this value using function in ng-init but got me error.
```
<div ng-controller="ProductsCtrl" ng-init="getData()">
<div class="col-sm-12" ng-repeat="data in form">
<div class="card">
<div class="card-header">
<h4>{{data.title}}</h4>
</div>
<div class="card-block">
<div class="row" ng-init="getImages({{data.id}})">
<div class="form-group col-sm-3" ng-repeat="image in images">
<figure>
<img ng-src="{{imgURL}}/{{image.file_name}}" width="220" height="176">
<figcaption>Fig.1 - A view of the pulpit rock in Norway.</figcaption><br />
<label>Description : {{image.remarks}}</label><br />
<a href="">Read More . .</a>
</figure>
</div>
</div>
</div>
<div class="card-footer">
<h4>{{data.description}}</h4>
</div>
</div>
</div>
</div>
```
So, how can I pass {{data.id}} in ng-init="getImages({{data.id}})"? If I put value ng-init="getImages(15)" then, item will appear.
file.js
```
$scope.getImages = function (id2) {
$http.get(commonData.apiURL + 'product/detailsImage.php?id='+id2)
.success(function (data) {
$scope.images = data;
//console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
}
``` | 2018/01/19 | [
"https://Stackoverflow.com/questions/48333458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7942721/"
] | >
> `I was hoping someone could use the context of this question to help me understand pointers better....`
>
>
>
In context of your program:
```
int main(int argc, char *argv[])
```
First, understand what is `argc` and `argv` here.
**`argc`(argument count):** is the number of arguments passed into the program from the command line, including the name of the program.
**`argv`(argument vector):** An array of character pointers pointing to the string arguments passed.
A couple of points about `argv`:
* The string pointed to by `argv[0]` represents the program name.
* `argv[argc]` is a null pointer.
For better understanding, let's consider an example:
Say you are passing some command line arguments to a program -
```
# test have a nice day
```
`test` is the name of the executable file and `have`, `a`, `nice` and `day` are arguments passed to it and in this case, the argument count (`argc`) will be `5`.
The in-memory view of the argument vector (`argv`) will be something like this:
```
argv --
+----+ +-+-+-+-+--+ |
argv[0]| |--->|t|e|s|t|\0| |
| | +-+-+-+-+--+ |
+----+ +-+-+-+-+--+ |
argv[1]| |--->|h|a|v|e|\0| |
| | +-+-+-+-+--+ |
+----+ +-+--+ |
argv[2]| |--->|a|\0| > Null terminated char array (string)
| | +-+--+ |
+----+ +-+-+-+-+--+ |
argv[3]| |--->|n|i|c|e|\0| |
| | +-+-+-+-+--+ |
+----+ +-+-+-+--+ |
argv[4]| |--->|d|a|y|\0| |
| | +-+-+-+--+ |
+----+ --
argv[5]|NULL|
| |
+----+
```
A point to note about string (null-terminated character array) that it decays into pointer which is assigned to the type `char*`.
Since `argv` (argument vector) is an array of pointers pointing to string arguments passed. So,
```
argv+0 --> will give address of first element of array.
argv+1 --> will give address of second element of array.
...
...
and so on.
```
We can also get the address of the first element of the array like this - `&argv[0]`.
That means:
```
argv+0 and &argv[0] are same.
```
Similarly,
```
argv+1 and &argv[1] are same.
argv+2 and &argv[2] are same.
...
...
and so on.
```
When you dereference them, you will get the string they are pointing to:
```
*(argv+0) --> "test"
*(argv+1) --> "have"
....
....
and so on.
```
Similarly,
```
*(&argv[0]) --> "test"
```
`*(&argv[0])` can also written as `argv[0]`.
which means:
```
*(argv+0) can also written as argv[0].
```
So,
```
*(argv+0) and argv[0] are same
*(argv+1) and argv[1] are same
...
...
and so on.
```
When printing them:
```
printf ("%s", argv[0]); //---> print "test"
printf ("%s", *(argv+0)); //---> print "test"
printf ("%s", argv[3]); //---> print "nice"
printf ("%s", *(argv+3)); //---> print "nice"
```
And since the last element of argument vector is `NULL`, when we access - `argv[argc]` we get `NULL`.
To access characters of a string:
```
argv[1] is a string --> "have"
argv[1][0] represents first character of string --> 'h'
As we have already seen:
argv[1] is same as *(argv+1)
So,
argv[1][0] is same as *(*(argv+1)+0)
```
To access the second character of string "have", you can use:
```
argv[1][1] --> 'a'
or,
*(*(argv+1)+1) --> 'a'
```
I hope this will help you out in understanding pointers better in context of your question.
To identify the vowels in arguments passed to program, you can do:
```
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("ERROR: You need at least one argument.\n");
return -1;
}
for (char **pargv = argv+1; *pargv != argv[argc]; pargv++) {
/* Explaination:
* Initialization -
* char **pargv = argv+1; --> pargv pointer pointing second element of argv
* The first element of argument vector is program name
* Condition -
* *pargv != argv[argc]; --> *pargv iterate to argv array
* argv[argc] represents NULL
* So, the condition is *pargv != NULL
* This condition (*pargv != argv[argc]) is for your understanding
* If using only *pragv is also okay
* Loop iterator increment -
* pargv++
*/
printf ("Vowels in string \"%s\" : ", *pargv);
for (char *ptr = *pargv; *ptr != '\0'; ptr++) {
if (*ptr == 'a' || *ptr == 'e' || *ptr == 'i' || *ptr == 'o' || *ptr == 'u'
|| *ptr == 'A' || *ptr == 'E' || *ptr == 'I' || *ptr == 'O' || *ptr == 'U') {
printf ("%c ", *ptr);
}
}
printf ("\n");
}
return 0;
}
```
Output:
```
#./a.out have a nice day
Vowels in string "have" : a e
Vowels in string "a" : a
Vowels in string "nice" : i e
Vowels in string "day" : a
``` |
3,574 | I am getting the error -
`'System.QueryException: sObject type 'CollaborationGroup' is not supported.'`
When running the following code as part of a managed package by scheduled apex:
>
> List groups = [select id, name, description from
> collaborationGroup];
>
>
>
What's strange is that the code works if I run it in the developer console but not when it runs from scheduled apex (setup as part of a post install script).
I've got 'with sharing on' so could it be down to the installer user profile? It works in some installed instances but not others but can't see a reason e.g. SFDC edition, profile, chatter settings, etc...
I do know that Chatter has to be enabled but that is the case anyway in the partnerforce dev orgs.
What am I missing here? | 2012/10/22 | [
"https://salesforce.stackexchange.com/questions/3574",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/783/"
] | Your code must be run in a `without sharing` context in order for it to have access to the `CollaborationGroup` SObject. I'm guessing that your Utility class which contains the query is *not* explicitly declared as `without sharing`, so you can do one of two things:
1. Move all of your code into your actual PostInstall Script Apex class (the one that implements `InstallHandler`).
2. If possible, change the signature of your Utility class to be `without sharing`.
3. Extract out the particular logic that executes this query into a separate Utility class that is declared as `without sharing`. |
5,018,340 | I have this little piece of code, and I'm trying to convert a JSON string to a map.
```
String json = "[{'code':':)','img':'<img src=/faccine/sorriso.gif>'}]";
ObjectMapper mapper = new ObjectMapper();
Map<String,String> userData = mapper.readValue(json,new TypeReference<HashMap<String,String>>() { });
```
But it returns the following error:
```
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.HashMap out of START_ARRAY token
at [Source: java.io.StringReader@1b1756a4; line: 1, column: 1]
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:198)
at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:151)
at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:25)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2131)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1402)
at CodeSnippet_19.run(CodeSnippet_19.java:13)
at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain1.eval(ScrapbookMain1.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain.evalLoop(ScrapbookMain.java:54)
at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain.main(ScrapbookMain.java:35)
```
What am I doing wrong? | 2011/02/16 | [
"https://Stackoverflow.com/questions/5018340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613631/"
] | From what I remember Jackson is used to convert json to java classes - it is probably expecting the first object is reads to be a map, like
```
String json = "{'code':':)','img':'<img src=/faccine/sorriso.gif>'}";
``` |
57,698,746 | I am trying to do a migration in django 2.2.4 in python 3.7.
First I try to make do makemigations:
```
python3 manage.py makemigrations
```
I get:
```
Migrations for 'main':
main/migrations/0001_initial.py
- Create model TutorialCategory
- Create model TutorialSeries
- Create model Tutorial
```
But then I try the second step:
```
python3 manage.py migrate
```
I get:
```
Operations to perform:
Apply all migrations: admin, auth, contenttypes, main, sessions
Running migrations:
No migrations to apply.
```
Even though a migration should happen.
I tried deleting my migrations folder and then remaking it (with the empty `__init__.py` file inside) but it still doesn't work.
(Note: I have been following along the tutorial: Linking models with Foreign Keys - Django Web Development with Python p.9 by sentdex) | 2019/08/28 | [
"https://Stackoverflow.com/questions/57698746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8802333/"
] | Somehow your migrations are virtually or faked applied in the database, Truncating **django\_migrations** table should work.
1. Delete all the migrations files:
find . -path "*/migrations/*.py" -not -name "**init**.py" -delete
find . -path "*/migrations/*.pyc" -delete
2. Truncate table:
truncate django\_migrations
3. makemigrations, migrate. |
24,197,830 | let's say that I have a form
```
<form >
<div class="control-group">
<label class="control-label" for="numeinculpat">Nume inculpat</label>
<div class="controls">
<input type="text" id="numeinculpat" placeholder="Nume inculpat" name="nume" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="numeinculpat2">Nume inculpat2</label>
<div class="controls">
<input type="text" id="numeinculpat2" placeholder="Nume inculpat2" name="nume" />
</div>
</div>
</form>
```
---
And the user introduce some empty value .
How cand can I do if someone enter wrong data(or empty),when enter again, the input to have the value of data that he previous introduced ?? | 2014/06/13 | [
"https://Stackoverflow.com/questions/24197830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3677455/"
] | There are several ways to do this, one way is to create a directive with an isolate scope that accepts an array of `label`s to be displayed aligned with the `input[radio]` elements and second is the model for all the `input[radio]` elements. Create a template that handles the iteration of each label together with the `ngModel`(input radio) accepted in the `isolate scope`.
UPDATE: You can update all the `input[radio]` elements in your directive before the directive is linked, compile phase. Use `element.find('input')` to get all input radio elements inside the directive regardless of element levels. Evaluate if they are type radio and add the ngModel and name attributes accordingly.
Please see this UPDATED [PLUNKER DEMO](http://plnkr.co/edit/bKPaH6S6MocHAhF5iCUP?p=preview) (The Size Model Example) |
46,377,827 | Let us assume In PHP
```
$i = 016;
echo $i / 2;
```
The output is returning `7`.! why..? | 2017/09/23 | [
"https://Stackoverflow.com/questions/46377827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6382509/"
] | Appending 0 to the front of a number in PHP is making it octal.
16 in octal is equivalent to 14 in decimal.
So , 14/2 = 7 is the answer. |
2,825,220 | I currently have a JS function that allows me to load partial content from another page into the current page using jQuery.load()
However I noticed when using this that I get a duplicate ID in the DOM (when inspecting with FireBug)
This function is used in conjuction with a Flash Building viewe so it does not contain any code to retrieve the URL from the anchor tag.
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
```
The code above works just fine in retrieving the content, however it just bugs me that when inspecting with firebug I get something like this.
```
<div id="apartmentInfo">
<div id="apartmentInfo">
<!-- Remote HTML here..... -->
</div>
</div>
```
Can anyone please suggest anything on how to remove the duplicate div?
Thanks,
Warren | 2010/05/13 | [
"https://Stackoverflow.com/questions/2825220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69795/"
] | If it's just that ID that is causing you an annoyance, you could either change that id, or remove the duplicate when the document is loaded:
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
$(this).attr('id', 'somethingElse'); //change the id
// OR
$(this).children().unwrap(); // remove the second apartmentId from the DOM completely.
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
```
If it's multiple ID's, the only solution I can think of is to prefix all the ID's within the remote page with something, or load the remote page in an IFRAME.
```
function displayApartment(apartmentID) {
$("#apartmentInfo").load(siteURL + apartmentID + ".aspx #apartmentInfo", function () {
$(this).find('*[id]').andSelf().attr('id', function (index, previous) {
return 'a-random-prefix-' + previous;
});
//re-do links loaded in
$("a.gallery").colorbox({ opacity: "0.5" });
});
}
``` |
114,864 | I am trying to get Emacs (24.3.1), Org-mode (8.0.3, from ELPA) and BibTeX (from TeX Live 2012) to work together.
I have followed the instructions under the **Bibliography** section in <http://orgmode.org/worg/org-tutorials/org-latex-export.html> but after exporting the document to LaTeX, compiling to PDF, and opening the result (with key sequence `C-c C-e l o` in the latest Org mode) I see a question mark instead of a citation (i.e., **[?]**) which means that the reference was not resolved by LaTeX. In fact, checking the `Org PDF LaTeX Output` buffer, I see the following warning:
```
LaTeX Warning: Citation `Tappert77' on page 3 undefined on input line 43.
No file org-bib-test.bbl.
[3] (.//org-bib-test.aux)
LaTeX Warning: There were undefined references.
```
It looked to me that probably Org-mode was looking for a `.bib` file with the same base name as the `.org` file but renaming the `.bib` file and updating the `\bibliography` line did not solve the problem.
Here are two minimal `.org` and `.bib` files that together can be used to reproduce the behavior described above:
**`org-bib-test.org`**
```
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
```
The following, using `#+LATEX_HEADER`, gives the same result:
**`org-bib-test.org`**
```
#+LATEX_HEADER: \bibliographystyle{plain}
#+LATEX_HEADER: \bibliography{org-bib-test-refs}
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
```
**`org-bib-test-refs.bib`**
```
@incollection {Tappert77,
AUTHOR = {Tappert, Fred D.},
TITLE = {The parabolic approximation method},
BOOKTITLE = {Wave propagation and underwater acoustics ({W}orkshop,
{M}ystic, {C}onn., 1974)},
PAGES = {224--287. Lecture Notes in Phys., Vol. 70},
PUBLISHER = {Springer},
ADDRESS = {Berlin},
YEAR = {1977},
MRCLASS = {76.41 (86.41)},
}
```
Currently I am using the following **ugly** hack to get the references resolved: I generate the `.bbl` file from the `.bib` file (using a minimal `.tex` file) and then I `\include` the resulting `.bbl` file directly in my `.org` file. This is rather cumbersome and of course requires that I regenerate the `.bbl` file every time I make a change to the `.bib` file. Although this process can be automated in Emacs by writing a lisp function to encapsulate these actions, I'd rather solve the problem than streamline a hack.
**Edit**
I have checked the `.tex` file generated by Org mode. It *does* have the following necessary lines exported in it:
```
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
``` | 2013/05/18 | [
"https://tex.stackexchange.com/questions/114864",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/11886/"
] | @G.JayKerns has a perfectly good solution in the comments, but since this question has been a while without an answer, I'll fill it in. The important elisp variable is `org-latex-pdf-process`, which can work with a number of settings. I have mine set up as something like:
```lisp
(setq org-latex-pdf-process (list
"latexmk -pdflatex='lualatex -shell-escape -interaction nonstopmode' -pdf -f %f"))
```
That's a simplification since I set the actual variable dynamically based on some other orgmode macro lines, but the basic idea should work.
You can use explicit multiple iterations or a build process like `latexmk` or `rubber` within `org-latex-pdf-process`. Use what you would at the command line and check the log in the `*Org PDF LaTeX Output*` buffer if you get errors.
The org-mode file should look like this:
`org-bib-test.org`
```
* Tests
** Test1 slide
- This is test1 \cite{Tappert77}.
\bibliographystyle{plain}
\bibliography{org-bib-test-refs}
```
Put your bibtex in the file `org-bib-test-refs.bib` and run `C-c C-e l o` and you should be good. |
4,082 | I think that [this question](https://math.stackexchange.com/questions/3704/integral-representation-of-infinite-series) deserves to be reopened. Hopefully now that we have more meta members, enough others will agree. Please vote to reopen if you agree.
**Edit** $\ $ The question is now reopened. Thanks to everyone who helped. Apologies for not being clearer from the start as to why I thought it deserved reopening.
Perhaps now the question will come to the attention of others who can say more about some of the powerful techniques here that deserve to be more widely known. | 2012/05/01 | [
"https://math.meta.stackexchange.com/questions/4082",
"https://math.meta.stackexchange.com",
"https://math.meta.stackexchange.com/users/242/"
] | I cast the final reopen vote. While at face value I think it made a close-worthy question according to the word of the FAQ and rules and such, I personally have a higher bar for my close votes:
* If the question has proven amenable to a valuable and original contribution from some member of the community as an answer, it deserves to remain open.
* If the question is feasibly salvageable by the original poster, he or she should be given ample time and opportunity to attempt to do so as best they can with help from the community.
But why reopen *now*? Well, why not - what does timing have to do with anything? The past doesn't become less interesting mathematically or useful for our community by virtue of being in the past.
Ultimately I think closures serve as models to our question-askers and our close-voters about what kinds of questions are discouraged. It is a difficult situation to be in to have a question nagging at you incessantly, but at the same time not understand the mathematical context well enough to be able to ask a question properly about it, or even know if your thoughts correspond at all to a "real" question. (Been there, done that.) I want users to feel free to at least *try* and find out if something fruitful can be said about what they're exploring, as best as our community can manage, as well as balance with closing the incorrigible ones, and to that end I devised the above two bullet points. |
339,291 | After opening the emoji keyboard with `Ctrl + Cmd + Space`, selecting an emoji and finally hitting enter, the emoji keyboard closes but nothing is inserted at my cursor.
[![enter image description here](https://i.stack.imgur.com/S8hL5.png)](https://i.stack.imgur.com/S8hL5.png)
A restart seems to fix this, but after some time the keyboard breaks again and I need to restart again.
Does anyone have an idea why this is happening?
This is on macOS High Sierra v10.13.6 (17G2307)
Thank you. | 2018/10/11 | [
"https://apple.stackexchange.com/questions/339291",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/43263/"
] | Lets assume you are not confusing Google and Chrome.
Google application passwords are stored in your KeyChain, for things like Gmail, Calendar, Google drive ect..
Chrome passwords are stored on your HD at
`~/Library/Application Support/Google/Chrome/Default/databases` in special format. (SQL)
However Chrome is a browser and its passwords for diverse websites is not stored in the KeyChain. |
33,099,133 | When I am run my application in android studio error. I am new in android developing.
My Logtag is here:
```
Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:assembleDebug]
Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
> Could not find com.android.support:recyclerview-v7:.
Searched in the following locations:
https://jcenter.bintray.com/com/android/support/recyclerview-v7//recyclerview-v7-.pom
https://jcenter.bintray.com/com/android/support/recyclerview-v7//recyclerview-v7-.jar
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.pom
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.jar
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.pom
file:/C:/Users/ANDROID/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/recyclerview-v7//recyclerview-v7-.jar
Required by:
ShoppingMazza:app:unspecified
Information:BUILD FAILED
Information:Total time: 4.964 secs
Information:1 error
Information:0 warnings
Information:See complete output in console
```
My `build.gradle`:
```
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.catalyst.android.shoppingmazza"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile 'com.android.support:recyclerview-v7:'
}
``` | 2015/10/13 | [
"https://Stackoverflow.com/questions/33099133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5064636/"
] | **Error:**
>
> Error:A problem occurred configuring project ':app'. Could not
> resolve all dependencies for configuration ':app:\_debugCompile'.
>
> Could not find com.android.support:recyclerview-v7:.
>
>
>
From error i can say you'll have to add the following gradle dependency :
```
compile 'com.android.support:recyclerview-v7:+'
```
**EDIT:**
>
> Error:Execution failed for task ':app:dexDebug'. >
> com.android.ide.common.process.ProcessException:
> org.gradle.process.internal.ExecException: Process 'command
> 'C:\Program Files\Java\jdk1.8.0\_51\bin\java.exe'' finished with
> non-zero exit value 1
>
>
>
For this error i think you are compiling `JAR` library twice. You are using
```
compile fileTree(dir: 'libs', include: ['*.jar'])
```
in `build.gradle` file so it will compile all library that has jar extension on libs folder, so You can remove this lines:
```
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
```
If issue still exists then issue is quite possibly due to exceeding the 65K methods dex limit imposed by Android. This problem can be solved either by cleaning the project, and removing some unused libraries and methods from dependencies in `build.gradle`, OR by adding `multidex` support.
```
defaultConfig {
// Enabling multidex support.
multiDexEnabled true
}
``` |
68,682,825 | I am using last version of ActiveMQ Artemis.
My use case is pretty simple. The broker sends a lot of messages to consumer - a single queue. I have 2 consumers per queue. Consumers are set to use default prefetch size of messages (1000).
Is there a way to monitor how many messages are pre-fetch and processed from each consumer? | 2021/08/06 | [
"https://Stackoverflow.com/questions/68682825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4173038/"
] | There are several ways you can go about "shuffling" an array. I chose the Fisher-Yates method in an experimental "war" card game.
<https://github.com/scottm85/war/blob/master/src/Game/Deck.js#L80>
```
shuffle()
{
/* Use a Fisher-Yates shuffle...If provides a much more reliable shuffle than using variations of a sort method https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */
let cards = this.cards;
for (let i = cards.length - 1; i > 0; i--)
{
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[cards[i], cards[j]] = [cards[j], cards[i]];
}
this.cards = cards;
console.log("----------------- Deck Shuffled -----------------");
}
```
<https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle>
Granted my provided example is slightly different than your needs as I was doing this in react, had a Deck array built out, and wasn't using JS for direct DOM manipulation. In theory though, you could modify this to work with your method. Something like this:
```
function shuffleCards
{
let cards = document.querySelectorAll('.card');
let cardsArray = Array.from(cards);
for (let i = cardsArray.length - 1; i > 0; i--)
{
let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
[cardsArray[i], cardsArray[j]] = [cardsArray[j], cardsArray[i]];
cards[i].remove();
}
cardsArray.forEach(t => document.body.appendChild(t));
}
``` |
25,906,182 | I am using Eclipse Indigo (version 3.7) for my Plug in development. I have created a plug-in and added Jersey archive jars in my Build Path . When i try to debug or run the application I am getting......
```
org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.NoClassDefFoundError: com/sun/jersey/api/client/Client)
at org.eclipse.swt.SWT.error(SWT.java:4282)
at org.eclipse.swt.SWT.error(SWT.java:4197)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:138)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4140)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3757)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.block(ModalContext.java:173)
at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:388)
at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:1029)
at com.cts.adpart.testmanagement.jira.configwizard.JiraConnectionPage.connect(JiraConnectionPage.java:256)
at com.cts.adpart.testmanagement.jira.configwizard.JiraConnectionPage.access$0(JiraConnectionPage.java:249)
at com.cts.adpart.testmanagement.jira.configwizard.JiraConnectionPage$1.widgetSelected(JiraConnectionPage.java:142)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:240)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4165)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3754)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
at org.eclipse.jface.window.Window.open(Window.java:801)
at com.cts.adpart.ui.configuration.pages.management.ManagementConfigurationBlock.showAddConfigurationWizard(ManagementConfigurationBlock.java:171)
at com.cts.adpart.ui.configuration.pages.management.ManagementConfigurationBlock.access$1(ManagementConfigurationBlock.java:153)
at com.cts.adpart.ui.configuration.pages.management.ManagementConfigurationBlock$2.linkActivated(ManagementConfigurationBlock.java:133)
at org.eclipse.ui.forms.widgets.AbstractHyperlink.handleActivate(AbstractHyperlink.java:233)
at org.eclipse.ui.forms.widgets.AbstractHyperlink.handleMouseUp(AbstractHyperlink.java:327)
at org.eclipse.ui.forms.widgets.AbstractHyperlink.access$2(AbstractHyperlink.java:311)
at org.eclipse.ui.forms.widgets.AbstractHyperlink$4.handleEvent(AbstractHyperlink.java:125)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4165)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3754)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2701)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2665)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at com.cts.adpart.standalone.Application.start(Application.java:94)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
at org.eclipse.equinox.launcher.Main.main(Main.java:1386)
Caused by: java.lang.NoClassDefFoundError: com/sun/jersey/api/client/Client
at com.cts.adpart.testmanagement.jira.api.JiraConnection.connect(JiraConnection.java:34)
at com.cts.adpart.testmanagement.jira.configwizard.JiraConnectionPage$3$1.run(JiraConnectionPage.java:268)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
... 47 more
Caused by: java.lang.ClassNotFoundException: com.sun.jersey.api.client.Client
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:513)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:429)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:417)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 51 more
```
Exception . I have no idea on how to resolve this issue. Any suggestion ? | 2014/09/18 | [
"https://Stackoverflow.com/questions/25906182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3926459/"
] | **EDIT**
I've just noticed (after adding my answer) an error in your constructor - it's name is `_construct` with single underscore. It should be with double underscore `__construct` so correct the name and make sure if error is still present and if it is, read the rest of the answer.
**Rest of the answer**
The first thing you need to run `View::share` before `View::make` otherwise you will get this error.
So if you use somewhere:
```
$wait = 'available';
View::share('wait', $wait);
return View::make('myview');
```
In your template you can simply use:
```
{{ $wait }}
```
and you will get output `available` for your variable and not any notice.
But you mentioned you put `View::share` in a constructor. Is it in your controller class or in parent class? If in parent, you should then execute it using `parent::__construct();` - you need to make sure that this constructor is launched at all, so you can even add `echo 'I'm running'; exit;` in this constructor to make sure it has been launched at all. |
77,767 | In a cavity, the standing wave will constructively interfere with itself, so its energy gets higher while the oscillator is still vibrating. Since the vibration time is not a constant value, and sometimes the wall of the cavity absorbs some of the wave energy, the energy of a standing EM wave is probabilistic and follows Maxwell-Boltzmann distribution. Am I correct in the statement above?
---
Actually I'm thinking about the black-body radiation. To calculate the energy density in a cavity which is heated up to $T$, we assume that the cavity is a cube, and only standing wave can exist in it(Why?). First we need to calculate how many kinds of standing waves(how many different wave vectors) for one frequency $f$. This can be done with some mathematical tricks. And then we have to determine the energy of each wave $\overline{E(f)}$. And my question is, actually, why does this overline come from? Why is it an average energy, instead of a constant value? | 2013/09/18 | [
"https://physics.stackexchange.com/questions/77767",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/24610/"
] | Conservation of energy follows directly from Maxwell's equations, so if you convince yourself that energy isn't conserved when EM waves interfere, you've made a mistake, and you need to go back and figure out what your mistake was.
>
> In a cavity, the standing wave will constructively interfere with itself, [...]
>
>
>
Not true. If you work out the right-hand relationships for two EM plane waves traveling in opposite directions, you'll find that if the E fields are in phase, the B fields have opposite phases, and vice versa. |
7,660 | I've started Wing Chun few days before. Everything seems to be nice, but I've seen some videos on internet, they say that Wing Chun can't handle Boxers or Wrestlers.
What are the comparisons between Wing Chun and boxing/wrestling that would lead someone to make this claim? Are there weaknesses that can be exploited? | 2017/07/16 | [
"https://martialarts.stackexchange.com/questions/7660",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/-1/"
] | As always, you can't compare style A with style B and say either one is better. It's not because you're a boxer, you immediately win agains a wing chun practitioner. It all depends on how good both fighters are, how much experience they got fighting opponents of different styles, the competition's rules (eg. if you pit a judoka vs. a taekwondo, and rules state no throws or groundwork, chances are the taekwondo will win. If the rules state throws and groundwork are allowed, but kicks to the head aren't, the tables will turn), and even as much as how good/bad a day someone's been having and even sheer luck (Remember, one lucky hit can be all it takes)
Of course, each style has its strengths and weaknesses. Once you understand your system well enough (and your own body, for that matter), you can start playing with the strengths and the weaknesses. You can get creative with them. That's an important part of the experience part mentioned above.
But yeah, in short: You can't just compare style A with style B. A kid who did 3 weeks boxing classes won't win against Ip Man. A kid who did Wing Chun for 3 weeks won't win against Mohammed Ali. |
12,011,559 | I have the following html that is bound to an object containing id and status. I want to translate status values into a specific color (hence the converter function convertStatus). I can see the converter work on the first binding, but if I change status in the binding list I do not see any UI update nor do I see convertStatus being subsequently called. My other issue is trying to bind the id property of the first span does not seem to work as expected (perhaps it is not possible to set this value via binding...)
HTML:
```
<span data-win-bind="id: id">person</span>
<span data-win-bind="textContent: status converter.convertStatus"></span>
```
Javascript (I have tried using to modify the status value):
>
> // persons === WinJS.Binding.List
>
> // updateStatus is a function that is called as a result of status changing in the system
>
>
>
```
function updateStatus(data) {
persons.forEach(function(value, index, array) {
if(value.id === data.id) {
value.status = data.status;
persons.notifyMutated(index);
}
}, this);
}
```
I have seen notifyMutated(index) work for values that are not using a converter.
**Updating with github project**
[Public repo for sample (not-working)](https://github.com/ShelbyZ/winjs-data-binding) - this is a really basic app that has a listview with a set of default data and a function that is executed when the item is clicked. The function attempts to randomize one of the bound fields of the item and call notifyMutated(...) on the list to trigger a visual updated. Even with defining the WinJS.Binding.List({ binding: true }); I do not see updates unless I force it via notifyReload(), which produces a reload-flicker on the listview element. | 2012/08/17 | [
"https://Stackoverflow.com/questions/12011559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665106/"
] | To answer your two questions:
1) Why can't I set id through binding?
This is deliberately prevented. The WinJS binding system uses the ID to track the element that it's binding to (to avoid leaking DOM elements through dangling bindings). As such, it has to be able to control the id for bound templates.
2) Why isn't the converter firing more than once?
The Binding.List will tell the listview about changes in the contents of the list (items added, removed, or moved around) but it's the responsibility of the individual items to notify the listview about changes in their contents.
You need to have a data object that's bindable. There are a couple of options:
* Call `WinJS.Binding.as` on the elements as you add them to the collection
* Turn on binding mode on the Binding.List
The latter is probably easier. Basically, when you create your Binding.List, do this:
```
var list = new WinJS.Binding.List({binding: true});
```
That way the List will call binding.as on everything in the list, and things should start updating. |
46,586,267 | Context
-------
For quite a lot of our CentOS servers I would like to install some monitoring software, the software is based on the CentOS version, I want to check the release version and install software based on that.
Issue
-----
It seems that the if statements are run successfully without errors while the results never should be true for both or all three if statements. I've looked into the if commands and the tests, it seems that I should use double brackets and single = symbol in bash. I believe that I'm doing something really simple wrong, but I just can't find it.
Code
----
```
#!/bin/bash
versionknown=false
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version"="CentOS release 6.9 (Final)" ]] ; then
echo "Same versions as expected"
versionknown=true
#run commands for this specific version
fi
if [[ "$version"="CentOS Linux release 7.3.1611 (Core)" ]] ; then
echo "Same versions as expected v2"
versionknown=true
#run commands for this specific version
fi
if [[ "$versionknown"=false ]] ; then
echo "Different version detected than known:"
echo $version
echo "Aborted"
fi
echo $versionknown
```
Results
-------
```
Same versions as expected
Same versions as expected v2
Different version detected than known:
CentOS Linux release 7.3.1611 (Core)
Aborted
true
```
Update
======
After getting some responses I've changed my code, adding spaces around the equal signs(=). Still doesn't work as intended since the comparison should return true on the second if statement which it doesn't.
Code #2
-------
```
#!/bin/bash
versionknown=false
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version" = "CentOS release 6.9 (Final)" ]] ; then
echo "Same versions as expected"
versionknown=true
#run script for this specific version
fi
if [[ "$version" = "CentOS Linux release 7.3.1611 (Core)" ]] ; then
echo "Same versions as expected v2"
versionknown=true
#run script for this specific version
fi
if [[ "$versionknown" = false ]] ; then
echo "Different version detected than known:"
echo $version
echo "Aborted"
fi
echo $versionknown
```
Results #2
----------
```
Different version detected than known:
CentOS Linux release 7.3.1611 (Core)
Aborted
false
```
Update
======
`declare -p version` learned me that `/etc/centos-release` has a space added to the end of the script file, I believe that on CentOS release 6.9 (Final) that wasn't the case. Adding the space in the string, or all together making use of my known\_version variables and adding the space solves the issues, script now works as intended. | 2017/10/05 | [
"https://Stackoverflow.com/questions/46586267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8726241/"
] | You need whitespace around the `=` sign; without it, the shell treats the "expression" as a single word, not a comparison of two words for equality.
```
[[ "$version" = "CentOS release 6.9 (Final)" ]]
```
`[[ a=b ]]` is equivalent to `[[ -n a=b ]]`, i.e., you are simply testing if the single word is a non-empty string.
Whether you use `=` or `==` inside `[[ ... ]]` is a matter of style; `bash` supports both.
I would avoid using a `versionknown` variable altogether, and write the code like this:
```
version=$(</etc/centos-release)
known_version1="CentOS release 6.9 (Final)"
known_version2="CentOS Linux release 7.3.1611 (Core)"
if [[ "$version" = "$known_version1" ]] ; then
echo "Same versions as expected"
#run commands for this specific version
elif [[ "$version" = "$known_version2" ]] ; then
echo "Same versions as expected v2"
#run commands for this specific version
else
echo "Different version detected than known:"
echo "$version"
echo "Aborted"
fi
```
or a `case` statement
```
case $version in
"$known_version1")
echo "Same versions as expected"
# ...
;;
"$known_version2")
echo "Same versions as expected v2"
# ...
;;
*)
echo "Different version detected than known:"
echo "$version"
echo "Aborted"
esac
``` |
539,083 | I am trying to build a small circuit using an ESP8288-12E, 4 5V relays and a 74HC595 shift register as the main components. To power the whole circuit I am using a Hi Link HLK 5M05 5V/5W switch power supply module.
Here is how I planned the whole circuit:
[![enter image description here](https://i.stack.imgur.com/iTD0j.jpg)](https://i.stack.imgur.com/iTD0j.jpg)
If it is difficult to see in this image then I can provide PDF as well.
I took this AMS1117-3.3 to get 3.3V from my 5V power supply. Instead of 3.3C, I am getting 4.2V on my PCB. I am not sure why this is happening.
I am attaching my EasyEDA file for the PCB design also.
[![enter image description here](https://i.stack.imgur.com/ogBMW.png)](https://i.stack.imgur.com/ogBMW.png)
One more issue I am facing is that when i take my multi-meter probes near to the circuit the relays are triggering automatically. I didn't connect the ESP8266-12E on the PCB yet, as I am not getting proper voltage on ESP8266-12E VCC pin.
Any suggestions, why this issue might be happening? Any suggestions will be helpful!
If someone wants to have an EasyEDA access I can provide for this project so can visualize the same issue more easily.
<https://oshwlab.com/nehul.splendit/shift-resistor-sn74hc595-with-4-channel-relay>
Here is the link of the same project. | 2020/12/25 | [
"https://electronics.stackexchange.com/questions/539083",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/212459/"
] | If there is no load at all on the 3V3 regulator, it has no minimum required load so it won't output 3V3.
When there is no ESP connected, there is nothing connected on HC595 input pins, so they are floating. The input impedance is so high that taking multimeter probes nearby will cause the HC595 to see activity on input pins and it will randomly load in a data pattern to drive the relays to they will chatter on and off.
Also do note that inputs of HC595 fed with 5V is not compatible with 3.3V outputs of ESP. Either change the HC type to something else that can work with 3.3V input voltages, or change the supply of HC595 to 3V3.
Edit: Oh dear I just realized the supply that converts mains voltage to 5V is not external but onboard. The PCB layout is not safe for mains voltage at all. Not the mains input to supply, and not the relay contact wiring either. Please don't connect this to mains as it is unsafe. |
66,223,067 | Is it possible to expose all the Spring metrics in an rest endpoint?
In our environment Micrometer cannot forward directly the metrics to our monitoring system, then my idea was to have all the metrics exposed in a rest endpoint (or on a file, json format but the endpoint is preferable) and then having a script to fetch all the metrics at once, manipulate the payload and forward the metrics to our customized monitoring api.
If micrometer is not the right choice, what is it?
**EDIT**
I tried to use the actuator/prometheus endpoint. I can see the endpoint but as soon as I hit the endpoint, it hang and does not return anything:
I am using spring boot 2.2.2 and I added this dependency
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.3.1</version>
</dependency>
```
application.yml
```
management:
endpoints:
web:
exposure:
include: health, metrics, prometheus
``` | 2021/02/16 | [
"https://Stackoverflow.com/questions/66223067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/980515/"
] | You may use this redirect rule in your site root .htaccess:
```sh
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www\.)?website\.com$ [NC]
RewriteRule ^reservation/?$ https://test.com/test/page [L,NC,R=301]
```
Query string and fragment i.e. part after `#` will automatically be forwarded to the new URL. |
42,347,969 | how to block a jsp page
(i want is ,when I click the links to redirect each pages I want to block some specific pages for specific users)
I create an java script function to retrieve the jsp pages of each users(pages that user can access).But I have no idea to block other pages for the same user) | 2017/02/20 | [
"https://Stackoverflow.com/questions/42347969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5983136/"
] | use js `document.getElementById("id name of link").style.display = 'none';` to remove the link from page and use **'block'** instead of **'none'** for showing the link. |
44,124,940 | How would I go about dividing arrays into quarters?
For example, I want to ask the user to enter say 12 values. Then, divide them into 4 quarters and add the values in each quarter. I figured how to add all of them up, but I'm stuck on how to add them separately in groups.
Thank You.
```
import java.util.Scanner;
import java.util.stream.*;
public class SalesData {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] salesData = new int[12];
int monthNumber=1;
for (int i = 0; i < 12; i++) {
System.out.println("Please enter the data for month "+monthNumber);
salesData[i] = keyboard.nextInt();
int newNumber=monthNumber++;
}
System.out.println("The first quarter total is ");
System.out.println("The second quarter total is ");
System.out.println("The third quarter total is ");
System.out.println("The fourth quarter total is ");
double sum = IntStream.of(salesData).sum();
System.out.println("The Annual Sales Total is "+sum);
}//end main
}`
``` | 2017/05/23 | [
"https://Stackoverflow.com/questions/44124940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8051072/"
] | ```
String[] quarters = {"first", "second", "third", "fourth"};
for (int i = 0; i < 12; i += 3)
System.out.printf("The %s quarter total is %d%n",
quarters[i / 3],
Arrays.stream(salesData, i, i + 3).sum());
``` |
28,277,685 | I have webpages with URL <http://siteurl/directory/onemore/>$fileID.php
I am trying to extract just the $fileID and after that use
```
$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
$hits = $hits + 1;
$query = $mysqli->query("UPDATE tablename SET HITS = $hits WHERE ID = $fileID");
echo 'Total hits on page'.$hits.'';
```
I can't figure out how to get just the $fileID part and wanted to ask is the rest of my procedure correct?
**EDIT**
With the code above hits get stuck at one. I was thinking that after each page refresh they will update to +1. | 2015/02/02 | [
"https://Stackoverflow.com/questions/28277685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4516574/"
] | You can determine the $fileId like this:
```
/* $_SERVER['PHP_SELF'] results to e.g. '/directory/onemore/5.php' */
/* basename(...) results to e.g. '5.php' */
$fileName = basename($_SERVER['PHP_SELF']);
/* take the text before the last occurrence of '.' */
$fileID = substr($fileName, 0, strrpos($fileName, '.'));
$query = $mysqli->query("UPDATE tablename SET HITS = HITS + 1 WHERE ID = $fileID");
$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
echo 'Total hits on page'.$hits.'';
``` |
22,345,614 | How can this be possible:
```
var string1 = "", string2 = "";
//comparing the charCode
console.log(string1.charCodeAt(0) === string2.charCodeAt(0)); //true
//comparing the character
console.log(string1 === string2.substring(0,1)); //false
//This is giving me a headache.
```
<http://jsfiddle.net/DerekL/B9Xdk/>
If their char codes are the same in both strings, by comparing the character itself should return `true`. It is true when I put in `a` and `ab`. But when I put in these strings, it simply breaks.
Some said that it might be the encoding that is causing the problem. But since it works perfectly fine when there's only one character in the string literal, I assume encoding has nothing to do with it.
(This question addresses the core problem in my previous questions. Don't worry I deleted them already.) | 2014/03/12 | [
"https://Stackoverflow.com/questions/22345614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283863/"
] | In JavaScript, strings are treated by characters instead of bytes, but only if they can be expressed in 16-bit code points.
A majority of the characters will cause no issues, but in this case they don't "fit" and so they occupy 2 characters as far as JavaScript is concerned.
In this case you need to do:
```
string2.substring(0, 2) // ""
```
For more information on Unicode quirkiness, see [UTF-8 Everywhere](http://utf8everywhere.org/). |
9,743,846 | I have to do some processing on a file loaded by the user. This process can take a long time based on the number of pages within the file. I am planning on using jQuery UIs progressbar and telling the user how many pages have been processed. However, my progress check does not return until the first ajax call is complete. Both calls complete properly are connecting to the corresponding web methods.
I researched this a little bit already, and I found [this answer](https://stackoverflow.com/a/4863630/2486) to another question which pretty much stated that if both calls use the Session they wont process concurrently. I only use the Session in one of the calls though.
What am I missing?
This is the initial call that starts the processing of the file. I set the UpdateProgressBar to run a second after the processing of the file starts.
```
setTimeout("UpdateProgressBar();", 1000);
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Do stuff when file is finished processing
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
This is the UpdateProgressBar function:
```
function UpdateProgressBar() {
$.ajax({
type: "POST",
async: true,
data: // my params go here
url: // path to web method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var totalPages = parseInt($('[id$=lbl_PageCount]').text());
var pagesProcessed = result.d;
var percentProcessed = pagesProcessed / totalPages;
$('#div_ProgressBar').progressbar("value", percentProcessed);
if (pagesProcessed < totalPages)
setTimeout("UpdateProgressBar();", 800);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown != null)
alert(textStatus + " : " + errorThrown);
}
});
```
**Edit**:
This is the WebMethod called by UpdateProgressBar. The other WebMethod does use Session, but as you can see this one does not. They both access a dll, however, I tried testing without using the dll for the update and it did not make a difference.
```
[WebMethod]
public static int CheckPDFProcessingProgress(// params go here)
{
int pagesProcessed = 1;
try
{
OrderService _orderService = new OrderService();
pagesProcessed = _orderService.GetMailingPDFPagesProcessedProgress(PersonID);
}
catch (Exception ex)
{
// log error
}
return pagesProcessed;
}
``` | 2012/03/16 | [
"https://Stackoverflow.com/questions/9743846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | You can do it in a single thread.
Suppose you have a script that prints lines at random times:
```
#!/usr/bin/env python
#file: child.py
import os
import random
import sys
import time
for i in range(10):
print("%2d %s %s" % (int(sys.argv[1]), os.getpid(), i))
sys.stdout.flush()
time.sleep(random.random())
```
And you'd like to collect the output as soon as it becomes available, you could use [`select`](http://docs.python.org/dev/library/select#select.select) on POSIX systems as [@zigg suggested](https://stackoverflow.com/questions/9743838/python-subprocess-in-parallel/9746401#comment12393687_9743899):
```
#!/usr/bin/env python
from __future__ import print_function
from select import select
from subprocess import Popen, PIPE
# start several subprocesses
processes = [Popen(['./child.py', str(i)], stdout=PIPE,
bufsize=1, close_fds=True,
universal_newlines=True)
for i in range(5)]
# read output
timeout = 0.1 # seconds
while processes:
# remove finished processes from the list (O(N**2))
for p in processes[:]:
if p.poll() is not None: # process ended
print(p.stdout.read(), end='') # read the rest
p.stdout.close()
processes.remove(p)
# wait until there is something to read
rlist = select([p.stdout for p in processes], [],[], timeout)[0]
# read a line from each process that has output ready
for f in rlist:
print(f.readline(), end='') #NOTE: it can block
```
A more portable solution (that should work on Windows, Linux, OSX) can use reader threads for each process, see [Non-blocking read on a subprocess.PIPE in python](https://stackoverflow.com/q/375427/4279).
Here's [`os.pipe()`](http://docs.python.org/2/library/os#os.pipe)-based solution that works on Unix and Windows:
```
#!/usr/bin/env python
from __future__ import print_function
import io
import os
import sys
from subprocess import Popen
ON_POSIX = 'posix' in sys.builtin_module_names
# create a pipe to get data
input_fd, output_fd = os.pipe()
# start several subprocesses
processes = [Popen([sys.executable, 'child.py', str(i)], stdout=output_fd,
close_fds=ON_POSIX) # close input_fd in children
for i in range(5)]
os.close(output_fd) # close unused end of the pipe
# read output line by line as soon as it is available
with io.open(input_fd, 'r', buffering=1) as file:
for line in file:
print(line, end='')
#
for p in processes:
p.wait()
``` |
22,312,325 | I have a set of 8 buttons in a horizontal row. How can i make them like the buttons in [www.dotacinema.com](http://www.dotacinema.com) where when you smaller the window the buttons go together too (or zoom in, the buttons are still visible)
Thanks
EDIT:
```
height: 38px;
float: left;
min-width: 60px;
max-width: 140px;
display: inline-block;
width: 12.5%;
background-image: url(button.jpg);
background-size: 100%;
color: white;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
color: #d0d0d0;
border: outset #555 1.5px;
cursor: pointer;
text-align: center;
font-size: 16px;
```
does not make the buttons squish together for some reason. Pls help. | 2014/03/10 | [
"https://Stackoverflow.com/questions/22312325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2881151/"
] | Make the width of the buttons a percentage of the page, and then set a minimum button width using `min-width: ;` to stop them getting any smaller than readable.
<http://jsfiddle.net/s2VvX/3/> |
65,229,771 | After working with the tensorflow's example tutorial on colab: Basic regression: Predict fuel efficiency, which can be found here: <https://www.tensorflow.org/tutorials/keras/regression>.
I've been trying to run this example on jupyter notebook via anaconda in order to be able to run it offline too.
The code that one can find on the link works fine on google colab, but when I try to run it on jupyter notebook I get a vector of nan's.
1. A run on google colab yields:
[Running the example on google colab](https://i.stack.imgur.com/wvafS.png)
2. A run on jupyter yields:
[Running the example on jupyter lab](https://i.stack.imgur.com/BvRkU.png)
**The code for building the sequential model: [where the problem might come from]**
```
horsepower_model = tf.keras.Sequential([
horsepower_normalizer,
layers.Dense(units=1)
])
horsepower_model.summary()
```
**The rest of the code can be found in this link that I have attached above:**
<https://www.tensorflow.org/tutorials/keras/regression>
**What the model has to do:**
This model takes 2 arrays from a dataset: MPG and Horsepower, and is about to use single-variable linear regression in order to predict MPG from Horsepower.
Therefore, the model is introduce a Dense layer with shape of 1 as one can see from here:
```
layers.Dense(units=1)
```
The output of the model should be the values of the MPG, based on the horsepower values.
Then we will be able to compare it with the values of the real MPG that we've got from the dataset.
Thank you in advance.
**EDIT: I upload my notebook:**
<https://www.udrop.com/Jk3/Horsepower.ipynb> | 2020/12/10 | [
"https://Stackoverflow.com/questions/65229771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14799022/"
] | I see you are using different models in them.
In **Colab** you have used model having only **5** parameters
whereas in **Notebook** you are using a dense model having **944** parameters.
**Try running the model with less parameter on notebook first**
or
Try running the same model on both.(Maybe the complex model was not trained completely.)
**EDIT 1:**
I have created a jupyter notebook and tried the code.
In my system it is working fine, try running this jupyter notebook in your system. [Jupyter Notebook](https://drive.google.com/file/d/1dDiJZ7LAsR5x3bz1Y-7EetTwWX2mXEjG/view?usp=sharing)
. If it works then maybe there is some syntax error in your code.
**EDIT 2:**
Update tensorflow:
```
pip install --ignore-installed --upgrade tensorflow
```
use this or any other command that works on your version. |
38,408,974 | I'm new in swift-ios. I'm studying [this](https://www.ralfebert.de/tutorials/ios-swift-uitableviewcontroller/)
when I'm trying to create cocoa file,
>
> import cocoa
>
>
>
is giving error.
I've searched in google and found cocoa class not work in ios-swift. it works in osx.
So I'm not getting what'll I do now. Any help appreciated. | 2016/07/16 | [
"https://Stackoverflow.com/questions/38408974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2007490/"
] | Cocoa is a framework for macOS. However, CocoaTouch is an umbrella module for iOS. To import the main module dependency for an iOS app, you use
```
import Foundation
```
And to import the main UI module for an iOS app, you use
```
import UIKit
``` |
50,621,187 | I need to click a button whose xpath is "**//input[contains(@value,'Export to Excel')]**" through **Execute Javascript** keyword. I don't know how to use it.
Can anyone help me out!!! | 2018/05/31 | [
"https://Stackoverflow.com/questions/50621187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9667509/"
] | You can write it as below
```
Execute JavaScript document.evaluate("ur xpath",document.body,null,9,null).singleNodeValue.click();
``` |
1,038,189 | which one of the 2 have the best performance?
In javascript I was heard douglas crockford say that you shouldn't use str += if you are concatenating a large string but use array.push instead.
I've seen lots of code where developers use $str .= to concatenate a large string in PHP as well, but since "everything" in PHP is based on arrays (try dumping an object), my thought was that the same rule applies for PHP.
Can anyone confirm this? | 2009/06/24 | [
"https://Stackoverflow.com/questions/1038189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117278/"
] | Strings are mutable in PHP so using .= does not have the same affect in php as using += in javascript. That is, you will not not end up with two different strings every time you use the operator.
See:
[php String Concatenation, Performance](https://stackoverflow.com/questions/124067/php-string-concatenation-performance)
[Are php strings immutable?](https://stackoverflow.com/questions/496669/are-php-strings-immutable) |
61,339,388 | I have two tables t1 & t2. In t1, there are 1641787 records. In t2, there are 33176007 records. I want to take two columns from t2 and keep everything of t1 using a left join. When I use left join with t1 to t2, I got more records than t1. I would like to get a similar number of records as t1 after joining. Please give me a suggestion. There are many to many relationships between the tables. Here is my code:
```
SELECT t1.*, t2.City
FROM t1 LEFT JOIN t2 ON t1.ID = t2.ID;
``` | 2020/04/21 | [
"https://Stackoverflow.com/questions/61339388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5846329/"
] | You need to aggregate `t2` *before* joining:
```
SELECT t1.*, t2.City
FROM t1 LEFT JOIN
(SELECT t2.ID, ANY_VALUE(t2.City) as City
FROM t2
GROUP BY t2.ID)
) t2
ON t1.ID = t2.ID;
``` |
4,012,120 | I am trying to build a simple graphics application in WPF C#. The purpose is to draw 10000\*10000 rectangles of size 4 pixels each.
I have modified the OnRender method of the canvas to draw the rectangles. Drawings are performed for smaller number of rectangles (say 50\*50 or 100\*100 rectangles of 4 pixel each) but it is slowing down as I am increasing the no. of rectangles.
Following is my code:
```
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
FillCells(dc);
if (_ShowGrids)
{
DrawGrid(dc); // draw grid lines
}
}
void FillCells(DrawingContext dc)
{
int cellSize=4;
for (int i = 0; i < MaxRow; i++)
{
for (int j = 0; j < MaxColumn; j++)
{
dc.DrawRectangle(GetRectBrush(i,j), GetRectPen(i,j), new Rect(j * cellSize , i * cellSize , cellSize - 1, cellSize - 1));
}
}
}
```
The above code takes more than a minute to draw 1000\*1000 rectangles.
Is there any method to make this process faster? Is there any other thing I can use in place of this?
Thanks. | 2010/10/25 | [
"https://Stackoverflow.com/questions/4012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461537/"
] | >
> The purpose is to draw 10000\*10000
> rectangles of size 4 pixels each.
>
>
>
Do NOT draw them. That simple. This would be 40k to 40k pixels.
Most will not be visible. So they must not bee drawn. Basically only draw those that are visible in the canvas. When resizing or scrolling you repaint anyway, then do the same - only draw those that are visible.
Virtualization is the key to performance here. Take things out of the drawing loop as early as possible. Stuff not visible per definition does not need to be drawn at all.
Next alternative would be not to use a canvas. Try a bitmap. Prepare it on a separate thread, then draw this one at once. |
2,332,712 | Let $M$ , $N$, and $P$ be smooth manifolds with or without boundary.
Every constant map $c: M\rightarrow N$ is smooth.
**Proof:** Let $c: M \rightarrow N$ be a constant map. Let $p \in M$. Smoothness of $c$ means there are charts $(U,\phi)$ of $p$ and $(V,\psi)$ of $c(p)$ such that $c(U) \subseteq V$ and $\psi \circ c \ \circ \phi^{-1} $ is smooth. Since $c$ is a constant map we know that $c(p)=y$ for every $p \in M$.
This is as far as I got with the proof. I'm a bit lost on how to finish the proof using the fact that c is a constant map to show that $c: M \rightarrow N$ is smooth.
I'd appreciate hints or advice instead of a full solution to the problem that way it doesn't spoil the problem for me.
I'm using Lee's Introduction to Smooth Manifolds. | 2017/06/22 | [
"https://math.stackexchange.com/questions/2332712",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/203845/"
] | We have chosen some chart $\phi \colon U \rightarrow \phi(U) \subseteq \mathbb{R}^n$ on $M$ and a chart $\psi \colon V \rightarrow \psi(V) \subseteq \mathbb{R}^m$ on $N$. We want to show that $\psi \circ c \circ \phi^{-1}$ is smooth given $c$ is constant.
Hints: 1. What is the domain and codomain of the map $\psi \circ c \circ \phi^{-1}$
2. Is a constant map $k \colon \mathbb{R}^n \rightarrow \mathbb{R}^m$ smooth? |
446,618 | ![enter image description here](https://i.stack.imgur.com/0CH4T.jpg)
This was my grandfather’s and have no idea what it is only that it is some piece of physics equipment!
The main black cylinder doesn’t seem like it wants to rotate but not sure if it should? | 2018/12/11 | [
"https://physics.stackexchange.com/questions/446618",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/37250/"
] | It looks like an [induction coil](https://en.wikipedia.org/wiki/Induction_coil) with the make and break device at the bottom and a switch right at the bottom. If you connect it up to an accumulator, be very, very careful as the output between the two balls, when separate, could be lethal. Also the electrical insulation elsewhere may be poor and you might get a shock just by touching the switch.
**Use with very great care** and preferably have somebody who knows about such devices with you. |
35,287 | hello.
I am looking for tensor manipulation software that would allow me:
* declare indices
* declare results of contraction (or simplification rules)
* allow algebraic simplifications and expansion
* index renaming
So far I have found Maxima to satisfy my requirement more or less, <http://maxima.sourceforge.net/docs/manual/en/maxima_27.html>
one last thing I also want, (but not necessarily require), is interface with python.
In principle I could use sage to interface with maxima.
Is there some other Cas that has package with similar tensor
manipulation properties?
from links given below, I also found this, <http://cadabra.phi-sci.com/>, which looks geared specifically for tensor manipulations. | 2010/08/11 | [
"https://mathoverflow.net/questions/35287",
"https://mathoverflow.net",
"https://mathoverflow.net/users/5925/"
] | I think that everything in your list (except the Python interface) can be found in Kasper Peeters' [Cadabra](http://cadabra.phi-sci.com/).
As for a Python interface, there are two directions:
1. [It is planned](http://cadabra.phi-sci.com/ideas.html) to add an interface layer to Cadabra to either Maxima or SymPy - in the latter case you'd probably get access to Python.
2. [There is talk](http://groups.google.com.au/group/sage-devel/browse_thread/thread/83182fbfc62cd0f6/3623f8d9d819c01c?q=Cadabra+interface#3623f8d9d819c01c) of adding a Cadabra interface to sage using the standard sage.interfaces.expect class.
As an aside some of the index algorithms come from José Martin-Garcia's [xPerm](http://metric.iem.csic.es/Martin-Garcia/xAct/index.html), a Mathematica package. xPerm seems to be more suited to GR while Cadabra is focused on QFT.
[FORM](http://www.nikhef.nl/~form/) (the successor of Schoonschip) is also very powerful and used in a lot of high energy physics computing. |
46,934,653 | we are facing an issue in production that the 'Content-Length' header is not being sent, even if we hard-code it in the headers properties, so we are receiving back from the server the 411 Length Required error.
We are using:
* Axios 0.16.2
* NodeJS 6.10
* Application deployed inside AWS Lambda environment
The code that is causing the issue is the following:
```
let cookieJar;
const postBody = "MyBody=MyBodyContentGoesHere";
const url = "https://my-url.com";
return axios
.post(url,
postBody,
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: 10000,
jar: cookieJar,
withCredentials: true
}
);
```
I wrote an application in .NET and the header is sent properly (without to pass it manually). This .NET application was written just to test, it's not the real application.
Do you have some idea?
I open a issue in the axios github project, but I want to know from you guys some ideas.
Thank you. | 2017/10/25 | [
"https://Stackoverflow.com/questions/46934653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/513808/"
] | You can specify the .py file form which you wish to import in the code itself by adding a statement `sc.addPyFile(Path)`.
The path passed can be either a local file, a file in HDFS (or other Hadoop-supported filesystems), or an HTTP, HTTPS or FTP URI.
Then use `from add_num import add_two_nos` |
30,957,706 | I am trying to modify Javascripts Array type with a method which will push a value to an array only if its is not already present.
Here is my code:
```
// add a method conditionally
Array.prototype.method = function (name, func){
if(!this.prototype[name]){
this.prototype[name] = func;
return this;
}
};
// exclusive push
Array.method('xadd', function(value){
if(this.indexOf(value) === -1){
this.push(value)
};
return this;
});
```
However when I run the code the scratchpad in Firefox returns:
```
/*
Exception: TypeError: Array.method is not a function
@Scratchpad/3:19:1
*/
```
I want a vanilla way of doing this. Not a library as I am writing an open source library. | 2015/06/20 | [
"https://Stackoverflow.com/questions/30957706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1652010/"
] | When you're putting a method on `Array.prototype` the method will be available on the instances of Array.
```
// Add the custom method
Array.prototype.method = function() {
console.log('XXX');
}
var foo = [];
// prints XXX
foo.method();
``` |
18,380,463 | Recently I'm working on a new project and `UTF-8` is a must. I don't know why I'm facing this, but it is really strange to me. I really tried everything I knew, but the problem remains.
I'm sending a JSON string to my servlet and here is the servlet part:
```
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
if (action.equals("startProcess")) {
final String data = request.getParameter("mainData");
URLDecoder.decode(data, "UTF-8");
System.out.println("DATA \n" + URLDecoder.decode(data, "UTF-8"));
JSONObject jsonObj = new JSONObject();
try {
JSONArray jsonArr = new JSONArray(URLDecoder.decode(data, "UTF-8"));
jsonObj.put("data", jsonArr);
JSONArray array = jsonObj.getJSONArray("data");
System.out.println("insertDtls \n" + jsonObj.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
```
the `System.out.println("insertDtls \n" + jsonObj.toString());` returns:
this result: `DATA
[{"department":"1"},{"stampType":"кÑÑÐ³Ð»Ð°Ñ Ð¿ÐµÑаÑÑ"},{"headCompany":"да"},{"stampReason":"1"},{"textToPrint":"asd"},{"comments":"da"},{"other":"дÑÑгой"}]`
I realy don't know what to do here. I'm sure that I'm missing something really small, but I'm not able to spot it. Is it possible to have this string double encoded somehow? | 2013/08/22 | [
"https://Stackoverflow.com/questions/18380463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1773265/"
] | `String data = request.getParameter("mainData");`
request.getParameter() already decodes mainData parameter. No further decoding is necessary: `URLDecoder.decode(data, "UTF-8")`
If you still want to get raw mainData parameter value use [request.getQueryString()](http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getQueryString%28%29) and then decode it: `URLDecoder.decode(request.getQueryString(), "UTF-8");`
On client side make sure that when sending a GET request all URL parameters are correctly UTF-8 encoded.
Also on server side make sure your GET parameters are UTF-8 decoded. For example to fix it in Tomcat you must configure *URIEncoding* attribute in server.xml:
`<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" ...>` |
42,623 | Every once in a while, my eighth-inch audio jack will slip loose and I'll seemingly lose only the voice part of a track -- leaving somewhat of a "karaoke" version. What I would guess about how audio plugs work suggests that I'd be making this up; however, I've asked and others tell me they've experienced this as well.
What causes this stripped vocals from audio when a 1/8" audio jack is partially unplugged? | 2012/10/02 | [
"https://electronics.stackexchange.com/questions/42623",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/13714/"
] | When the plug starts to slip out of the jack, very often it's the ground contact (sleeve) that breaks its connection first, leaving the two "hot" leads (left and right, tip and ring) still connected.
With the ground open like this, both earpieces still get a signal, but now it's the "difference" signal between the left and right channels; any signal that is in-phase in both channels cancels out.
Recording engineers tend to place the lead vocal signal right in the middle of the stereo image, so that's just one example of an in-phase signal that disappears when you're listening to the difference signal. |
37,590,244 | I am using laravel 5 and having following array:
```
array:3 [▼
0 => 3,
1 => 4,
2 => 5
]
```
Now i wanted to get all values/rows from table say 'X' having id's 3,4,5 | 2016/06/02 | [
"https://Stackoverflow.com/questions/37590244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2305113/"
] | Try this query
```
$array = [ 0 => 3,1 => 4, 2 => 5];
$results = DB::table('x')
->whereIn('id',$array)
->get();
``` |
114,936 | Say every container and the host itself has its own dedicated, external IP. Is it possible to do this without any problems?
And is this really a good plan? Instead of hosting a database per container, hosting a database per host, for all containers to share?
This question is sort of related to this one: <https://unix.stackexchange.com/questions/114786/giving-ovz-containers-their-own-ip> | 2014/02/12 | [
"https://unix.stackexchange.com/questions/114936",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/56196/"
] | I do this exact same thing, I have ~10+ OpenVZ guests and a single instance of MySQL running in one of the 10. This is a good approach if the following things are true:
* All the VM's using this DB won't overload it
* Running multiple individual MySQL instances in their own VMs would be more resource intensive
* All the guest VMs that are talking to the single instance of MySQL can be coordinated to have it (MySQL) down when doing maintenance, backups, etc.
From a technology standpoint OpenVZ can definitely do this, it really comes down to what expectations the applications and other VMs are expecting the database "service" to be available.
I think you're confusing the situation due to the technology being used. There is nothing inherent in OpenVZ that will disallow you from setting up this kind of architecture. OpenVZ will allow you to loosely "wall off" instances of applications and allow you to create multiple hostnames for the varying services, if you so choose, but otherwise it's no different then if you were to spin up 10 machines with 10 instances of Apache running on them, with a single host running MySQL. |
6,533,242 | I want to add the ability to see the server exception on the client side.
If the server got some exception => i want to show some MessageBox on the client side that will show the exception message ..
How can i do it ? | 2011/06/30 | [
"https://Stackoverflow.com/questions/6533242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465558/"
] | First of all, you need to enable your WCF service to return detailed error information. This is OFF by default, for security reasons (you don't want to tell your attackers all the details of your system in your error messages...)
For that, you need to create a new or amend an existing service behavior with the `<ServiceDebug>` behavior:
```
<behaviors>
<serviceBehaviors>
<behavior name="ServiceWithDetailedErrors">
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
```
Secondly, you need to change your `<service>` tag to reference this new service behavior:
```
<service name="YourNamespace.YourServiceClassName"
behaviorConfiguration="ServiceWithDetailedErrors">
......
</service>
```
And third: you need to adapt your SL solution to look at the details of the errors you're getting back now.
And lastly: while this setting is very useful in development and testing, you **should** turn those error details OFF for production - see above, for security reasons. |
13,159,303 | I'm creating dates from strings with the format 'yyyy-MM-dd' but they're always created on the previous day for some reason. If I set the date as '2012-10-31' the Date object with actually be 30 of October and not 31. For example, this:
```
var d1=new Date('2012-10-31');
```
Will output this:
```
Tue Oct 30 2012 19:30:00 GMT-0430 (Venezuela Standard Time)
```
Can someone explain why this happens? | 2012/10/31 | [
"https://Stackoverflow.com/questions/13159303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478108/"
] | Both are valid approaches. I tend to favour the first option, because it allows better modularity and quite clear boundaries for high level BC. The second option is the 'standard' way of doing this, it favours let's say a more technical layering, while the first option literally favours a more domain driven layering.
Choose the one you feel more comfortable with. |
23,406,727 | I'm trying to simulate (very basic & simple) OS process manager subsystem, I have three "processes" (workers) writing something to console (this is an example):
```
public class Message
{
public Message() { }
public void Show()
{
while (true)
{
Console.WriteLine("Something");
Thread.Sleep(100);
}
}
}
```
Each worker is supposed to be run on a different thread. That's how I do it now:
I have a Process class which constructor takes Action delegate and starts a thread from it and **suspends it**.
```
public class Process
{
Thread thrd;
Action act;
public Process(Action act)
{
this.act = act;
thrd = new Thread(new ThreadStart(this.act));
thrd.Start();
thrd.Suspend();
}
public void Suspend()
{
thrd.Suspend();
}
public void Resume()
{
thrd.Resume();
}
}
```
In that state it waits before my scheduler **resumes it, gives it a time slice to run, then suspends it again.**
```
public void Scheduler()
{
while (true)
{
//ProcessQueue is just FIFO queue for processes
//MainQueue is FIFO queue for ProcessQueue's
ProcessQueue currentQueue = mainQueue.Dequeue();
int count = currentQueue.Count;
if (currentQueue.Count > 0)
{
while (count > 0)
{
Process currentProcess = currentQueue.GetNext();
currentProcess.Resume();
//this is the time slice given to the process
Thread.Sleep(1000);
currentProcess.Suspend();
Console.WriteLine();
currentQueue.Add(currentProcess);
count--;
}
}
mainQueue.Enqueue(currentQueue);
}
}
```
The problem is that it doesn't work consistently. It even doesn't work at all in this state, i have to add Thread.Sleep() before WriteLine in Show() method of the worker, like this.
```
public void Show()
{
while (true)
{
Thread.Sleep(100); //Without this line code doesn't work
Console.WriteLine("Something");
Thread.Sleep(100);
}
}
```
I've been trying to use ManualResetEvent instead of suspend/resume, it works, but since that event is shared, all threads relying on it wake up simultaneously, while I need only one specific thread to be active at one time.
If some could help me figure out how to pause/resume task/thread normally, that'd be great.
What I'm doing is trying to simulate simple preemptive multitasking.
Thanks. | 2014/05/01 | [
"https://Stackoverflow.com/questions/23406727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492726/"
] | `Thread.Suspend` is evil. It is about as evil as `Thread.Abort`. Almost no code is safe in the presence of being paused at arbitrary, unpredictable locations. It might hold a lock that causes other threads to pause as well. You quickly run into deadlocks or unpredictable stalls in other parts of the system.
Imagine you were accidentally pausing the static constructor of `string`. Now all code that wants to use a `string` is halted as well. `Regex` internally uses a locked cache. If you pause while this lock is taken all `Regex` related code might pause. These are just two egregious examples.
Probably, suspending some code deep inside the `Console` class is having unintended consequences.
I'm not sure what to recommend to you. This seems to be an academic exercise so thankfully this is not a production problem for you. User-mode waiting and cancellation must be cooperative in practice. |
58,181,553 | I have three columns in a pandas dataframe that I want to convert into a single date column. The problem is that one of the columns is day column. I am not able to convert into exact date of that month and year. Can anyone please help me to solve this issue. It looks something like this:
```
BirthMonth BirthYear Day
0 5 88 1st Monday
1 10 87 3rd Tuesday
2 12 87 2nd Saturday
3 1 88 1st Tuesday
4 2 88 1st Monday
``` | 2019/10/01 | [
"https://Stackoverflow.com/questions/58181553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12061738/"
] | Based on your reply to my first comment I updated my answer as follows. I think this is what you are looking for:
```
import re
import time
import calendar
import numpy as np
days = ['1st Monday', '3rd Tuesday', '4th wednesday']
months = [2, 3, 5]
years = [1990, 2000, 2019]
def extract_numeric(text: str):
return int(re.findall(r'\d+', text)[0])
def weekday_to_number(weekday: str):
return time.strptime(weekday, "%A").tm_wday
def get_date(number: int, weekday: int, month: int, year: int) -> str:
""" 3rd Tuesday translates to number: 3, weekday: 1 """
firstday, n_days = calendar.monthrange(year, month)
day_list = list(range(7)) * 6
month_days = day_list[firstday:][:n_days]
day = (np.where(np.array(month_days) == weekday)[0] + 1)[number - 1]
return '{}/{}/{}'.format(day, month, year)
numbers = []
weekdays = []
for day in days:
number, weekday = day.split()
numbers.append(extract_numeric(number))
weekdays.append(weekday_to_number(weekday))
dates = []
for number, weekday, month, year in zip(numbers, weekdays, months, years):
dates.append(get_date(number, weekday, month, year))
print(dates) # ['5/2/1990', '21/3/2000', '22/5/2019']
``` |
152,286 | I have a genuine question, I am a noob at stocks. from what I have been reading value investors get higher returns than growth investors but then how come the growth etf IVW gets much higher returns than the value index fund VTV. I've looked at other value ETF's but they sucked even more. Is value investing worth the hype or are these ETF's just bad. If professionals can't do good value investing what chance do we have? Is this a skill worth spending my time in?
[![enter image description here](https://i.stack.imgur.com/XMJfI.png)](https://i.stack.imgur.com/XMJfI.png) | 2022/08/23 | [
"https://money.stackexchange.com/questions/152286",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/118279/"
] | "Value investing" is essentially looking for stocks that are cheaper than they "should be" by some measure. That ETF tracks an index of *large cap* value stocks,
which may skew the results somewhat, since there may be more smaller "value" stocks that perform better than larger ones.
Also note that the two were largely in sync until mid-2018 and mid-2020, where large tech stocks (which are more "growth" than value) dominated from COVID lockdowns (there are many other factors, but that's a significant one).
And note that *this year*, VTV has outperformed IVW - the value fund is only down 5% while the growth fund is down 18%. So it may be an anomaly that growth has outperformed over the period you're looking at.
If you're a "noob at stocks" then it's best to stick with very broad index funds until you understand more the risks associated with different styles of funds, and slowly move to individual stocks. There's no way to ensure that you pick the "best fund" or even the best strategy going forward.
As a young kid, you have plenty of time to make mistakes and learn from them. Don't try to "get rich young" (you might get lucky and do that, but more than likely you'll lose more than you win). Play the long game, save as much as you can, watch it grow, and as you grow you can set aside portions of your portfolio (say 10%) to experiment with individual stocks or other strategies. |
9,130 | Is it scientifically possible to briefly walk on the moon bare footed?
What possible side effects could there be?
Are these side effects mild enough to make it worth it? | 2015/05/16 | [
"https://space.stackexchange.com/questions/9130",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/10160/"
] | There are 3 main threats you'd have to account for:
1. Vacuum. This is discussed in the questions @Forgemonkey linked to. Conclusion: brief exposure of the feet only is survivable.
2. Temperature. Surface temperatures on the Moon swing between + 120 and - 150 °C, so you'd have to pick your spot carefully to have a survivable temperature.
3. Cuts and abrasion. Lunar [regolith](http://www.airspacemag.com/space/stronger-than-dirt-8944228/?no-ist) is [very sharp](http://www.universetoday.com/96208/the-moon-is-toxic/). It'd be like walking across glass shards. On Earth, dust and sand are subject to erosion from wind and water, which tends to make everything smooth. On the Moon these forces are absent, so e.g. the debris from a meteorite impact all keeps its sharp edges indefinitely.
All in all, not a pleasant experience, I'd think. |
237,609 | Consider the following:
```
if(a == b or c)
```
In most languages, this would need to be written as:
```
if(a == b or a == c)
```
which is slightly cumbersome and repeats information.
I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea.
Why don't more languages offer it? Is there performance or syntax issues? | 2014/05/01 | [
"https://softwareengineering.stackexchange.com/questions/237609",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/97416/"
] | The syntax issue is – that it requires syntax.
Whatever syntax your language has, people using the language have to learn it. Otherwise they run the risk of seeing code and not knowing what it does. Thus it's generally considered a good thing if a language has a simple syntax that cleanly handles a lot of cases.
In your specific example, you are trying to take an infix operator (a function that takes two arguments but is written `Argument1 Operator Argument2`) and trying to extend it to multiple arguments. That doesn't work very cleanly because the whole point of infix operators, to the extent that there is one, is to put the operator right in between the 2 arguments. Extending to `(Argument1 Operator Argument2 MagicallyClearSymbol Argument3...)` doesn't seem to add a lot of clarity over `Equals(Arg1,Arg2,...)`. Infix is also typically used to emulate mathematical conventions that people are familiar with, which wouldn't be true of an alternate syntax.
There would not be any particular performance issues associated with your idea, other than that the parser would have to deal with a grammar with another production rule or two, which might have a slight effect on the speed of parsing. This might make some difference for an interpreted or JIT compiled language, but probably not a big difference.
The bigger problem with the idea is just that making **lots of special cases** in a language tends to be a **bad idea**. |
21,045,630 | Regarding to this [tutorial by AppCoda about how to implement a app with UIPageViewController](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/) I'd like to use a custom page control element on top of the pages instead of at the bottom.
When I just put a page control element on top of the single views which will be displayed, the logical result is that the control elements scrolls with the page view away from the screen.
How is it possible to put the control element on top of the views so the page views are full screen (like with an image) so the user can see the views underneath the fixed control element?
I attached an example screenshot - credits to [AppCoda and Path](http://www.appcoda.com/uipageviewcontroller-tutorial-intro/):
![enter image description here](https://i.stack.imgur.com/pR5KH.jpg) | 2014/01/10 | [
"https://Stackoverflow.com/questions/21045630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66414/"
] | After further investigation and searching [I found a solution](https://stackoverflow.com/a/19140401/66414), also on stackoverflow.
The key is the following message to send to a custom `UIPageControl` element:
```
[self.view bringSubviewToFront:self.pageControl];
```
[The AppCoda tutorial is the foundation for this solution](http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/):
Add a `UIPageControl` element on top of the `RootViewController` - the view controller with the arrow.
Create a related `IBOutlet` element in your `ViewController.m`.
In the `viewDidLoad` method you should then add the following code as the last method you call after adding all subviews.
```
[self.view bringSubviewToFront:self.pageControl];
```
To assign the current page based on the pageIndex of the current content view you can add the following to the `UIPageViewControllerDataSource` methods:
```
- (UIPageViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
// ...
index--;
[self.pageControl setCurrentPage:index];
return [self viewControllerAtIndex:index];
}
- (UIPageViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
// ...
index++;
[self.pageControl setCurrentPage:index];
// ...
return [self viewControllerAtIndex:index];
}
``` |
69,089,637 | I'm using React Native, and I have a functional component that has a function in it.
This child component is located inside another component, on that another component I have a button.
So, When the user clicks the button, I want to execute the function in the child component.
I read about forwardRef (as I saw few questions about this that suggested this solution): <https://reactjs.org/docs/forwarding-refs.html>
But it does not seems to fit my problem.
I don't need to access an element in my child component, only to execute the function.
This is my child component:
```
const Popup = () => {
const opacity = useRef(new Animated.Value(1)).current;
const translationY = useRef(new Animated.Value(-120)).current;
const {theme} = useContext(ThemeContext);
const displayPopup = () => {
Animated.spring(translationY, {
toValue: 100,
useNativeDriver: true,
}).start();
};
return (
<Animated.View
style={[
styles.container,
{
backgroundColor: theme.popup,
opacity: opacity,
transform: [{translateY: translationY}],
},
]}>
...
</Animated.View>
);
};
```
Inside the parent component:
```
<SafeAreaView>
// Other components
<Popup />
<Button onPress={() => {//NEEDS TO CALL displayPopup}}/>
</SafeAreaView>
``` | 2021/09/07 | [
"https://Stackoverflow.com/questions/69089637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7868565/"
] | Using a forward ref to give access to a child function can be a solution, but it's not the React way to do it (See [useImperativeHandle hook](https://reactjs.org/docs/hooks-reference.html#useimperativehandle))
Instead, I would change a props of the Popup component to trigger the animation you want to use:
```
import { useEffect } from "react";
const Popup = ({display = false}) => {
const opacity = useRef(new Animated.Value(1)).current;
const translationY = useRef(new Animated.Value(-120)).current;
const {theme} = useContext(ThemeContext);
useEffect(() => {
if(display){
Animated.spring(translationY, {
toValue: 100,
useNativeDriver: true,
}).start();
}
}, [display])
return (
<Animated.View
style={[
styles.container,
{
backgroundColor: theme.popup,
opacity: opacity,
transform: [{translateY: translationY}],
},
]}>
...
</Animated.View>
);
};
```
Parent component:
```
const [display, setDisplay] = useState(false);
return(
<SafeAreaView>
// Other components
<Popup display={display} />
<Button onPress={() => {setDisplay(true)}}/>
</SafeAreaView>
)
``` |
31,030,780 | I have an xaml page with 40 rectangles, (4x10 grid), all named in the format r1-1 through to r10-4.
I would like to iterate through these in code:
```
for (int row = 1; row < 10; row++)
{
for (int col = 1; col < 4; col++)
{
...// what do I need here
}
}
```
Any help please? | 2015/06/24 | [
"https://Stackoverflow.com/questions/31030780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/954884/"
] | Although I wouldn't recommend doing this, you can simply iterate through all of the items in the `Grid Panel` if you have a reference to it. Try something like this:
```
foreach (UIElement element in YourGrid.Children)
{
// do something with each element here
}
``` |
37,810,011 | So at the moment I am doing some iPhone and iPad testing and noticed a very annoying bug in relation to scrolling. So at the moment I have my basic page like so:
```
<body>
<div>
Content of my website...
<button>This button uses jQuery to add a class to the fixed-form div</button>
</div>
<div class="fixed-form">
<form>
</form>
</div>
</body>
```
This is a very basic HTML example that show my basic content area inside the body however I also have a div called `fixed-form`, when the button is pressed in the content area this then adds a class with the following styling to the `fixed-form` div:
```
z-index:0;
color:#fff;
position: fixed;
height: 100% !important;
overflow-y:auto;
-webkit-overflow-scrolling: touch;
overflow-x:hidden;
top:0;
width:100%;
z-index:999 !important;
```
The `fixed-form` div then covers the viewport. The issue is that the content/body behind the `fixed-form` is still scrollable and elements are still clickable. Surely the z-index would have stopped this from happening however it has not. Any idea why this might be happening? I would just like to completely disable all of the content that is not the `fixed-form` div to be disabled from scrolling and clickable.
UPDATE: So far I have tried adding overflow:hidden to the content div however this does stop horizontal scrolling but does not effect the vertical scrolling issue.
Thanks | 2016/06/14 | [
"https://Stackoverflow.com/questions/37810011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5929529/"
] | Is your image too large? Try uploading smaller images (a few 100 KBs in size). If that works, try compressing, or reducing the resolution of the image before encoding it. Here is an example: <https://stackoverflow.com/a/20382559/1237117>
Another option is to increase the json size limit at your Web API.
```
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
``` |
801,993 | After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP:
>
> To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:
>
>
> * Initializing an object reference from a *static* initializer.
> * Storing a reference to it into a *volatile* field.
> * Storing a reference to it into a *final* field.
> * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock.
>
>
>
My first question: how many java developers are aware of this (problem)?
How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above. | 2009/04/29 | [
"https://Stackoverflow.com/questions/801993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148909/"
] | Proportionally, it's probably fair to say that very few programmers sufficiently understand synchronization and concurrency. Who knows how many server applications there are out there right now managing financial transactions, medical records, police records, telephony etc etc that are full of synchronization bugs and essentially work by accident, or very very occasionally fail (never heard of anybody get a phantom phone call added to their telephone bill?) for reasons that are never really looked into or gotten to the bottom of.
Object publication is a particular problem because it's often overlooked, and it's a place where it's quite reasonable for compilers to make optimisations that could result in unexpected behaviour if you don't know about it: in the JIT-compiled code, storing a pointer, then incrementing it and storing the data is a very reasonable thing to do. You might think it's "evil", but at a low level, it's really how you'd expect the JVM spec to be. (Incidentally, I've heard of real-life programs running in JRockit suffering from this problem-- it's not purely theoretical.)
If you know that your application has synchronization bugs but isn't misbehaving in your current JVM on your current hardware, then (a) congratulations; and (b), now is the time to start "walking calmly towards the fire exit", fixing your code and educating your programmers before you need to upgrade too many components. |
22,445,382 | I have this exath path saved somewhere:
```
Array
(
[0] => library
[1] => 1
[2] => book
[3] => 0
[4] => title
[5] => 1
)
```
I have some array and I want to change the value on this index:
```
$values[library][1][book][0][title][1] = "new value";
```
I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints? | 2014/03/17 | [
"https://Stackoverflow.com/questions/22445382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757937/"
] | It makes sense to create a function that does this, so:
```
function array_path_set(array & $array, array $path, $newValue) {
$aux =& $array;
foreach ($path as $key) {
if (isset($aux[$key])) {
$aux =& $aux[$key];
} else {
return false;
}
}
$aux = $newValue;
return true;
}
$values = array(
'library' => array(
1 => array(
'book' => array(
0 => array(
'title' => array(
1 => 'MAGIC VALUE!',
),
),
),
),
),
);
$path = array('library', 1, 'book', 0, 'title', 1);
$newValue = 'ANOTHER MAGIC VALUE!';
var_dump($values);
var_dump(array_path_set($values, $path, $newValue));
var_dump($values);
``` |
897,342 | I am searching for an example of a semigroup, with unique idempotent element, that is not a monoid. Please help. | 2014/08/14 | [
"https://math.stackexchange.com/questions/897342",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/42041/"
] | How about a 2-element null semigroup? If the elements are $x$ and $y$, then the multiplication can be $xy=y=yx=y^2=x^2$. |
32,207 | I have been taking 2-3gm of creatine per day mixed extremely well with 16-17oz lukewarm water, that too on workout days (i.e. I avoid the non-workout days) for at least 2.5 months now. However, I feel that the paunch/belly fat I had, as mentioned in [this post of mine](https://fitness.stackexchange.com/questions/32030/how-much-cardio-is-advisable-for-an-overweight-person-who-is-new-to-bodybuilding), has increased considerably. Now, if I start taking whey protein, would the cons (from the pov of fat in belly/waist) overweigh the pros significantly?
---
Edit: I linked a wrong thread instead of the one I intended to, earlier. The correction has been made. | 2016/09/19 | [
"https://fitness.stackexchange.com/questions/32207",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/22139/"
] | To answer the valid question here:
### Does Creatine cause bloating?
Yes, the water retention usually seen with higher (>10g) loading doses can exceed five pounds (more than two kilograms). Lower doses may cause less water retention. While water mass is not muscle mass (though both count as lean mass), prolonged creatine supplementation is met with an increased rate of muscle growth.
<https://examine.com/supplements/creatine/#hem-weight>
Do you need to load creatine? No. <http://examine.com/nutrition/do-i-need-to-load-creatine/>
However: **you are retaining more water, not more fat**. Your weight is going up as a result of supplementing creatine increasing water retention but that weight is **not fat**. Some bodybuilders cycle off creatine for competitions but it varies from person-to-person.
Note: Some body-fat measuring scales (using electrical resistance) which claim to tell you your body-fat percentage are affected massively by your hydration/water level. Taking creatine may make it read falsely that your body-fat has gone up.
---
If that first post was from you I'd say that personally it sounds like you are trying to cut to show abs you probably don't have. Based on the original questions statistics (weigh/height) my personal recommendation would be to focus your main effort on your strength training, following a structured barbell program will help a lot. Consistency is key here. |
57,172,077 | This spreadsheet I am working on tracks trainings. I'm having issues with this because one training counts for itself and fills the requirement for the other. I am trying to apply conditional formatting on column G that turns the cell red if the dates in;
* Column F and G are not within 3 years
* Column G are blank
* Column F = 0 and Column G are not within 3 years
Here is my best effort at the formula
```
=OR(AND(TODAY()-$F1>1095,TODAY()-$G1>1095),$G1=0,AND($F1=0,TODAY()-$G1>1095))
``` | 2019/07/23 | [
"https://Stackoverflow.com/questions/57172077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11826815/"
] | The domain `toastmasterstimer.tk` seems to be missing the Digital Asset Links file, necessary to validate ownership and enable fullscreen.
The file needs to be available at `https://toastmasterstimer.tk/.well-known/assetlinks.json`.
You can use the [Statement List Generator and Tester](https://developers.google.com/digital-asset-links/tools/generator) to generate the `assetlinks.json` file.
This [section](https://developers.google.com/web/updates/2019/02/using-twa#link-site-to-app) of the documentation provides more information, including how to extract the SHA-256 fingerprint from your signing key. |