qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
56,888 | At work we make websites for other companies. One of our client wanted us to make a e-commerce website for them. Nothing out of the ordinary until we realized they had 50 000+ products to sell and their classification is inexistant. In other words, we don't have ay categories to work with. They just told us to "Put a search bar and it'll be fine".
So, how would you make an e-commerce site work for the users without any kind of browsing through lists of products ?
**EDIT**
The client is a reseller. He sells power outlets, light bulbs, electrical cords and stuff like that. The reselling part is why he doesn't have categories, because every single seller manage their own database with their own description for each product. | 2014/05/07 | ['https://ux.stackexchange.com/questions/56888', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/47784/'] | Your client might not be able to assign categories to products, but there is noting stopping them assigning categories to *sellers*.
The kind of sellers using a resale ecommerce site are likely to be specialists in certain categories already, rather than having a diverse range of products (e.g. there will likely be sellers that specialise in lightbulbs and related items). You could build loose categories around this information to augment the search functionality. For example you could have an option to "view more sellers like this", or "view all items from similar sellers". | If there is no way of categorizing the products then search must be the primary method of traversing the catalog. But as a previous answer suggests you should guide the user with top products sold for a search, top products viewed for a search etc. The other users behavior should help guide them, consider adding a method for users to tag products to build the categories may be an option. You may also be able to build a straw man structure by querying the product names for things like bulb, switch, socket etc and start with that to see what sort of a category structure may be involved. |
203,891 | I found part of my answer here: [If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)](https://math.stackexchange.com/questions/28123/if-gfx-is-one-to-one-injective-show-fx-is-also-one-to-one-given-that); however I wanted to flesh out the last two statements I had in a proposition in my notes.
>
> **Proposition:**
> Let $f: A \rightarrow B$ and $g: B \rightarrow C$. Then:
>
>
> (i) If $g \circ f$ is one-to-one, then $f$ is one-to-one.
>
>
> (ii) If $g \circ f$ is onto, then $g$ is onto.
>
>
>
Proof:
(i) Suppose $f(x)=f(y)$ for some $x,y$.
Since $g \circ f$ is one-to-one: $$g\circ f(x) = g\circ f(y) \Rightarrow x=y,\forall x,y \in A.$$
Therefore $f$ must be one-to-one.
(ii) Since $g \circ f (x)$ is onto, then for every $c \in C$ there exists an $a \in A$ such that $c=g(f(a))$. Then there exists a $b \in B$ with $b=f(a)$ such that $g(b)=c$. Thus g is onto.
I wanted to confirm that these proofs are both correct for my peace of mind (as they weren't proven in class). | 2012/09/28 | ['https://math.stackexchange.com/questions/203891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/'] | Both of your proofs are correct. | I've never taken an analysis course but I don't believe that your first proof is correct. Since take for example $f=x^2$, which isn't one-to-one. $g \circ f (-2)$ and $g \circ f (2)$ would be equal, since in both cases it is $g(4)$ and $g$ is a function. So $x$ would not have to equal $y$ and thus $f$ does not have a requirement of being one-to-one for the composition $g(f(x))$ to be one to one. However I do believe that $g$ would have to be one to one for that to be the case. Please correct me if I am wrong. Just my two cents. |
203,891 | I found part of my answer here: [If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)](https://math.stackexchange.com/questions/28123/if-gfx-is-one-to-one-injective-show-fx-is-also-one-to-one-given-that); however I wanted to flesh out the last two statements I had in a proposition in my notes.
>
> **Proposition:**
> Let $f: A \rightarrow B$ and $g: B \rightarrow C$. Then:
>
>
> (i) If $g \circ f$ is one-to-one, then $f$ is one-to-one.
>
>
> (ii) If $g \circ f$ is onto, then $g$ is onto.
>
>
>
Proof:
(i) Suppose $f(x)=f(y)$ for some $x,y$.
Since $g \circ f$ is one-to-one: $$g\circ f(x) = g\circ f(y) \Rightarrow x=y,\forall x,y \in A.$$
Therefore $f$ must be one-to-one.
(ii) Since $g \circ f (x)$ is onto, then for every $c \in C$ there exists an $a \in A$ such that $c=g(f(a))$. Then there exists a $b \in B$ with $b=f(a)$ such that $g(b)=c$. Thus g is onto.
I wanted to confirm that these proofs are both correct for my peace of mind (as they weren't proven in class). | 2012/09/28 | ['https://math.stackexchange.com/questions/203891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/'] | Both of your proofs are correct. | On the first one i would say since g composed of f is one-to-one, if g(f(x))=g(f(y)) for all x,y in A then x=y. By definition of f then there exist some value f(x) and f(y) in B. Then because we already noted x=y. F(x) must equal F(y) by the definition of a function. |
203,891 | I found part of my answer here: [If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)](https://math.stackexchange.com/questions/28123/if-gfx-is-one-to-one-injective-show-fx-is-also-one-to-one-given-that); however I wanted to flesh out the last two statements I had in a proposition in my notes.
>
> **Proposition:**
> Let $f: A \rightarrow B$ and $g: B \rightarrow C$. Then:
>
>
> (i) If $g \circ f$ is one-to-one, then $f$ is one-to-one.
>
>
> (ii) If $g \circ f$ is onto, then $g$ is onto.
>
>
>
Proof:
(i) Suppose $f(x)=f(y)$ for some $x,y$.
Since $g \circ f$ is one-to-one: $$g\circ f(x) = g\circ f(y) \Rightarrow x=y,\forall x,y \in A.$$
Therefore $f$ must be one-to-one.
(ii) Since $g \circ f (x)$ is onto, then for every $c \in C$ there exists an $a \in A$ such that $c=g(f(a))$. Then there exists a $b \in B$ with $b=f(a)$ such that $g(b)=c$. Thus g is onto.
I wanted to confirm that these proofs are both correct for my peace of mind (as they weren't proven in class). | 2012/09/28 | ['https://math.stackexchange.com/questions/203891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/'] | Both of your proofs are correct. | (i) If $f \circ g$ is one-to-one, then it is invertible. Its inverse is $g^{-1} \circ f^{-1}.$ Thus $f^{-1}$ exists. Therefore, $f$ is invertible, and thus is one-to-one. QED. |
203,891 | I found part of my answer here: [If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)](https://math.stackexchange.com/questions/28123/if-gfx-is-one-to-one-injective-show-fx-is-also-one-to-one-given-that); however I wanted to flesh out the last two statements I had in a proposition in my notes.
>
> **Proposition:**
> Let $f: A \rightarrow B$ and $g: B \rightarrow C$. Then:
>
>
> (i) If $g \circ f$ is one-to-one, then $f$ is one-to-one.
>
>
> (ii) If $g \circ f$ is onto, then $g$ is onto.
>
>
>
Proof:
(i) Suppose $f(x)=f(y)$ for some $x,y$.
Since $g \circ f$ is one-to-one: $$g\circ f(x) = g\circ f(y) \Rightarrow x=y,\forall x,y \in A.$$
Therefore $f$ must be one-to-one.
(ii) Since $g \circ f (x)$ is onto, then for every $c \in C$ there exists an $a \in A$ such that $c=g(f(a))$. Then there exists a $b \in B$ with $b=f(a)$ such that $g(b)=c$. Thus g is onto.
I wanted to confirm that these proofs are both correct for my peace of mind (as they weren't proven in class). | 2012/09/28 | ['https://math.stackexchange.com/questions/203891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/'] | I've never taken an analysis course but I don't believe that your first proof is correct. Since take for example $f=x^2$, which isn't one-to-one. $g \circ f (-2)$ and $g \circ f (2)$ would be equal, since in both cases it is $g(4)$ and $g$ is a function. So $x$ would not have to equal $y$ and thus $f$ does not have a requirement of being one-to-one for the composition $g(f(x))$ to be one to one. However I do believe that $g$ would have to be one to one for that to be the case. Please correct me if I am wrong. Just my two cents. | On the first one i would say since g composed of f is one-to-one, if g(f(x))=g(f(y)) for all x,y in A then x=y. By definition of f then there exist some value f(x) and f(y) in B. Then because we already noted x=y. F(x) must equal F(y) by the definition of a function. |
203,891 | I found part of my answer here: [If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)](https://math.stackexchange.com/questions/28123/if-gfx-is-one-to-one-injective-show-fx-is-also-one-to-one-given-that); however I wanted to flesh out the last two statements I had in a proposition in my notes.
>
> **Proposition:**
> Let $f: A \rightarrow B$ and $g: B \rightarrow C$. Then:
>
>
> (i) If $g \circ f$ is one-to-one, then $f$ is one-to-one.
>
>
> (ii) If $g \circ f$ is onto, then $g$ is onto.
>
>
>
Proof:
(i) Suppose $f(x)=f(y)$ for some $x,y$.
Since $g \circ f$ is one-to-one: $$g\circ f(x) = g\circ f(y) \Rightarrow x=y,\forall x,y \in A.$$
Therefore $f$ must be one-to-one.
(ii) Since $g \circ f (x)$ is onto, then for every $c \in C$ there exists an $a \in A$ such that $c=g(f(a))$. Then there exists a $b \in B$ with $b=f(a)$ such that $g(b)=c$. Thus g is onto.
I wanted to confirm that these proofs are both correct for my peace of mind (as they weren't proven in class). | 2012/09/28 | ['https://math.stackexchange.com/questions/203891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/'] | (i) If $f \circ g$ is one-to-one, then it is invertible. Its inverse is $g^{-1} \circ f^{-1}.$ Thus $f^{-1}$ exists. Therefore, $f$ is invertible, and thus is one-to-one. QED. | On the first one i would say since g composed of f is one-to-one, if g(f(x))=g(f(y)) for all x,y in A then x=y. By definition of f then there exist some value f(x) and f(y) in B. Then because we already noted x=y. F(x) must equal F(y) by the definition of a function. |
3,257,640 | Let $\gamma:[0,1] \longrightarrow \mathbf{C} \backslash \{0\}$ be a closed curve (continuous and of bounded variation).
We call
$$\operatorname{Ind}\_\gamma(0) \overset{\mathrm{def}}{=} \frac{1}{2 \pi i}\int\_\gamma \frac{1}{z}\ dz.$$
$\textbf{the index of $\gamma$ around $0$.}$
As for the winding number, we can take a pair of continuous real valued functions $r$ and $\theta$ that satisfies
$$r:[0,1] \longrightarrow (0,\infty),$$
$$\theta:[0,1] \longrightarrow \mathbf{R},$$
$$\forall t \in [0,1]\, \left[\, \gamma(t) = r(t) \cdot e^{i \cdot \theta(t)}\, \right],$$
and
$$-\pi < \theta(0) \leq \pi.$$
(The proof of this can be found in chapter 7 of A. F. Beardon, Complex Analysis: The Argument Principle in Analysis and Topology, Wiley-Interscience publication 1979).
We call
$$\operatorname{Wnd}\_\gamma(0) \overset{\mathrm{def}}{=}\frac{\theta(1) - \theta(0)}{2\pi}$$
$\textbf{the winding number of $\gamma$ around $0$}$.
It is already known that if $\gamma$ is $C^1$-curve, then
$$\operatorname{Ind}\_\gamma(0) = \operatorname{Wnd}\_\gamma(0)$$
(see [definition of winding number, have doubt in definition.](https://math.stackexchange.com/questions/186512/definition-of-winding-number-have-doubt-in-definition)).
My question: When $\gamma$ is not $C^1$ path,
$$\operatorname{Ind}\_\gamma(0) = \operatorname{Wnd}\_\gamma(0)?$$
Thank you for reading. | 2019/06/10 | ['https://math.stackexchange.com/questions/3257640', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/680871/'] | First, we observe that
$$
f(x)=x-\ln x -1\geq \frac{(x-1)^2}{2}-\frac{(x-1)^3}{3}=g(x).
$$
Now clearly if
$$
g(x)\geq\varepsilon \Rightarrow f(x)\geq \varepsilon
$$
Now all we have to do is to find the roots $f(x)-\varepsilon=0$ and identify the one which is larger than, but close to $1$.
It is given by
$$
x(\varepsilon)=-\frac{1}{4}(1-12\varepsilon+2\sqrt{36\varepsilon^2-6\varepsilon})^\tfrac{1}{3}-\frac{1}{4(1-12\varepsilon+2\sqrt{36\varepsilon^2-6\varepsilon})^\tfrac{1}{3}}+\frac{3}{2}-\frac{i\sqrt{3}}{2}\left(\frac{1-12\varepsilon+2\sqrt{36\varepsilon^2-6\varepsilon})^\tfrac{1}{3}}{2}-\frac{1}{2(1-12\varepsilon+2\sqrt{36\varepsilon^2-6\varepsilon})^\tfrac{1}{3})}\right)
$$
edit: If this expression does not satisfy you, you can of, of course expand it around $\varepsilon=0$ to get:
$$
x(\varepsilon)\approx 1+\sqrt{2\varepsilon}+\tfrac{2}{3}\varepsilon+\tfrac{5}{9}\sqrt{2}\varepsilon^\tfrac{3}{2}
$$ | $x(\epsilon)=x-\ln(x)-1$ is the largest upper bound possible, and also happens to be in closed form. |
125,202 | I'm writing a simple utility to crop batches of multi-band geotiff raster files to the same (smaller) area. Using gdalwarp, I can easily crop a file using a single-polygon clipping shapefile:
```
gdalwarp -cutline clipper.shp -crop_to_cutline input.tif output.tif
```
However, the actual area I want to clip to will always be initially defined by another geotiff raster file, not a shapefile. It would be nice if I could use the extent of that raster as the clipping file, but I'm not sure how to do this. Unsurprisingly, the following doesn't work (it doesn't raise an error, it just doesn't produce anything):
```
gdalwarp -cutline clipper.tif-crop_to_cutline input.tif output.tif
```
So, my question is, is there a way to supply a raster to `gdalwarp -cutline`? Alternately, is there another gdal function that can clip a raster using another raster? If neither of these are possible, is there a very simple way to produce a shapefile with a single polygon defined by the extent of a raster?
This code will be wrapped in a more extensive python script, so I can use either command line gdal utilities or any of the python bindings for gdal.
As a side note, I know that I could easily just make a clipping shapefile that covers the extent of my raster in QGIS. I may wind up doing that if I don't find a straightforward solution, but I will ultimately wind up using this utility on dozens if not hundreds of areas as part of a large automated analysis, so I'd prefer not to have a tedious manual step even if it is very easy. | 2014/12/10 | ['https://gis.stackexchange.com/questions/125202', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37589/'] | I don't know if it's possible to clip a raster with an other raster but
you could use gdaltindex to build the shapefile with the extent of your raster.
<http://www.gdal.org/gdaltindex.html> | For irregular polygons, and assuming that your geotiff raster file is a binary raster, you could use [GDAL\_Calc](http://www.gdal.org/gdal_calc.html):
```
GDAL_Calc.py -A Mask.tif -B CutBigImageToClip.tif --outfile=SmallerFile.tif --NoDataValue=0 --Calc="B*(A>0)"
```
This query will populate 0 where Mask.tif <= 0 and BigImage where the Mask > 0. To do this both rasters must be the same cell size, rows and columns. To extract the same extents use GDAL\_Translate with the `-projwin ulx uly lrx lry` option (box is in projected coordinates), but ensure that the projwin box does not extend over the edges of either raster.
```
GDAL_Translate -of GTIFF -projwin ulx uly lrx lry BigImageToClip.tif CutBigImageToClip.tif
```
Substitute values for the projwin box derived from the Mask. |
125,202 | I'm writing a simple utility to crop batches of multi-band geotiff raster files to the same (smaller) area. Using gdalwarp, I can easily crop a file using a single-polygon clipping shapefile:
```
gdalwarp -cutline clipper.shp -crop_to_cutline input.tif output.tif
```
However, the actual area I want to clip to will always be initially defined by another geotiff raster file, not a shapefile. It would be nice if I could use the extent of that raster as the clipping file, but I'm not sure how to do this. Unsurprisingly, the following doesn't work (it doesn't raise an error, it just doesn't produce anything):
```
gdalwarp -cutline clipper.tif-crop_to_cutline input.tif output.tif
```
So, my question is, is there a way to supply a raster to `gdalwarp -cutline`? Alternately, is there another gdal function that can clip a raster using another raster? If neither of these are possible, is there a very simple way to produce a shapefile with a single polygon defined by the extent of a raster?
This code will be wrapped in a more extensive python script, so I can use either command line gdal utilities or any of the python bindings for gdal.
As a side note, I know that I could easily just make a clipping shapefile that covers the extent of my raster in QGIS. I may wind up doing that if I don't find a straightforward solution, but I will ultimately wind up using this utility on dozens if not hundreds of areas as part of a large automated analysis, so I'd prefer not to have a tedious manual step even if it is very easy. | 2014/12/10 | ['https://gis.stackexchange.com/questions/125202', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37589/'] | I don't know if it's possible to clip a raster with an other raster but
you could use gdaltindex to build the shapefile with the extent of your raster.
<http://www.gdal.org/gdaltindex.html> | The solution in Python directly, without making shape:
```
import gdal
from gdalconst import GA_ReadOnly
data = gdal.Open('img_mask.tif', GA_ReadOnly)
geoTransform = data.GetGeoTransform()
minx = geoTransform[0]
maxy = geoTransform[3]
maxx = minx + geoTransform[1] * data.RasterXSize
miny = maxy + geoTransform[5] * data.RasterYSize
call('gdal_translate -projwin ' + ' '.join([str(x) for x in [minx, maxy, maxx, miny]]) + ' -of GTiff img_orig.tif img_out.tif', shell=True)
``` |
125,202 | I'm writing a simple utility to crop batches of multi-band geotiff raster files to the same (smaller) area. Using gdalwarp, I can easily crop a file using a single-polygon clipping shapefile:
```
gdalwarp -cutline clipper.shp -crop_to_cutline input.tif output.tif
```
However, the actual area I want to clip to will always be initially defined by another geotiff raster file, not a shapefile. It would be nice if I could use the extent of that raster as the clipping file, but I'm not sure how to do this. Unsurprisingly, the following doesn't work (it doesn't raise an error, it just doesn't produce anything):
```
gdalwarp -cutline clipper.tif-crop_to_cutline input.tif output.tif
```
So, my question is, is there a way to supply a raster to `gdalwarp -cutline`? Alternately, is there another gdal function that can clip a raster using another raster? If neither of these are possible, is there a very simple way to produce a shapefile with a single polygon defined by the extent of a raster?
This code will be wrapped in a more extensive python script, so I can use either command line gdal utilities or any of the python bindings for gdal.
As a side note, I know that I could easily just make a clipping shapefile that covers the extent of my raster in QGIS. I may wind up doing that if I don't find a straightforward solution, but I will ultimately wind up using this utility on dozens if not hundreds of areas as part of a large automated analysis, so I'd prefer not to have a tedious manual step even if it is very easy. | 2014/12/10 | ['https://gis.stackexchange.com/questions/125202', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37589/'] | I don't know if it's possible to clip a raster with an other raster but
you could use gdaltindex to build the shapefile with the extent of your raster.
<http://www.gdal.org/gdaltindex.html> | Here u can use this code to run an intersection raster tool. You need to be aware of CRS and pixel size (cols and rows).
```
# This file is part of Brazil Data Cube Validation Tools.
# Copyright (C) 2020.
# Python Native
import os
# 3rd party
import gdal
import numpy
def raster_intersection(ds1, ds2, nodata1=None, nodata2=None, output_name1=None,
output_name2=None):
"""Perform image intersection of two rasters with different extent and
projection.
Args:
ds1 (GDAL dataset) - GDAL dataset of an image
ds2 (GDAL dataset) - GDAL dataset of an image
nodata1 (number) - nodata value of image 1
nodata2 (number) - nodata value of image 2
output_name1 (string) - path to output intersection of ds1
output_name2 (string) - path to output intersection of ds2
Returns:
dataset1 (GDAL dataset), dataset2 (GDAL dataset): intersection dataset1
and intersection dataset2.
"""
###Setting nodata
nodata = 0
###Check if images NoData is set
if nodata2 is not None:
nodata = nodata2
ds2.GetRasterBand(1).SetNoDataValue(nodata)
else:
if ds2.GetRasterBand(1).GetNoDataValue() is None:
ds2.GetRasterBand(1).SetNoDataValue(nodata)
if nodata1 is not None:
nodata = nodata1
ds1.GetRasterBand(1).SetNoDataValue(nodata1)
else:
if ds1.GetRasterBand(1).GetNoDataValue() is None:
ds1.GetRasterBand(1).SetNoDataValue(nodata)
### Get extent from ds1
projection = ds1.GetProjectionRef()
geoTransform = ds1.GetGeoTransform()
###Get minx and max y
minx = geoTransform[0]
maxy = geoTransform[3]
###Raster dimensions
xsize = ds1.RasterXSize
ysize = ds1.RasterYSize
maxx = minx + geoTransform[1] * xsize
miny = maxy + geoTransform[5] * ysize
###Warp to same spatial resolution
gdaloptions = {'format': 'MEM', 'xRes': geoTransform[1], 'yRes':
geoTransform[5], 'dstSRS': projection}
ds2w = gdal.Warp('', ds2, **gdaloptions)
ds2 = None
###Translate to same projection
ds2c = gdal.Translate('', ds2w, format='MEM', projWin=[minx, maxy, maxx, miny],
outputSRS=projection)
ds2w = None
ds1c = gdal.Translate('', ds1, format='MEM', projWin=[minx, maxy, maxx, miny],
outputSRS=projection)
ds1 = None
###Check if will create file on disk
if output_name1 is not None or output_name2 is not None:
driver = gdal.GetDriverByName("GTiff")
if output_name1 is None:
output_name1 = 'intersection1.tif'
if output_name2 is None:
output_name2 = 'intersection2.tif'
else:
driver = gdal.GetDriverByName("MEM")
output_name1 = ''
output_name2 = ''
dataset1 = driver.Create(output_name1, xsize, ysize, 1,
ds1c.GetRasterBand(1).DataType)
dataset1.SetGeoTransform(geoTransform)
dataset1.SetProjection(projection)
dataset1.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value
dataset1.GetRasterBand(1).WriteArray(ds1c.GetRasterBand(1).ReadAsArray())
dataset2 = driver.Create(output_name2, xsize, ysize, 1,
ds2c.GetRasterBand(1).DataType)
dataset2.SetGeoTransform(geoTransform)
dataset2.SetProjection(projection)
dataset2.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value
dataset2.GetRasterBand(1).WriteArray(ds2c.GetRasterBand(1).ReadAsArray())
ds1c = None
ds2c = None
return dataset1, dataset2
def raster_absolute_diff(ds1, ds2, nodata1=None, nodata2=None,
output_file=None):
"""Perform image absolute difference (support different extent and projection).
Args:
path1 (string) - path to image 1 (reference)
path2 (string) - path to image 2 (target)
output_dir (string) - path to output files
nodata1 (number) - nodata value of image 1
nodata2 (number) - nodata value of image 2
Returns:
dataset (GDAL dataset): dataset containing absolute difference between
ds1 and ds2.
"""
if output_file is None:
output_file = 'abs_diff.tif'
ds1_intersec, ds2_intersec = raster_intersection(ds1, ds2, nodata1, nodata2,
None, None)
### Read bands with numpy to algebra
nodata = ds1_intersec.GetRasterBand(1).GetNoDataValue()
bandtar = numpy.array(ds1_intersec.GetRasterBand(1).ReadAsArray().astype(float))
fill_bandtar = numpy.where(bandtar == nodata)
bandref = numpy.array(ds2_intersec.GetRasterBand(1).ReadAsArray().astype(float))
fill_bandref = numpy.where(bandref == nodata)
### Get extent from ds1
projection = ds1.GetProjectionRef()
geoTransform = ds1.GetGeoTransform()
[cols, rows] = ds1.GetRasterBand(1).ReadAsArray().shape
ds1 = None
ds2 = None
diff = numpy.abs(bandtar - bandref)
diff[fill_bandtar] = nodata
diff[fill_bandref] = nodata
###Check if will create file on disk
if output_file is not None:
driver = gdal.GetDriverByName("GTiff")
else:
driver = gdal.GetDriverByName("MEM")
output_file = ''
dataset = driver.Create(output_file, rows, cols, 1,
ds1_intersec.GetRasterBand(1).DataType)
dataset.SetGeoTransform(geoTransform)
dataset.SetProjection(projection)
dataset.GetRasterBand(1).SetNoDataValue(nodata)
dataset.GetRasterBand(1).WriteArray(diff)
return dataset
``` |
125,202 | I'm writing a simple utility to crop batches of multi-band geotiff raster files to the same (smaller) area. Using gdalwarp, I can easily crop a file using a single-polygon clipping shapefile:
```
gdalwarp -cutline clipper.shp -crop_to_cutline input.tif output.tif
```
However, the actual area I want to clip to will always be initially defined by another geotiff raster file, not a shapefile. It would be nice if I could use the extent of that raster as the clipping file, but I'm not sure how to do this. Unsurprisingly, the following doesn't work (it doesn't raise an error, it just doesn't produce anything):
```
gdalwarp -cutline clipper.tif-crop_to_cutline input.tif output.tif
```
So, my question is, is there a way to supply a raster to `gdalwarp -cutline`? Alternately, is there another gdal function that can clip a raster using another raster? If neither of these are possible, is there a very simple way to produce a shapefile with a single polygon defined by the extent of a raster?
This code will be wrapped in a more extensive python script, so I can use either command line gdal utilities or any of the python bindings for gdal.
As a side note, I know that I could easily just make a clipping shapefile that covers the extent of my raster in QGIS. I may wind up doing that if I don't find a straightforward solution, but I will ultimately wind up using this utility on dozens if not hundreds of areas as part of a large automated analysis, so I'd prefer not to have a tedious manual step even if it is very easy. | 2014/12/10 | ['https://gis.stackexchange.com/questions/125202', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37589/'] | For irregular polygons, and assuming that your geotiff raster file is a binary raster, you could use [GDAL\_Calc](http://www.gdal.org/gdal_calc.html):
```
GDAL_Calc.py -A Mask.tif -B CutBigImageToClip.tif --outfile=SmallerFile.tif --NoDataValue=0 --Calc="B*(A>0)"
```
This query will populate 0 where Mask.tif <= 0 and BigImage where the Mask > 0. To do this both rasters must be the same cell size, rows and columns. To extract the same extents use GDAL\_Translate with the `-projwin ulx uly lrx lry` option (box is in projected coordinates), but ensure that the projwin box does not extend over the edges of either raster.
```
GDAL_Translate -of GTIFF -projwin ulx uly lrx lry BigImageToClip.tif CutBigImageToClip.tif
```
Substitute values for the projwin box derived from the Mask. | Here u can use this code to run an intersection raster tool. You need to be aware of CRS and pixel size (cols and rows).
```
# This file is part of Brazil Data Cube Validation Tools.
# Copyright (C) 2020.
# Python Native
import os
# 3rd party
import gdal
import numpy
def raster_intersection(ds1, ds2, nodata1=None, nodata2=None, output_name1=None,
output_name2=None):
"""Perform image intersection of two rasters with different extent and
projection.
Args:
ds1 (GDAL dataset) - GDAL dataset of an image
ds2 (GDAL dataset) - GDAL dataset of an image
nodata1 (number) - nodata value of image 1
nodata2 (number) - nodata value of image 2
output_name1 (string) - path to output intersection of ds1
output_name2 (string) - path to output intersection of ds2
Returns:
dataset1 (GDAL dataset), dataset2 (GDAL dataset): intersection dataset1
and intersection dataset2.
"""
###Setting nodata
nodata = 0
###Check if images NoData is set
if nodata2 is not None:
nodata = nodata2
ds2.GetRasterBand(1).SetNoDataValue(nodata)
else:
if ds2.GetRasterBand(1).GetNoDataValue() is None:
ds2.GetRasterBand(1).SetNoDataValue(nodata)
if nodata1 is not None:
nodata = nodata1
ds1.GetRasterBand(1).SetNoDataValue(nodata1)
else:
if ds1.GetRasterBand(1).GetNoDataValue() is None:
ds1.GetRasterBand(1).SetNoDataValue(nodata)
### Get extent from ds1
projection = ds1.GetProjectionRef()
geoTransform = ds1.GetGeoTransform()
###Get minx and max y
minx = geoTransform[0]
maxy = geoTransform[3]
###Raster dimensions
xsize = ds1.RasterXSize
ysize = ds1.RasterYSize
maxx = minx + geoTransform[1] * xsize
miny = maxy + geoTransform[5] * ysize
###Warp to same spatial resolution
gdaloptions = {'format': 'MEM', 'xRes': geoTransform[1], 'yRes':
geoTransform[5], 'dstSRS': projection}
ds2w = gdal.Warp('', ds2, **gdaloptions)
ds2 = None
###Translate to same projection
ds2c = gdal.Translate('', ds2w, format='MEM', projWin=[minx, maxy, maxx, miny],
outputSRS=projection)
ds2w = None
ds1c = gdal.Translate('', ds1, format='MEM', projWin=[minx, maxy, maxx, miny],
outputSRS=projection)
ds1 = None
###Check if will create file on disk
if output_name1 is not None or output_name2 is not None:
driver = gdal.GetDriverByName("GTiff")
if output_name1 is None:
output_name1 = 'intersection1.tif'
if output_name2 is None:
output_name2 = 'intersection2.tif'
else:
driver = gdal.GetDriverByName("MEM")
output_name1 = ''
output_name2 = ''
dataset1 = driver.Create(output_name1, xsize, ysize, 1,
ds1c.GetRasterBand(1).DataType)
dataset1.SetGeoTransform(geoTransform)
dataset1.SetProjection(projection)
dataset1.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value
dataset1.GetRasterBand(1).WriteArray(ds1c.GetRasterBand(1).ReadAsArray())
dataset2 = driver.Create(output_name2, xsize, ysize, 1,
ds2c.GetRasterBand(1).DataType)
dataset2.SetGeoTransform(geoTransform)
dataset2.SetProjection(projection)
dataset2.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value
dataset2.GetRasterBand(1).WriteArray(ds2c.GetRasterBand(1).ReadAsArray())
ds1c = None
ds2c = None
return dataset1, dataset2
def raster_absolute_diff(ds1, ds2, nodata1=None, nodata2=None,
output_file=None):
"""Perform image absolute difference (support different extent and projection).
Args:
path1 (string) - path to image 1 (reference)
path2 (string) - path to image 2 (target)
output_dir (string) - path to output files
nodata1 (number) - nodata value of image 1
nodata2 (number) - nodata value of image 2
Returns:
dataset (GDAL dataset): dataset containing absolute difference between
ds1 and ds2.
"""
if output_file is None:
output_file = 'abs_diff.tif'
ds1_intersec, ds2_intersec = raster_intersection(ds1, ds2, nodata1, nodata2,
None, None)
### Read bands with numpy to algebra
nodata = ds1_intersec.GetRasterBand(1).GetNoDataValue()
bandtar = numpy.array(ds1_intersec.GetRasterBand(1).ReadAsArray().astype(float))
fill_bandtar = numpy.where(bandtar == nodata)
bandref = numpy.array(ds2_intersec.GetRasterBand(1).ReadAsArray().astype(float))
fill_bandref = numpy.where(bandref == nodata)
### Get extent from ds1
projection = ds1.GetProjectionRef()
geoTransform = ds1.GetGeoTransform()
[cols, rows] = ds1.GetRasterBand(1).ReadAsArray().shape
ds1 = None
ds2 = None
diff = numpy.abs(bandtar - bandref)
diff[fill_bandtar] = nodata
diff[fill_bandref] = nodata
###Check if will create file on disk
if output_file is not None:
driver = gdal.GetDriverByName("GTiff")
else:
driver = gdal.GetDriverByName("MEM")
output_file = ''
dataset = driver.Create(output_file, rows, cols, 1,
ds1_intersec.GetRasterBand(1).DataType)
dataset.SetGeoTransform(geoTransform)
dataset.SetProjection(projection)
dataset.GetRasterBand(1).SetNoDataValue(nodata)
dataset.GetRasterBand(1).WriteArray(diff)
return dataset
``` |
125,202 | I'm writing a simple utility to crop batches of multi-band geotiff raster files to the same (smaller) area. Using gdalwarp, I can easily crop a file using a single-polygon clipping shapefile:
```
gdalwarp -cutline clipper.shp -crop_to_cutline input.tif output.tif
```
However, the actual area I want to clip to will always be initially defined by another geotiff raster file, not a shapefile. It would be nice if I could use the extent of that raster as the clipping file, but I'm not sure how to do this. Unsurprisingly, the following doesn't work (it doesn't raise an error, it just doesn't produce anything):
```
gdalwarp -cutline clipper.tif-crop_to_cutline input.tif output.tif
```
So, my question is, is there a way to supply a raster to `gdalwarp -cutline`? Alternately, is there another gdal function that can clip a raster using another raster? If neither of these are possible, is there a very simple way to produce a shapefile with a single polygon defined by the extent of a raster?
This code will be wrapped in a more extensive python script, so I can use either command line gdal utilities or any of the python bindings for gdal.
As a side note, I know that I could easily just make a clipping shapefile that covers the extent of my raster in QGIS. I may wind up doing that if I don't find a straightforward solution, but I will ultimately wind up using this utility on dozens if not hundreds of areas as part of a large automated analysis, so I'd prefer not to have a tedious manual step even if it is very easy. | 2014/12/10 | ['https://gis.stackexchange.com/questions/125202', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37589/'] | The solution in Python directly, without making shape:
```
import gdal
from gdalconst import GA_ReadOnly
data = gdal.Open('img_mask.tif', GA_ReadOnly)
geoTransform = data.GetGeoTransform()
minx = geoTransform[0]
maxy = geoTransform[3]
maxx = minx + geoTransform[1] * data.RasterXSize
miny = maxy + geoTransform[5] * data.RasterYSize
call('gdal_translate -projwin ' + ' '.join([str(x) for x in [minx, maxy, maxx, miny]]) + ' -of GTiff img_orig.tif img_out.tif', shell=True)
``` | Here u can use this code to run an intersection raster tool. You need to be aware of CRS and pixel size (cols and rows).
```
# This file is part of Brazil Data Cube Validation Tools.
# Copyright (C) 2020.
# Python Native
import os
# 3rd party
import gdal
import numpy
def raster_intersection(ds1, ds2, nodata1=None, nodata2=None, output_name1=None,
output_name2=None):
"""Perform image intersection of two rasters with different extent and
projection.
Args:
ds1 (GDAL dataset) - GDAL dataset of an image
ds2 (GDAL dataset) - GDAL dataset of an image
nodata1 (number) - nodata value of image 1
nodata2 (number) - nodata value of image 2
output_name1 (string) - path to output intersection of ds1
output_name2 (string) - path to output intersection of ds2
Returns:
dataset1 (GDAL dataset), dataset2 (GDAL dataset): intersection dataset1
and intersection dataset2.
"""
###Setting nodata
nodata = 0
###Check if images NoData is set
if nodata2 is not None:
nodata = nodata2
ds2.GetRasterBand(1).SetNoDataValue(nodata)
else:
if ds2.GetRasterBand(1).GetNoDataValue() is None:
ds2.GetRasterBand(1).SetNoDataValue(nodata)
if nodata1 is not None:
nodata = nodata1
ds1.GetRasterBand(1).SetNoDataValue(nodata1)
else:
if ds1.GetRasterBand(1).GetNoDataValue() is None:
ds1.GetRasterBand(1).SetNoDataValue(nodata)
### Get extent from ds1
projection = ds1.GetProjectionRef()
geoTransform = ds1.GetGeoTransform()
###Get minx and max y
minx = geoTransform[0]
maxy = geoTransform[3]
###Raster dimensions
xsize = ds1.RasterXSize
ysize = ds1.RasterYSize
maxx = minx + geoTransform[1] * xsize
miny = maxy + geoTransform[5] * ysize
###Warp to same spatial resolution
gdaloptions = {'format': 'MEM', 'xRes': geoTransform[1], 'yRes':
geoTransform[5], 'dstSRS': projection}
ds2w = gdal.Warp('', ds2, **gdaloptions)
ds2 = None
###Translate to same projection
ds2c = gdal.Translate('', ds2w, format='MEM', projWin=[minx, maxy, maxx, miny],
outputSRS=projection)
ds2w = None
ds1c = gdal.Translate('', ds1, format='MEM', projWin=[minx, maxy, maxx, miny],
outputSRS=projection)
ds1 = None
###Check if will create file on disk
if output_name1 is not None or output_name2 is not None:
driver = gdal.GetDriverByName("GTiff")
if output_name1 is None:
output_name1 = 'intersection1.tif'
if output_name2 is None:
output_name2 = 'intersection2.tif'
else:
driver = gdal.GetDriverByName("MEM")
output_name1 = ''
output_name2 = ''
dataset1 = driver.Create(output_name1, xsize, ysize, 1,
ds1c.GetRasterBand(1).DataType)
dataset1.SetGeoTransform(geoTransform)
dataset1.SetProjection(projection)
dataset1.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value
dataset1.GetRasterBand(1).WriteArray(ds1c.GetRasterBand(1).ReadAsArray())
dataset2 = driver.Create(output_name2, xsize, ysize, 1,
ds2c.GetRasterBand(1).DataType)
dataset2.SetGeoTransform(geoTransform)
dataset2.SetProjection(projection)
dataset2.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value
dataset2.GetRasterBand(1).WriteArray(ds2c.GetRasterBand(1).ReadAsArray())
ds1c = None
ds2c = None
return dataset1, dataset2
def raster_absolute_diff(ds1, ds2, nodata1=None, nodata2=None,
output_file=None):
"""Perform image absolute difference (support different extent and projection).
Args:
path1 (string) - path to image 1 (reference)
path2 (string) - path to image 2 (target)
output_dir (string) - path to output files
nodata1 (number) - nodata value of image 1
nodata2 (number) - nodata value of image 2
Returns:
dataset (GDAL dataset): dataset containing absolute difference between
ds1 and ds2.
"""
if output_file is None:
output_file = 'abs_diff.tif'
ds1_intersec, ds2_intersec = raster_intersection(ds1, ds2, nodata1, nodata2,
None, None)
### Read bands with numpy to algebra
nodata = ds1_intersec.GetRasterBand(1).GetNoDataValue()
bandtar = numpy.array(ds1_intersec.GetRasterBand(1).ReadAsArray().astype(float))
fill_bandtar = numpy.where(bandtar == nodata)
bandref = numpy.array(ds2_intersec.GetRasterBand(1).ReadAsArray().astype(float))
fill_bandref = numpy.where(bandref == nodata)
### Get extent from ds1
projection = ds1.GetProjectionRef()
geoTransform = ds1.GetGeoTransform()
[cols, rows] = ds1.GetRasterBand(1).ReadAsArray().shape
ds1 = None
ds2 = None
diff = numpy.abs(bandtar - bandref)
diff[fill_bandtar] = nodata
diff[fill_bandref] = nodata
###Check if will create file on disk
if output_file is not None:
driver = gdal.GetDriverByName("GTiff")
else:
driver = gdal.GetDriverByName("MEM")
output_file = ''
dataset = driver.Create(output_file, rows, cols, 1,
ds1_intersec.GetRasterBand(1).DataType)
dataset.SetGeoTransform(geoTransform)
dataset.SetProjection(projection)
dataset.GetRasterBand(1).SetNoDataValue(nodata)
dataset.GetRasterBand(1).WriteArray(diff)
return dataset
``` |
72,475 | There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes.
Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people)
[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)
[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html)
These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated).
Of course, there's plenty of snakes around.
So the question (obviously) is how can the tribesmen get the snakes off the plain? | 2017/02/28 | ['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/'] | Just ask Moses
==============
From [Artapansus of Alexandria](https://en.wikipedia.org/wiki/Artapanus_of_Alexandria) in his History of the Jews:
>
> Jealousy of Moses' excellent qualities induced Chenephres to send him
> with unskilled troops on a military expedition to Ethiopia, where he
> won great victories. After having built the city of Hermopolis, he
> taught the people the value of the ibis as a protection against the
> serpents, making the bird the sacred guardian spirit of the city...
>
>
>
Behold, your savior
===================
[![enter image description here](https://i.stack.imgur.com/TbKjq.jpg)](https://i.stack.imgur.com/TbKjq.jpg)
Your people worship the Ibis
============================
Not only are [Sacred Ibis](https://en.wikipedia.org/wiki/African_sacred_ibis)' great for keeping around and eating snakes, they are also native to the same plains that the Masai Mara live on, and they are [easy to worship](https://en.wikipedia.org/wiki/Thoth) too!
[![enter image description here](https://i.stack.imgur.com/rWMQ1.jpg)](https://i.stack.imgur.com/rWMQ1.jpg) | Do what any human does and kill them
------------------------------------
Look at human history, you can likely easily name 5 animals off the top of your head that humanity has hunted to extinction. Unless the animals mass breeds like insects, early man has always had dominion over animal life.
If these people truly hated and despised the snakes, to the point that they saw it their religious duty to god to kill them, the snakes wouldn't stand a chance. Humans always win. |
72,475 | There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes.
Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people)
[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)
[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html)
These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated).
Of course, there's plenty of snakes around.
So the question (obviously) is how can the tribesmen get the snakes off the plain? | 2017/02/28 | ['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/'] | Just ask Moses
==============
From [Artapansus of Alexandria](https://en.wikipedia.org/wiki/Artapanus_of_Alexandria) in his History of the Jews:
>
> Jealousy of Moses' excellent qualities induced Chenephres to send him
> with unskilled troops on a military expedition to Ethiopia, where he
> won great victories. After having built the city of Hermopolis, he
> taught the people the value of the ibis as a protection against the
> serpents, making the bird the sacred guardian spirit of the city...
>
>
>
Behold, your savior
===================
[![enter image description here](https://i.stack.imgur.com/TbKjq.jpg)](https://i.stack.imgur.com/TbKjq.jpg)
Your people worship the Ibis
============================
Not only are [Sacred Ibis](https://en.wikipedia.org/wiki/African_sacred_ibis)' great for keeping around and eating snakes, they are also native to the same plains that the Masai Mara live on, and they are [easy to worship](https://en.wikipedia.org/wiki/Thoth) too!
[![enter image description here](https://i.stack.imgur.com/rWMQ1.jpg)](https://i.stack.imgur.com/rWMQ1.jpg) | Why do you have snakes on the plain in the first place? Rodents! So you need to find a way to control the rodent populations. If the snakes have nothing to eat, they won't hang about in large numbers.
Introduce species that will eliminate the rodents and the snakes won't have prey. This is why Bast was an Egyptian Goddess. She represented cats, which kept critters out of the grain cribs. Also weasels and ferrets and mongoose might help. The mongoose will also eat the snakes as well. Then the whole killing snakes becomes a circle of life thing.
Mammals are going to have an advantage in that they are not as affected by cold.
In a culture like you describe, though, I would think the snake might at least be respected because it does help control the rodent population without endangering the food supply. So Sam L Jackson may not be necessary after all. |
72,475 | There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes.
Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people)
[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)
[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html)
These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated).
Of course, there's plenty of snakes around.
So the question (obviously) is how can the tribesmen get the snakes off the plain? | 2017/02/28 | ['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/'] | Just ask Moses
==============
From [Artapansus of Alexandria](https://en.wikipedia.org/wiki/Artapanus_of_Alexandria) in his History of the Jews:
>
> Jealousy of Moses' excellent qualities induced Chenephres to send him
> with unskilled troops on a military expedition to Ethiopia, where he
> won great victories. After having built the city of Hermopolis, he
> taught the people the value of the ibis as a protection against the
> serpents, making the bird the sacred guardian spirit of the city...
>
>
>
Behold, your savior
===================
[![enter image description here](https://i.stack.imgur.com/TbKjq.jpg)](https://i.stack.imgur.com/TbKjq.jpg)
Your people worship the Ibis
============================
Not only are [Sacred Ibis](https://en.wikipedia.org/wiki/African_sacred_ibis)' great for keeping around and eating snakes, they are also native to the same plains that the Masai Mara live on, and they are [easy to worship](https://en.wikipedia.org/wiki/Thoth) too!
[![enter image description here](https://i.stack.imgur.com/rWMQ1.jpg)](https://i.stack.imgur.com/rWMQ1.jpg) | >
> Kookaburra roams through the plains with glee, eating all the snakes
> with a grin is he, laugh, Kookaburra laugh, Kookaburra full your stomach
> must be.
>
>
>
The humble Kookaburra! <https://en.wikipedia.org/wiki/Kookaburra>
A less well known Australian bird who loves to eat snakes and small rodents (solves two suspected problems here!!)
My only problem would be that they would usually nest in a tree, so if there are no suitable trees around, we may have to make a hybrid kingfisher-kookaburra breed which would use the habitat of the kingfisher which is small holes in sand-mounds. |
72,475 | There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes.
Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people)
[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)
[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html)
These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated).
Of course, there's plenty of snakes around.
So the question (obviously) is how can the tribesmen get the snakes off the plain? | 2017/02/28 | ['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/'] | Why do you have snakes on the plain in the first place? Rodents! So you need to find a way to control the rodent populations. If the snakes have nothing to eat, they won't hang about in large numbers.
Introduce species that will eliminate the rodents and the snakes won't have prey. This is why Bast was an Egyptian Goddess. She represented cats, which kept critters out of the grain cribs. Also weasels and ferrets and mongoose might help. The mongoose will also eat the snakes as well. Then the whole killing snakes becomes a circle of life thing.
Mammals are going to have an advantage in that they are not as affected by cold.
In a culture like you describe, though, I would think the snake might at least be respected because it does help control the rodent population without endangering the food supply. So Sam L Jackson may not be necessary after all. | Do what any human does and kill them
------------------------------------
Look at human history, you can likely easily name 5 animals off the top of your head that humanity has hunted to extinction. Unless the animals mass breeds like insects, early man has always had dominion over animal life.
If these people truly hated and despised the snakes, to the point that they saw it their religious duty to god to kill them, the snakes wouldn't stand a chance. Humans always win. |
72,475 | There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes.
Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people)
[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)
[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html)
These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated).
Of course, there's plenty of snakes around.
So the question (obviously) is how can the tribesmen get the snakes off the plain? | 2017/02/28 | ['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/'] | >
> Kookaburra roams through the plains with glee, eating all the snakes
> with a grin is he, laugh, Kookaburra laugh, Kookaburra full your stomach
> must be.
>
>
>
The humble Kookaburra! <https://en.wikipedia.org/wiki/Kookaburra>
A less well known Australian bird who loves to eat snakes and small rodents (solves two suspected problems here!!)
My only problem would be that they would usually nest in a tree, so if there are no suitable trees around, we may have to make a hybrid kingfisher-kookaburra breed which would use the habitat of the kingfisher which is small holes in sand-mounds. | Do what any human does and kill them
------------------------------------
Look at human history, you can likely easily name 5 animals off the top of your head that humanity has hunted to extinction. Unless the animals mass breeds like insects, early man has always had dominion over animal life.
If these people truly hated and despised the snakes, to the point that they saw it their religious duty to god to kill them, the snakes wouldn't stand a chance. Humans always win. |
72,475 | There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes.
Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people)
[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)
[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html)
These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated).
Of course, there's plenty of snakes around.
So the question (obviously) is how can the tribesmen get the snakes off the plain? | 2017/02/28 | ['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/'] | Why do you have snakes on the plain in the first place? Rodents! So you need to find a way to control the rodent populations. If the snakes have nothing to eat, they won't hang about in large numbers.
Introduce species that will eliminate the rodents and the snakes won't have prey. This is why Bast was an Egyptian Goddess. She represented cats, which kept critters out of the grain cribs. Also weasels and ferrets and mongoose might help. The mongoose will also eat the snakes as well. Then the whole killing snakes becomes a circle of life thing.
Mammals are going to have an advantage in that they are not as affected by cold.
In a culture like you describe, though, I would think the snake might at least be respected because it does help control the rodent population without endangering the food supply. So Sam L Jackson may not be necessary after all. | >
> Kookaburra roams through the plains with glee, eating all the snakes
> with a grin is he, laugh, Kookaburra laugh, Kookaburra full your stomach
> must be.
>
>
>
The humble Kookaburra! <https://en.wikipedia.org/wiki/Kookaburra>
A less well known Australian bird who loves to eat snakes and small rodents (solves two suspected problems here!!)
My only problem would be that they would usually nest in a tree, so if there are no suitable trees around, we may have to make a hybrid kingfisher-kookaburra breed which would use the habitat of the kingfisher which is small holes in sand-mounds. |
36,096,018 | This may be a very typical task yet i am having issued cracking a solution for it.
I am using a form which has 2 select options in it
```
<form enctype="multipart/form-data" id="uploadimage" method="post" action="" class="allForms">
<select id="parentCatSel" onchange=listsubcategory(this.value)>
<option value="">Choose category</option>
</select>
<div id="subcatcontainer"><select id="subCatSel"><option value="">Choose Sub category</option></select></div>
<input name="save" class="save" type="submit" id="save" value="Save"/>
</form>
```
Based on the category chosen in "parentCatSel" the "subcatcontainer" is populated with a select option of subcategories
for the chosen parent category
listsubcategory()
returns
```
<select id="subCatSel"><option value="">Choose Sub category</option>
<option value="1">1</option>
<option value="2">2</option></select>
```
the display of subcategory works fine with no errors, however when i try to post the values in the form , i am not able to retrieve the value of chosen option in "subCatSel" as below
```
document.getelement['subCatSel']= null
post['subCatSel'] = null
```
please suggest an alternative. | 2016/03/18 | ['https://Stackoverflow.com/questions/36096018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1332909/'] | Add name attribute to your select inputs.
```
<select id="subCatSel" name="subCatSel"><option value="">Choose Sub category</option>
``` | Sorry guys, my terrible bad of coding in the actual code. I missed out on a quote in the select
just changed that to
it works as wanted!!, thanks everyone |
65,421,043 | I want to create a new table from query result in SSMS:
Query result:
```
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc;
```
How can I create new table from above result:
I have tried
```
select *
into new_table
from (
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc
);
```
I got the error
>
> Msg 102, Level 15, State 1, Line 11 Incorrect syntax near ';'.
>
>
>
Thanks | 2020/12/23 | ['https://Stackoverflow.com/questions/65421043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14875495/'] | I would recommend using [redux toolkit](https://redux-toolkit.js.org/) because it reduces boilerplate code in redux...
With [createSlice](https://redux-toolkit.js.org/api/createSlice) you create Action and Reducer at the same time. And in case of dispatching API calls to the backend and performing suitable state mutations for pending, fulfilled and rejected API calls, [createAsyncThunk](https://redux-toolkit.js.org/api/createAsyncThunk) is the Best!
As per my personal experience, if you are asking this question just for initial learning, then your first setup that you attached as an answer is enough but for a real App, so should definitely go with Redux Toolkit.
You can check this [sandbox](https://codesandbox.io/s/nextjs-demo-gkluc) example | <https://github.com/vercel/next.js/tree/canary/examples/with-redux-wrapper>
cant get any easier than this |
65,421,043 | I want to create a new table from query result in SSMS:
Query result:
```
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc;
```
How can I create new table from above result:
I have tried
```
select *
into new_table
from (
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc
);
```
I got the error
>
> Msg 102, Level 15, State 1, Line 11 Incorrect syntax near ';'.
>
>
>
Thanks | 2020/12/23 | ['https://Stackoverflow.com/questions/65421043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14875495/'] | Assuming you have knowledge in Redux with React.
Firstly, install these packages
`$ npm install next-redux-wrapper react-redux redux redux-thunk --save`
`$ npm install redux-devtools-extension --save-dev`
---
Override or create the default App, create the file `./pages/_app.js` as shown below:
```js
import withRedux from 'next-redux-wrapper'
import { Provider } from 'react-redux'
import { withRouter } from 'next/router'
import App from 'next/app'
import createStore from 'store/createStore'
class MyApp extends App {
render () {
const { Component, pageProps, router, store } = this.props
return (
<Provider store={store}>
<Component router={router} {...pageProps} />
</Provider>
)
}
}
export default withRedux(createStore)(
withRouter(MyApp)
)
```
---
In your pages/component, you can use Redux as you do normally. | <https://github.com/vercel/next.js/tree/canary/examples/with-redux-wrapper>
cant get any easier than this |
65,421,043 | I want to create a new table from query result in SSMS:
Query result:
```
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc;
```
How can I create new table from above result:
I have tried
```
select *
into new_table
from (
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc
);
```
I got the error
>
> Msg 102, Level 15, State 1, Line 11 Incorrect syntax near ';'.
>
>
>
Thanks | 2020/12/23 | ['https://Stackoverflow.com/questions/65421043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14875495/'] | First i created simple next.js app with "npx create-next-app"
Then i installed "npm i redux react-redux redux-thunk redux-devtools-extension
Then I created general redux setup in a folder called "store" and folder structure is like the following image and code is for store.js
[![enter image description here](https://i.stack.imgur.com/Wr5XM.png)](https://i.stack.imgur.com/Wr5XM.png)
Code is for reducer > index.js
[![enter image description here](https://i.stack.imgur.com/dgEAv.png)](https://i.stack.imgur.com/dgEAv.png)
FINALLY created a \_app.js file in pages folder and code is like this
[![enter image description here](https://i.stack.imgur.com/VxhJh.png)](https://i.stack.imgur.com/VxhJh.png)
If anyone still have question about setup please let me know... | <https://github.com/vercel/next.js/tree/canary/examples/with-redux-wrapper>
cant get any easier than this |
65,421,043 | I want to create a new table from query result in SSMS:
Query result:
```
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc;
```
How can I create new table from above result:
I have tried
```
select *
into new_table
from (
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc
);
```
I got the error
>
> Msg 102, Level 15, State 1, Line 11 Incorrect syntax near ';'.
>
>
>
Thanks | 2020/12/23 | ['https://Stackoverflow.com/questions/65421043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14875495/'] | Assuming you have knowledge in Redux with React.
Firstly, install these packages
`$ npm install next-redux-wrapper react-redux redux redux-thunk --save`
`$ npm install redux-devtools-extension --save-dev`
---
Override or create the default App, create the file `./pages/_app.js` as shown below:
```js
import withRedux from 'next-redux-wrapper'
import { Provider } from 'react-redux'
import { withRouter } from 'next/router'
import App from 'next/app'
import createStore from 'store/createStore'
class MyApp extends App {
render () {
const { Component, pageProps, router, store } = this.props
return (
<Provider store={store}>
<Component router={router} {...pageProps} />
</Provider>
)
}
}
export default withRedux(createStore)(
withRouter(MyApp)
)
```
---
In your pages/component, you can use Redux as you do normally. | I would recommend using [redux toolkit](https://redux-toolkit.js.org/) because it reduces boilerplate code in redux...
With [createSlice](https://redux-toolkit.js.org/api/createSlice) you create Action and Reducer at the same time. And in case of dispatching API calls to the backend and performing suitable state mutations for pending, fulfilled and rejected API calls, [createAsyncThunk](https://redux-toolkit.js.org/api/createAsyncThunk) is the Best!
As per my personal experience, if you are asking this question just for initial learning, then your first setup that you attached as an answer is enough but for a real App, so should definitely go with Redux Toolkit.
You can check this [sandbox](https://codesandbox.io/s/nextjs-demo-gkluc) example |
65,421,043 | I want to create a new table from query result in SSMS:
Query result:
```
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc;
```
How can I create new table from above result:
I have tried
```
select *
into new_table
from (
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc
);
```
I got the error
>
> Msg 102, Level 15, State 1, Line 11 Incorrect syntax near ';'.
>
>
>
Thanks | 2020/12/23 | ['https://Stackoverflow.com/questions/65421043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14875495/'] | I would recommend using [redux toolkit](https://redux-toolkit.js.org/) because it reduces boilerplate code in redux...
With [createSlice](https://redux-toolkit.js.org/api/createSlice) you create Action and Reducer at the same time. And in case of dispatching API calls to the backend and performing suitable state mutations for pending, fulfilled and rejected API calls, [createAsyncThunk](https://redux-toolkit.js.org/api/createAsyncThunk) is the Best!
As per my personal experience, if you are asking this question just for initial learning, then your first setup that you attached as an answer is enough but for a real App, so should definitely go with Redux Toolkit.
You can check this [sandbox](https://codesandbox.io/s/nextjs-demo-gkluc) example | Here is my simplest way, you can follow it.
<https://github.com/imimran/next-redux-example> |
65,421,043 | I want to create a new table from query result in SSMS:
Query result:
```
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc;
```
How can I create new table from above result:
I have tried
```
select *
into new_table
from (
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc
);
```
I got the error
>
> Msg 102, Level 15, State 1, Line 11 Incorrect syntax near ';'.
>
>
>
Thanks | 2020/12/23 | ['https://Stackoverflow.com/questions/65421043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14875495/'] | Assuming you have knowledge in Redux with React.
Firstly, install these packages
`$ npm install next-redux-wrapper react-redux redux redux-thunk --save`
`$ npm install redux-devtools-extension --save-dev`
---
Override or create the default App, create the file `./pages/_app.js` as shown below:
```js
import withRedux from 'next-redux-wrapper'
import { Provider } from 'react-redux'
import { withRouter } from 'next/router'
import App from 'next/app'
import createStore from 'store/createStore'
class MyApp extends App {
render () {
const { Component, pageProps, router, store } = this.props
return (
<Provider store={store}>
<Component router={router} {...pageProps} />
</Provider>
)
}
}
export default withRedux(createStore)(
withRouter(MyApp)
)
```
---
In your pages/component, you can use Redux as you do normally. | First i created simple next.js app with "npx create-next-app"
Then i installed "npm i redux react-redux redux-thunk redux-devtools-extension
Then I created general redux setup in a folder called "store" and folder structure is like the following image and code is for store.js
[![enter image description here](https://i.stack.imgur.com/Wr5XM.png)](https://i.stack.imgur.com/Wr5XM.png)
Code is for reducer > index.js
[![enter image description here](https://i.stack.imgur.com/dgEAv.png)](https://i.stack.imgur.com/dgEAv.png)
FINALLY created a \_app.js file in pages folder and code is like this
[![enter image description here](https://i.stack.imgur.com/VxhJh.png)](https://i.stack.imgur.com/VxhJh.png)
If anyone still have question about setup please let me know... |
65,421,043 | I want to create a new table from query result in SSMS:
Query result:
```
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc;
```
How can I create new table from above result:
I have tried
```
select *
into new_table
from (
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc
);
```
I got the error
>
> Msg 102, Level 15, State 1, Line 11 Incorrect syntax near ';'.
>
>
>
Thanks | 2020/12/23 | ['https://Stackoverflow.com/questions/65421043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14875495/'] | Assuming you have knowledge in Redux with React.
Firstly, install these packages
`$ npm install next-redux-wrapper react-redux redux redux-thunk --save`
`$ npm install redux-devtools-extension --save-dev`
---
Override or create the default App, create the file `./pages/_app.js` as shown below:
```js
import withRedux from 'next-redux-wrapper'
import { Provider } from 'react-redux'
import { withRouter } from 'next/router'
import App from 'next/app'
import createStore from 'store/createStore'
class MyApp extends App {
render () {
const { Component, pageProps, router, store } = this.props
return (
<Provider store={store}>
<Component router={router} {...pageProps} />
</Provider>
)
}
}
export default withRedux(createStore)(
withRouter(MyApp)
)
```
---
In your pages/component, you can use Redux as you do normally. | Here is my simplest way, you can follow it.
<https://github.com/imimran/next-redux-example> |
65,421,043 | I want to create a new table from query result in SSMS:
Query result:
```
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc;
```
How can I create new table from above result:
I have tried
```
select *
into new_table
from (
select table1.col1, table1.col2, table2.col3
from table1
inner join table2 on table1.col1 = table2.col1
order by col1 asc
);
```
I got the error
>
> Msg 102, Level 15, State 1, Line 11 Incorrect syntax near ';'.
>
>
>
Thanks | 2020/12/23 | ['https://Stackoverflow.com/questions/65421043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14875495/'] | First i created simple next.js app with "npx create-next-app"
Then i installed "npm i redux react-redux redux-thunk redux-devtools-extension
Then I created general redux setup in a folder called "store" and folder structure is like the following image and code is for store.js
[![enter image description here](https://i.stack.imgur.com/Wr5XM.png)](https://i.stack.imgur.com/Wr5XM.png)
Code is for reducer > index.js
[![enter image description here](https://i.stack.imgur.com/dgEAv.png)](https://i.stack.imgur.com/dgEAv.png)
FINALLY created a \_app.js file in pages folder and code is like this
[![enter image description here](https://i.stack.imgur.com/VxhJh.png)](https://i.stack.imgur.com/VxhJh.png)
If anyone still have question about setup please let me know... | Here is my simplest way, you can follow it.
<https://github.com/imimran/next-redux-example> |
12,636,300 | hello everyone i am unable to recieve asynchronous message using active mq, below code which i am using for publish message and subscribe it.
```
public class publishMessage extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
InitialContext initCtx = new InitialContext();
Context envContext = (Context) initCtx.lookup("java:comp/env");
ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) envContext.lookup("jms/ConnectionFactory");
Connection connection = connectionFactory.createConnection();
connection.start() ;
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("jms/topic/MyQueue");
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT) ;
TextMessage msg=session.createTextMessage();
msg.setText("Message sent");
System.out.println("Message Sent");
producer.send(msg);
session.commit() ;
connection.close() ;
}catch(Exception ex){
ex.printStackTrace() ;
}
}}
class Consumer{
protected Queue queue;
protected String queueName = "jms/topic/MyQueue";
protected String url = ActiveMQConnection.DEFAULT_BROKER_URL;
protected int ackMode = Session.AUTO_ACKNOWLEDGE;
public static void main(String[] args) {
Consumer rec=new Consumer();
try {
rec.run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() throws JMSException{
System.out.println("URL:" + url);
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
TopicConnection connection = (TopicConnection)connectionFactory.createTopicConnection();
connection.setClientID("Testingconn1") ;
connection.start();
MessageConsumer consumer = null;
Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
queue = session.createQueue(queueName) ;
consumer = session.createConsumer(queue);
consumer.setMessageListener(new MyListener()) ;
session.commit() ;
consumer.close();
session.close();
connection.close();
}
}
package com.java;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class MyListener implements MessageListener{
@Override
public void onMessage( final Message message )
{
if ( message instanceof TextMessage )
{
final TextMessage textMessage = (TextMessage) message;
try
{
System.out.println("Listener:" + textMessage.getText() );
}
catch (final JMSException e)
{
e.printStackTrace();
}
}
}
}
```
when i am executing the above code, publisher successfully send a message and the output comes as required when i start my consumer, no output comes into my console.
pl help me to resolve it or suggest a code to receive async message. | 2012/09/28 | ['https://Stackoverflow.com/questions/12636300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1565086/'] | Shell globbing?
```
cp -r J* /path/to/other/dir
``` | ```
cp -r J* /destination/path/
```
the -r option lets you copy directories recursively |
368,914 | I'm lost on where to start on this proof:
Using the fact that $A^m A^n = A^{m+n}$ , prove the identity
$F\_m F\_n + F\_{m−1} F\_{n−1} = F\_{m+n−1}$
I want to use induction starting with n = 1, but would I also have to make m = 1? I haven't done induction with 2 variables before.
or because of $A^m A^n = A^{m+n}$ should I setup the problem as a matrix (in that case what would the columns/rows be)?
I tried doing it mathematically however I think my algebra is wrong so I won't post it here. Am I correct to believe that $F\_{m-1} = F\_m\*-1$ is not the same as $2^{n+1} = 2^n\*2$?
Any help would be appreciated, thanks. | 2013/04/22 | ['https://math.stackexchange.com/questions/368914', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66788/'] | You can actually use induction here. We induct on $n$ proving that the relation holds for all $m$ at each step of the way. For $n=2$, $F\_1 = F\_2 =1$ and the identity $F\_m+F\_{m-1}=F\_{m+1}$ is true for all $m$ by the definition of the Fibonacci sequence. We now have a strong induction hypothesis that the identity holds for values up until $n$, for all $m$. To show that it holds for $n+1$, for all $m$ we note that
$$
F\_m F\_{n+1} + F\_{m-1} F\_n = F\_m(F\_{n-1} + F\_n) + F\_{m-1}(F\_{n-2} + F\_{n-1}) =
$$
$$
(F\_mF\_n+F\_{m-1}F\_{n-1}) + (F\_mF\_{n-1} + F\_{m-1}F\_{n-2}) = F\_{m+n-1} + F\_{m+n-2} = F\_{m+n}.
$$
This completes the induction. | Fibonacci numbers have a [matrix representation](http://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form):
$$\left( \begin{smallmatrix} F\_{n+1} & F\_n \\ F\_n & F\_{n-1}\end{smallmatrix} \right) = \left( \begin{smallmatrix} 1 & 1 \\ 1 & 0 \end{smallmatrix}\right)^n$$
This is probably what you were meant to use for this problem. |
368,914 | I'm lost on where to start on this proof:
Using the fact that $A^m A^n = A^{m+n}$ , prove the identity
$F\_m F\_n + F\_{m−1} F\_{n−1} = F\_{m+n−1}$
I want to use induction starting with n = 1, but would I also have to make m = 1? I haven't done induction with 2 variables before.
or because of $A^m A^n = A^{m+n}$ should I setup the problem as a matrix (in that case what would the columns/rows be)?
I tried doing it mathematically however I think my algebra is wrong so I won't post it here. Am I correct to believe that $F\_{m-1} = F\_m\*-1$ is not the same as $2^{n+1} = 2^n\*2$?
Any help would be appreciated, thanks. | 2013/04/22 | ['https://math.stackexchange.com/questions/368914', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66788/'] | You can actually use induction here. We induct on $n$ proving that the relation holds for all $m$ at each step of the way. For $n=2$, $F\_1 = F\_2 =1$ and the identity $F\_m+F\_{m-1}=F\_{m+1}$ is true for all $m$ by the definition of the Fibonacci sequence. We now have a strong induction hypothesis that the identity holds for values up until $n$, for all $m$. To show that it holds for $n+1$, for all $m$ we note that
$$
F\_m F\_{n+1} + F\_{m-1} F\_n = F\_m(F\_{n-1} + F\_n) + F\_{m-1}(F\_{n-2} + F\_{n-1}) =
$$
$$
(F\_mF\_n+F\_{m-1}F\_{n-1}) + (F\_mF\_{n-1} + F\_{m-1}F\_{n-2}) = F\_{m+n-1} + F\_{m+n-2} = F\_{m+n}.
$$
This completes the induction. | Hint: If $$v\_{n}=\left[ \begin{array} {c} F\_{n+1} \\ F\_{n}\end{array}\right]$$Then:$$F\_{m}F\_{n}+F\_{m-1}F\_{n-1}=\langle v\_{m-1},v\_{n-1}\rangle$$where $\langle \cdot, \cdot \rangle$ is the standard inner product on $\mathbb{R}^2$. This along with Vadim123's hint should get the job done. |
106,460 | I have a system which triggers a backup on repeated frequency and/or disk fill. For the the repeat frequency, my form shows the following (same field repeated in one image):
[![enter image description here](https://i.stack.imgur.com/Se3aa.jpg)](https://i.stack.imgur.com/Se3aa.jpg)
You can select a different values in the 'every' dropdown and it will show other options as pictured.
What is a better approach? I cannot find another user interface which asks for a similar input and I designed this one as I wanted. | 2017/03/29 | ['https://ux.stackexchange.com/questions/106460', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/99190/'] | The problem comes when you specify a pattern rather than an interval.
Technically, it's the period you want to set, not the frequency. Frequency being the number of occurrences of a repeating event per unit time vs period as the duration of time of one cycle.
When you specify a pattern like every X at Y you have to say things like:
* every day at time T
* every week but on day D, at time T
* every month but on day n at time T
The event occurs when the pattern is matched.
When you specify an interval you say things like
* every N days starting at time T
* every N weeks starting at time T
* every N months starting at time T
The event occurs when the interval elapses.
So with intervals you only ever have to specify the same pair of values:
* the interval (N + unit)
* when to start (for which NOW might be an option)
[bvckup](https://bvckup2.com/) is an awesome backup tool that uses exactly this structure:
[![enter image description here](https://i.stack.imgur.com/wZxzi.png)](https://i.stack.imgur.com/wZxzi.png) | To provide an example of a robust way to schedule a task I'd look at programs made for it - A tried and tested example is Microsoft Outlook. It's not pretty, but neither is our calendar, nor the way humans like to schedule things.
[![Example image](https://i.stack.imgur.com/ZxZi3.jpg)](https://i.stack.imgur.com/ZxZi3.jpg)
Some things to learn from this scheduler about common schedules:
* the 31st doesn't exist every month, consider including a 'last' option
* day of the week often trumps time of the month for long tasks. I'd much rather have my backup task run on the last saturday when I'm away than the last day of a month
* Time could have an AM/PM (dependant on locale)
* someone might want to schedule it twice a week or more so checkboxes to select the days can be useful
* every day on weekdays only
* every 2 months
* this isn't included in Outlook, but the Windows task scheduler also has an option to sync a task across time zones if the task requires it. All depends on your requirements
and always check with your users to see what they want to be able to do or see. I think your example would be more than enough for many people and use cases |
45,932,788 | I created a SharePoint Framework Webpart.
I call a webservice that returns some data from sharepoint (terms from termstore), and for each term i generate an html that display the term. On the onclick of each term i want to call a typescript function, passing the term as parameters, to get its children terms.
This code below create the following wrong behaviour: when the webpart is displayed, it automatically calls the function this.readIterm when I didnt even click on it !
Am I missing something or by design doing it the wrong way ? I tried to replace onclick="${this.readIterm(term)}" by onclick="readIterm($(term))" but it does nothing.
***Code below***
```
terms.forEach(term => {
htmlContent +=
`<div class="w3-card w3-third w3-margin-bottom" style="" onclick="${this.readIterm(term)}">
<header class="w3-container w3-blue">
<h1>Header</h1>
</header>
<div class="w3-container">
<span>${term.name}</p>
</div>
<footer class="w3-container w3-blue">
<h5>Footer</h5>
</footer>
</div>`
```
This html is then added to this.domElement.innerHTML, displaying it in the webpart.
`public readIterm(myTerm: ITerm) {
alert("readIterm is clicked");
}`
Thank you in advance for your help and guidance if I do not follow best practice !
Jeff | 2017/08/29 | ['https://Stackoverflow.com/questions/45932788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8191909/'] | There is one more way to attach event listener.
Refer below code sample. This works perfectly for me:
(Note: This is a basic idea. You can refer this code and make changes to yours accordingly.)
```
public render(): void{
this.domElement.innerHTML = ` <div class="form-group">
<button class="btn btn-success" id="btnReadAllItems">
<span class="ms-Button-label">Read All Items</span>
</button>
<button class="btn btn-success" id="btnReadItemById">
<span class="ms-Button-label">Read Item By Id</span>
</button>
</div>`;
this._setButtonEventHandlers();
}
private _setButtonEventHandlers(): void {
const webPart: SpfxCrudWebPart = this;
this.domElement.querySelector('#btnReadAllItems').addEventListener('click', () => {
this._GetListItemsNF();
});
}
private _GetListItemsNF(): void {
//
//
//
}
```
**Another way is as below. (But you will have to make some changes according to your code)**
```
public render(): void{
htmlContent +=
`<div class="w3-card w3-third w3-margin-bottom" id="test">
<header class="w3-container w3-blue">
<h1>Header</h1>
</header>
<div class="w3-container">
<span>${term.name}</p>
</div>
<footer class="w3-container w3-blue">
<h5>Footer</h5>
</footer>
</div>`
}
this._setButtonEventHandlers();
this.myTerm = term; // Here we are assigning value to the `myTerm` variable. And `myTerm` is a public property, So value of `myTerm` will be accessible using `this.myTerm`
}
public myTerm: ITerm; // here we are declaring `myTerm` variable
public readIterm():void{
// here you can access the cariable `myTerm` using `this.myTerm`.
// alert(this.myTerm);
// alert("readIterm is clicked");
}
private _setButtonEventHandlers(): void {
this.domElement.querySelector('#test').addEventListener('click', () => { this.readIterm(); });
}
``` | Rather onClick instead of onclick. Then check to make sure that you get into your "readIterm" method by calling the console (console.log). |
20,621,868 | I'm trying to import a large amount of data into a flat table using CSV. During the import BigQuery reports:
```
- File: 0 / Line:6659 / Field:11: Could not parse '' as a timestamp
```
In the schema I have 2 timestamps: fields 4 and 11 . Both are nullable. For the second timestamp the row entry on field 11 is indeed null.
Is it supposed to work like this or do I need to send it as "0" ? | 2013/12/16 | ['https://Stackoverflow.com/questions/20621868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3108981/'] | Note the difference between a null value and an empty string. Line 6659 copied above has empty strings, but not nulls.
To reproduce, I created a table with this schema:
```
[{"name":"a","type":"TIMESTAMP","mode":"NULLABLE"},
{"name":"b","type":"TIMESTAMP","mode":"NULLABLE"}]
```
Then uploaded this file to it:
```
"",""
```
Where I got this error:
```
File: 0 / Line:1 / Field:1, Could not parse '' as a timestamp
```
But if I upload this file:
```
,
```
Everything works fine, as there are 2 nulls surrounding that comma.
You can either transform all your files, getting rid of the empty strings, or import those columns to BigQuery as string, and run an ETL from string to timestamp inside BigQuery. | I had similar problem like this
The error was
```
- File: 2 / Line:9940 / Field:13: Day 0-0-0 does not exist for
timestamp: 0000-00-00 00:00:00
"9718470";"2769586jfghjkdf";"2015-08-03 15:57:28";"2015-08-03 16:10:10";"479";"128833308";"May 2015";"1461782";"ab_20150616";"1130567689";"69466";"emailid@hotmail.com";"0000-00-00 00:00:00";"2015-08-03 23:53:44"
```
The 13th field was TIMESTAMP in my BigQuery Schema, and I was sending "0000-00-00 00:00:00" .
Big Query doesn't accept "0000-00-00 00:00:00".
To solve this problem I send
```
"9718470";"2769586jfghjkdf";"2015-08-03 15:57:28";"2015-08-03 16:10:10";"479";"128833308";"May 2015";"1461782";"ab_20150616";"1130567689";"69466";"emailid@hotmail.com";;"2015-08-03 23:53:44"
```
In short you have to send **"someValue";;"someOtherValue"** instead of
"someValue";"0000-00-00 00:00:00";"someOtherValue or "someValue";"";"someOtherValue
Please note , I am using ; as delimiter. |
62,075,043 | Very new to Flutter and Dart, so pardon me for the ill-phrased question.
This is a generic code that I have:
```
// Constructor class
class ctr {
String i;
ctr(String a){
this.a = a;
}
// New variables based on contsructor
var ctrA = ctr('a');
var ctrB = ctr('b');
var ctrC = ctr('c');
// Storing the variables based on constructor in an array
List ctrList = [ctrA, ctrB, ctrC]
void main() {
String match = 'ctrB';
for (var i = 0; i<ctrList.length; i++) {
if(match == ctrList.toString() {
print('The string of your match is ${ctrList[i].a}');
} else {
print('Error!);
}
}
}
```
The current output is `Error!`.
Instead, what I'm looking for is `a`.
As you can see, I'm trying to iterate the variable `match` over the array that stores the variables based on an aforementioned constructor, and if it matches, print out the value in the constructor that it has matched to. `runtimeType` can only get me the name of the origin Class (which will be `ctr`).
I tried to convert the variable name by using `toString()` but that didn't work either. What I need is a method to convert these variable names to a string and get a match, but I'm not sure what I can do.
Thanks in advance for the help! | 2020/05/28 | ['https://Stackoverflow.com/questions/62075043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9234811/'] | Unlike previous suggestion, you should use `pdfplumber.open` instead of `pdfplumber.load`! [The link](https://github.com/jsvine/pdfplumber) for the repo of pdfplumber.
>
> Warning: pdfplumber.load is deprecated.Please use pdfplumber.open
> (with same arguments) instead.
>
>
>
Hence, the below code extracts entire pages rather than the first page in addition to using `pdfplumber.open` method.
```
import urllib3
import pdfplumber
import io
def extract_pdf_by_url(url):
http = urllib3.PoolManager()
temp = io.BytesIO()
temp.write(http.request("GET", url).data)
all_text = ''
with pdfplumber.open(temp) as pdf:
for pdf_page in pdf.pages:
single_page_text = pdf_page.extract_text()
all_text = all_text + '\n' + single_page_text
return all_text
url = 'https://raw.githubusercontent.com/jsvine/pdfplumber/stable/examples/pdfs/background-checks.pdf'
text = extract_pdf_by_url(url)
print(text)
``` | Here is an example, which uses `io.BytesIO()` instead of creating any files on the hard drive.
Note that `pdfplumber.load(...)` is used instead of `pdfplumber.open(...)`.
```
import urllib3
import pdfplumber
import io
def read_pdf(url: str) -> str:
http = urllib3.PoolManager()
temp = io.BytesIO()
temp.write(http.request("GET", url).data)
with pdfplumber.load(temp) as pdf:
text = pdf.pages[0].extract_text()
return text
text = read_pdf('https://sample.com/test.pdf')
``` |
52,837,952 | What I am trying to do is as follows:
I am taking few elements of an array, comparing them with a fixed value and trying to create a vector out of it.
Here is a piece of code:
```
architecture behav of main_ent is
...
type f_array is array(0 to 8) of std_logic_vector(7 downto 0);
signal ins_f_array: f_array;
signal sel_sig_cmd : std_logic_vector(3 downto 0);
...
process begin
sel_sig_cmd <= ((ins_f_array(4) = x"3A")&(ins_f_array(3)= x"3A")&(ins_f_array(2)= x"3A")&(ins_f_array(1)= x"3A"));
....
end process;
...
```
This should give something like **sel\_sig\_cmd = 1000** or may be **1011 etc**. But this is not working. Is there any alternative to this code?
cheers
Tahir | 2018/10/16 | ['https://Stackoverflow.com/questions/52837952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9547499/'] | This is because the = function in VHDL returns a boolean, not a std\_logic.
In VHDL '93, there is no tidy way to do this, other than set each bit manually:
```
sel_sig_cmd(3) <= '1' when (ins_f_array(4) = x"3A") else '0'
sel_sig_cmd(2) <= '1' when (ins_f_array(3) = x"3A") else '0'
-- etc
```
but in VHDL 2008, there are the relational operators (?= ?/= etc), that return std\_logic on compare. So your code becomes:
```
sel_sig_cmd <= ( (ins_f_array(4) ?= x"3A")
& (ins_f_array(3) ?= x"3A")
& (ins_f_array(2) ?= x"3A")
& (ins_f_array(1) ?= x"3A") );
``` | The answer from Tricky is a good one to follow. However, if you want to implement it in a process, then the process can be rewritten as follows :
```
architecture behav of main_ent is
...
type f_array is array(0 to 8) of std_logic_vector(7 downto 0);
signal ins_f_array: f_array;
signal sel_sig_cmd : std_logic_vector(3 downto 0);
...
process(ins_f_array(4 downto 1)) begin
if ((ins_f_array(4) = x"3A")&(ins_f_array(3)= x"3A")&
(ins_f_array(2)= x"3A")&(ins_f_array(1)= x"3A")) then
sel_sig_cmd <= "XXXX" -- Enter your desired value
....
end process;
...
```
This process would be tedious though as it has to cover all the 16 possibilities of the "if condition".
Another implementation is to use an if condition for each bit as follows :
```
architecture behav of main_ent is
...
type f_array is array(0 to 8) of std_logic_vector(7 downto 0);
signal ins_f_array: f_array;
signal sel_sig_cmd : std_logic_vector(3 downto 0);
...
process(ins_f_array(4 downto 1)) begin
if (ins_f_array(4) = x"3A") then
sel_sig_cmd(3) <= "X" -- Enter your desired value
else
sel_sig_cmd(3) <= "X" -- Enter your desired value
end if;
-- Repeat for other bits
....
end process;
...
``` |
52,837,952 | What I am trying to do is as follows:
I am taking few elements of an array, comparing them with a fixed value and trying to create a vector out of it.
Here is a piece of code:
```
architecture behav of main_ent is
...
type f_array is array(0 to 8) of std_logic_vector(7 downto 0);
signal ins_f_array: f_array;
signal sel_sig_cmd : std_logic_vector(3 downto 0);
...
process begin
sel_sig_cmd <= ((ins_f_array(4) = x"3A")&(ins_f_array(3)= x"3A")&(ins_f_array(2)= x"3A")&(ins_f_array(1)= x"3A"));
....
end process;
...
```
This should give something like **sel\_sig\_cmd = 1000** or may be **1011 etc**. But this is not working. Is there any alternative to this code?
cheers
Tahir | 2018/10/16 | ['https://Stackoverflow.com/questions/52837952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9547499/'] | This is because the = function in VHDL returns a boolean, not a std\_logic.
In VHDL '93, there is no tidy way to do this, other than set each bit manually:
```
sel_sig_cmd(3) <= '1' when (ins_f_array(4) = x"3A") else '0'
sel_sig_cmd(2) <= '1' when (ins_f_array(3) = x"3A") else '0'
-- etc
```
but in VHDL 2008, there are the relational operators (?= ?/= etc), that return std\_logic on compare. So your code becomes:
```
sel_sig_cmd <= ( (ins_f_array(4) ?= x"3A")
& (ins_f_array(3) ?= x"3A")
& (ins_f_array(2) ?= x"3A")
& (ins_f_array(1) ?= x"3A") );
``` | You can overload the "=" operator :
```
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity tb is
end entity;
architecture behav of tb is
function "=" (Left, Right: std_logic_vector) return std_logic is
begin
if (Left = Right) then
return '1';
else
return '0';
end if;
end function "=";
type f_array is array(0 to 8) of std_logic_vector(7 downto 0);
signal ins_f_array: f_array := (x"00",x"01",x"02",x"03",x"04",x"05",x"06",x"07",x"08");
signal sel_sig_cmd : std_logic_vector(3 downto 0);
begin
process (ins_f_array(1 to 4)) begin
sel_sig_cmd <= ((ins_f_array(4) = x"3A")&(ins_f_array(3) = x"3A")&(ins_f_array(2) = x"3A")&(ins_f_array(1) = x"3A"));
end process;
process
begin
wait for 10 us;
for i in 0 to 8 loop
ins_f_array(i) <= std_logic_vector(unsigned(ins_f_array(i)) + 1);
end loop;
end process;
end architecture;
``` |
52,837,952 | What I am trying to do is as follows:
I am taking few elements of an array, comparing them with a fixed value and trying to create a vector out of it.
Here is a piece of code:
```
architecture behav of main_ent is
...
type f_array is array(0 to 8) of std_logic_vector(7 downto 0);
signal ins_f_array: f_array;
signal sel_sig_cmd : std_logic_vector(3 downto 0);
...
process begin
sel_sig_cmd <= ((ins_f_array(4) = x"3A")&(ins_f_array(3)= x"3A")&(ins_f_array(2)= x"3A")&(ins_f_array(1)= x"3A"));
....
end process;
...
```
This should give something like **sel\_sig\_cmd = 1000** or may be **1011 etc**. But this is not working. Is there any alternative to this code?
cheers
Tahir | 2018/10/16 | ['https://Stackoverflow.com/questions/52837952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9547499/'] | The answer from Tricky is a good one to follow. However, if you want to implement it in a process, then the process can be rewritten as follows :
```
architecture behav of main_ent is
...
type f_array is array(0 to 8) of std_logic_vector(7 downto 0);
signal ins_f_array: f_array;
signal sel_sig_cmd : std_logic_vector(3 downto 0);
...
process(ins_f_array(4 downto 1)) begin
if ((ins_f_array(4) = x"3A")&(ins_f_array(3)= x"3A")&
(ins_f_array(2)= x"3A")&(ins_f_array(1)= x"3A")) then
sel_sig_cmd <= "XXXX" -- Enter your desired value
....
end process;
...
```
This process would be tedious though as it has to cover all the 16 possibilities of the "if condition".
Another implementation is to use an if condition for each bit as follows :
```
architecture behav of main_ent is
...
type f_array is array(0 to 8) of std_logic_vector(7 downto 0);
signal ins_f_array: f_array;
signal sel_sig_cmd : std_logic_vector(3 downto 0);
...
process(ins_f_array(4 downto 1)) begin
if (ins_f_array(4) = x"3A") then
sel_sig_cmd(3) <= "X" -- Enter your desired value
else
sel_sig_cmd(3) <= "X" -- Enter your desired value
end if;
-- Repeat for other bits
....
end process;
...
``` | You can overload the "=" operator :
```
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity tb is
end entity;
architecture behav of tb is
function "=" (Left, Right: std_logic_vector) return std_logic is
begin
if (Left = Right) then
return '1';
else
return '0';
end if;
end function "=";
type f_array is array(0 to 8) of std_logic_vector(7 downto 0);
signal ins_f_array: f_array := (x"00",x"01",x"02",x"03",x"04",x"05",x"06",x"07",x"08");
signal sel_sig_cmd : std_logic_vector(3 downto 0);
begin
process (ins_f_array(1 to 4)) begin
sel_sig_cmd <= ((ins_f_array(4) = x"3A")&(ins_f_array(3) = x"3A")&(ins_f_array(2) = x"3A")&(ins_f_array(1) = x"3A"));
end process;
process
begin
wait for 10 us;
for i in 0 to 8 loop
ins_f_array(i) <= std_logic_vector(unsigned(ins_f_array(i)) + 1);
end loop;
end process;
end architecture;
``` |
69,934,658 | Sorry for the lousy text in the question? I can't come up with a summarized way to ask this question.
I have a dataframe (variable df) such as the below:
```
df
```
| ID | A | B | C |
| --- | --- | --- | --- |
| 1 | m | nan | nan |
| 2 | n | nan | nan |
| 3 | b | nan | nan |
| 1 | nan | t | nan |
| 2 | nan | e | nan |
| 3 | nan | r | nan |
| 1 | nan | nan | y |
| 2 | nan | nan | u |
| 3 | nan | nan | i |
The desired output is:
| ID | A | B | C |
| --- | --- | --- | --- |
| 1 | m | t | y |
| 2 | n | e | u |
| 3 | b | r | i |
I solved this by running the following lines:
```
new_df = pd.DataFrame()
for column in df.columns:
new_df = pd.concat([new_df, df[column].dropna()], join='outer', axis=1)
```
And then I figured this would be faster:
```
empty_dict = {}
for column in df.columns:
empty_dict[column] = df[column].dropna()
new_df = pd.DataFrame.from_dict(empty_dict)
```
However, the dropna could represent a problem if, for example, there is a missing value in the rows that have the values to be used in each column. E.g. if df.loc[2,'A'] = nan, then that key in the dictionary will only have 2 values causing a misalignment with the rest of the columns. I'm not convinced.
I have the feeling pandas must have a builtin function that will do a better job and either of my two solutions. Is there? If not, is there any better way of solving this? | 2021/11/11 | ['https://Stackoverflow.com/questions/69934658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10608268/'] | Looks like you only need `groupby().first()`:
```
df.groupby('ID', as_index=False).first()
```
Output:
```
ID A B C
0 1 m t y
1 2 n e u
2 3 b r i
``` | Use `stack_unstack()` as suggested by @QuangHoang if `ID` is the index:
```
>>> df.stack().unstack().reset_index()
A B C
ID
1 m t y
2 n e u
3 b r i
```
You can use `melt` and `pivot`:
```
>>> df.melt('ID').dropna().pivot('ID', 'variable', 'value') \
.rename_axis(columns=None).reset_index()
ID A B C
0 1 m t y
1 2 n e u
2 3 b r i
``` |
42,156,145 | am writing a hook to a function using the basic x86 method of inserting a jump worth 5 bytes. My code is rusty but I think i have the logic. I get a segmentation fault error when I run against LD\_PRELOAD env var. Am basically using a replacement function, hook func, trampoline function to modify and return the original address. Below is the code link.
**foo.h**
```
#ifndef foo_h__
#define foo_h__
extern void foo(const char*);
#endif // foo_h_
```
**foo.c**
```
#include <stdio.h>
void foo(const char*str)
{
puts(str);
}
```
**main.c**
```
#include <stdio.h>
#include "foo.h"
int main(void)
{const char*str="I am a shared lib!\n";
int count=1;
puts("This is a shared library test...");
while(count!=200){
printf("%d time!\n",count);
foo(str);
count++;
}
return 0;
}
```
**hook.c**
```
# include <stdio.h>
# include <unistd.h>
# define __USE_GNU
# include <dlfcn.h>
# include <stdint.h>
# include <sys/mman.h>
const char*str = "Hooked! ma fucker!\n";
struct hookdata
{
int64_t*origFunc;
int64_t*newFunc;
const char*s;
void (*foo_trampoline)(const char*str);
}*hkd;
void fooHooked(const char*str)
{
puts(str);
hkd->foo_trampoline(hkd->s);
}
void hook(void)
{
//Get pointers to the original and new functions and calculate the jump offset
hkd->origFunc = dlsym(RTLD_NOW, "foo");
hkd->newFunc = (int64_t*) &fooHooked;
int64_t offset = hkd->newFunc - (hkd->origFunc + 5);
//Make the memory containing the original funcion writable
//Code from http://stackoverflow.com/questions/20381812/mprotect-always-returns-invalid-arguments
size_t pageSize = sysconf(_SC_PAGESIZE);
uintptr_t start = (uintptr_t) hkd->origFunc;
uintptr_t end = start + 1;
uintptr_t pageStart = start & -pageSize;
mprotect((void *) pageStart, end - pageStart,
PROT_READ | PROT_WRITE | PROT_EXEC);
//Insert the jump instruction at the beginning of the original function
int32_t instruction = 0xe9 | offset << 8;
*hkd->origFunc = instruction;
}
void foo(const char*str)
{
if (*hkd->origFunc == 0xe9)
{
printf("hook detected!");
}
else
hook();
}
``` | 2017/02/10 | ['https://Stackoverflow.com/questions/42156145', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6423730/'] | You can pass it as null. It's mentioned in the doc also
>
> inCertificate is the Object which is holding Certificate Information.
> Pass this as null if no client certificate is used by the merchant (as
> given above in the Prerequisites section)
>
>
> | I suggest you to use PGSDK 2.0 instead of old version which is not required any **Client side certificate**
```
----------
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
PaytmButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
getPaytmWindow() ;
}
} );
}
}
private void getPaytmWindow(String checksum) {
//use PaytmPGService Service = PaytmPGService.getProductionService();in production//
PaytmPGService Service = PaytmPGService.getStagingService();
//Kindly create complete Map and checksum on your server side and then put it here in paramMap.
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put( "MID", abc14146028455452" );
paramMap.put( "ORDER_ID", "GTR6079" );
paramMap.put( "CUST_ID", "1132" );
paramMap.put( "INDUSTRY_TYPE_ID", "Retail" );
paramMap.put( "CHANNEL_ID", "WAP" );
paramMap.put( "TXN_AMOUNT", "76" );
paramMap.put( "WEBSITE", "APP_STAGING" );
paramMap.put( "EMAIL", "test@gmail.com" );
paramMap.put( "MOBILE_NO", "7777777777" );
paramMap.put( "CALLBACK_URL", "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp" );
paramMap.put( "CHECKSUMHASH", "DkrZCCNCKS0h4IbLEk8HWqTClr6PCK/+Zh3xyW7fXfOsfHsmhmt3/wGx5pxgWrCSNCObPHyYFE3VJob0v7QQdkBFNyNAO7CR2+e2BiVgQpM=" );
PaytmOrder Order = new PaytmOrder( paramMap );
Service.initialize( Order, null );
Service.startPaymentTransaction( this, true, true,
new PaytmPaymentTransactionCallback() {
@Override
public void someUIErrorOccurred(String inErrorMessage) {
// Some UI Error Occurred in Payment Gateway Activity.
// // This may be due to initialization of views in
// Payment Gateway Activity or may be due to //
// initialization of webview. // Error Message details
// the error occurred.
Log.d( "LOG123444", "someUIErrorOccurred : " + inErrorMessage );
}
@Override
public void onTransactionResponse(Bundle inResponse) {
Log.d( "LOG123444", "Payment Transaction : " + inResponse );
if (inResponse.getString( "STATUS" ).contains( "TXN_SUCCESS" ))
{
Toast.makeText(getApplicationContext(),"Transaction completed",Toast.LENGTH_LONG).show();
}
Log.i( "LOG123444", inResponse.getString( "STATUS" ) );
// Toast.makeText( getApplicationContext(), "Payment Transaction response " + inResponse.toString(), Toast.LENGTH_LONG ).show();
}
@Override
public void networkNotAvailable() {
// If network is not
// available, then this
// method gets called.
}
@Override
public void clientAuthenticationFailed(String inErrorMessage) {
// This method gets called if client authentication
// failed. // Failure may be due to following reasons //
// 1. Server error or downtime. // 2. Server unable to
// generate checksum or checksum response is not in
// proper format. // 3. Server failed to authenticate
// that client. That is value of payt_STATUS is 2. //
// Error Message describes the reason for failure.
Log.i( "LOG123444", "clientAuthenticationFailed " + inErrorMessage );
}
@Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
Log.i( "LOG", "inErrorMessage " + inErrorMessage );
Log.i( "LOG", "inFailingUrl " + inFailingUrl );
}
// had to be added: NOTE
@Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
@Override
public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
Log.d( "LOG", "Payment Transaction Failed " + inErrorMessage );
Toast.makeText( getBaseContext(), "Payment Transaction Failed ", Toast.LENGTH_LONG ).show();
}
} );
}
``` |
21,644,400 | I am using the django-autoslug package with a project and, though the documentation is simple enough, I cannot get it to populate the database field with the slug.
models.py
```
class Thread(models.Model):
forum = models.ForeignKey(Forum)
title = models.CharField(max_length=100)
date_created = models.DateTimeField('date created')
user = models.ForeignKey(User)
slug = AutoSlugField(populate_from='title')
```
I have also tried overriding the save() method with both an `AutoSlugField` and a regular `SlugField`, but this did not work either.
```
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Thread, self).save(*args, **kwargs)
```
For example, when I create a thread with the title "This should create a slug", I would expect the "slug" field in the database to be populated with "this-should-create-a-slug". Instead, it is only being populate with an empty string: ''
Does anyone know what might cause this? I have not been able to find documentation of any similar issues with either the django-autoslug package or just overriding the save() method with a regular `SlugField` | 2014/02/08 | ['https://Stackoverflow.com/questions/21644400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2626646/'] | ```
File file[] = Environment.getExternalStorageDirectory().listFiles();
recursiveFileFind(file);
public void recursiveFileFind(File[] file1){
int i = 0;
String filePath="";
if(file1!=null){
while(i!=file1.length){
filePath = file1[i].getAbsolutePath();
if(file1[i].isDirectory()){
File file[] = file1[i].listFiles();
recursiveFileFind(file);
}
i++;
//Log.d(i+"", filePath);
}
}
}
```
>
> If this is not work then in below code u can give external path and
>
>
> get all files.
> ==============
>
>
>
```
private void getAllFilesOfDir(File directory) {
Log.d(TAG, "Directory: " + directory.getAbsolutePath() + "\n");
final File[] files = directory.listFiles();
if ( files != null ) {
for ( File file : files ) {
if ( file != null ) {
if ( file.isDirectory() ) { // it is a folder...
getAllFilesOfDir(file);
}
else { // it is a file...
Log.d(TAG, "File: " + file.getAbsolutePath() + "\n");
}
}
}
}
}
``` | This code will give internal files.
```
String[] SavedFiles;
ArrayList<String> arrList;
SavedFiles = getApplicationContext().fileList();
arrList = new ArrayList<String>();
if(SavedFiles != null)
{
for(int i=0; i<SavedFiles.length; i++)
{
arrList.add(SavedFiles[i]);
}
}
``` |
328,753 | I know this is a longshot but I was wondering if anyone knows if this is possible. | 2008/11/30 | ['https://Stackoverflow.com/questions/328753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | Most browsers set the [HTTP\_REFERRER](http://en.wikipedia.org/wiki/Referer) header to the current URL when requesting a linked document. However, it can be spoofed so don't use it for security. | I know nothing about air.
But if AIR has JavaScript access, and you can access the container document ( [How do I share a javascript object between different pages in Adobe AIR?](https://stackoverflow.com/questions/193130/how-do-i-share-a-javascript-object-between-different-pages-in-adobe-air) ) then all you need to work out is how to obtain Document.location from it. |
328,753 | I know this is a longshot but I was wondering if anyone knows if this is possible. | 2008/11/30 | ['https://Stackoverflow.com/questions/328753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | Most browsers set the [HTTP\_REFERRER](http://en.wikipedia.org/wiki/Referer) header to the current URL when requesting a linked document. However, it can be spoofed so don't use it for security. | I reckon this is rather late, but since I was searching for the same information 3 years later, here it goes.
[LoaderInfo.loaderUrl](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/LoaderInfo.html#loaderURL) should give you the information you are after.
HTH! |
50,032,109 | I'm trying to create a script that will list the servers I need to list along with the latency returned from each server, I need the list to be in ascending or descending order based on ping.
What I've come up with so far has given basically what I want, but if the ping returned is above 100 on one server, the other values are considered to be higher if they start with a value higher than 1.
I understand that I need the ping value returned as an integer, but I haven't been able to figure out exactly how to accomplish that with out removing the server name.
Anyway, here's what I've come up with so far
```
function TestNetwork {
$global:array = @("<ServerName>:<ipaddress>"; "<ServerName>:<ipaddress>"; "<ServerName>:<ipaddress>")
foreach ($str in $global:array) {
$avg = 0
$server = $($str -split ":")[0]
$PingServer = Test-Connection -Count 3 $server
$avg = ($PingServer | Measure-Object ResponseTime -Average)
$calc = [System.Math]::Round($avg.Average)
$output = "{000} | " -f $($calc) + $server
$Output
}
}
TestNetwork | Sort numerical -Descending `
```
and here are the results I get
```
75 | Server
73 | Server
110 | Server
``` | 2018/04/25 | ['https://Stackoverflow.com/questions/50032109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9631948/'] | There are several ways to address your problem.
You could [format](http://social.technet.microsoft.com/wiki/contents/articles/7855.using-the-f-format-operator-in-powershell.aspx) the number in a way that aligns integer sort order and string sort order as [LotPings suggested](https://stackoverflow.com/questions/50032109/how-do-i-sort-a-string-by-its-numerical-value-in-powershell#comment87081424_50032109):
```
'{0,3} | {1}' -f $calc, $server
```
You could also extract the number from the string, convert it back to an integer, and use that as the sorting property:
```
... | Sort-Object {[int]($_ -replace '(\d+).*', '$1')} -Descending
```
However, I wouldn't advise either approach. The PoSh way of doing things is to work with objects as [Olaf pointed out](https://stackoverflow.com/questions/50032109/how-do-i-sort-a-string-by-its-numerical-value-in-powershell#comment87080444_50032109), so wrap your data in custom objects and convert them to strings only if you have a reason to do so (e.g. to create text output):
```
foreach ($str in $global:array) {
...
New-Object -Type PSObject -Property ([ordered]@{
'ComputerName' = $server
'ResponseTime' = $calc
})
}
```
That way you can "naturally" sort your data:
```
TestNetwork | Sort ResponseTime -Descending | ForEach-Object {
'{0,3} | {1}' -f $_.ResponseTime, $_.ComputerName
}
```
or
```
TestNetwork | Sort ResponseTime -Descending | Export-Csv 'output.csv' -NoType
``` | Here is an alternative to the way you are doing things that will give output that can be sorted and formatted more easily:
```
function Test-Network
{
$array = ("<ServerName>","<ipaddress>"), ("<ServerName>","<ipaddress>"), ("<ServerName>","<ipaddress>")
$array | ForEach-Object {
[PsCustomObject]@{
AvgResponse = [Math]::Round((Test-Connection -Count 3 $_[0] | Measure-Object ResponseTime -Average).Average)
Server = $_[0]
}
}
}
Test-Network |
Sort-Object AvgResponse -Descending
```
Output will look like this:
```
AvgResponse Server
----------- ------
363 server1
12 server2
2 server3
```
The nice thing about outputting custom objects like this rather than strings is that you can then use further PowerShell techniques on the output, such as sorting, grouping, etc.
Note a couple of other points:
* Unless you intend to use your array outside the function, there is no need to declare it as 'global'
* Unless you really need the names in the format `"<ServerName>:<ipaddress>"`, consider storing them differently. I've used an array of arrays, which makes it easier to work with in this case as you avoid having to split a string each time.
* You should name your functions according to the PowerShell Verb-Noun naming standard, so `Test-Network`, rather than `TestNetwork`. |
50,032,109 | I'm trying to create a script that will list the servers I need to list along with the latency returned from each server, I need the list to be in ascending or descending order based on ping.
What I've come up with so far has given basically what I want, but if the ping returned is above 100 on one server, the other values are considered to be higher if they start with a value higher than 1.
I understand that I need the ping value returned as an integer, but I haven't been able to figure out exactly how to accomplish that with out removing the server name.
Anyway, here's what I've come up with so far
```
function TestNetwork {
$global:array = @("<ServerName>:<ipaddress>"; "<ServerName>:<ipaddress>"; "<ServerName>:<ipaddress>")
foreach ($str in $global:array) {
$avg = 0
$server = $($str -split ":")[0]
$PingServer = Test-Connection -Count 3 $server
$avg = ($PingServer | Measure-Object ResponseTime -Average)
$calc = [System.Math]::Round($avg.Average)
$output = "{000} | " -f $($calc) + $server
$Output
}
}
TestNetwork | Sort numerical -Descending `
```
and here are the results I get
```
75 | Server
73 | Server
110 | Server
``` | 2018/04/25 | ['https://Stackoverflow.com/questions/50032109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9631948/'] | Here is an alternative to the way you are doing things that will give output that can be sorted and formatted more easily:
```
function Test-Network
{
$array = ("<ServerName>","<ipaddress>"), ("<ServerName>","<ipaddress>"), ("<ServerName>","<ipaddress>")
$array | ForEach-Object {
[PsCustomObject]@{
AvgResponse = [Math]::Round((Test-Connection -Count 3 $_[0] | Measure-Object ResponseTime -Average).Average)
Server = $_[0]
}
}
}
Test-Network |
Sort-Object AvgResponse -Descending
```
Output will look like this:
```
AvgResponse Server
----------- ------
363 server1
12 server2
2 server3
```
The nice thing about outputting custom objects like this rather than strings is that you can then use further PowerShell techniques on the output, such as sorting, grouping, etc.
Note a couple of other points:
* Unless you intend to use your array outside the function, there is no need to declare it as 'global'
* Unless you really need the names in the format `"<ServerName>:<ipaddress>"`, consider storing them differently. I've used an array of arrays, which makes it easier to work with in this case as you avoid having to split a string each time.
* You should name your functions according to the PowerShell Verb-Noun naming standard, so `Test-Network`, rather than `TestNetwork`. | Cast string to integer
```
TestNetwork | Sort {[int]($_.numerical)} -Descending
``` |
50,032,109 | I'm trying to create a script that will list the servers I need to list along with the latency returned from each server, I need the list to be in ascending or descending order based on ping.
What I've come up with so far has given basically what I want, but if the ping returned is above 100 on one server, the other values are considered to be higher if they start with a value higher than 1.
I understand that I need the ping value returned as an integer, but I haven't been able to figure out exactly how to accomplish that with out removing the server name.
Anyway, here's what I've come up with so far
```
function TestNetwork {
$global:array = @("<ServerName>:<ipaddress>"; "<ServerName>:<ipaddress>"; "<ServerName>:<ipaddress>")
foreach ($str in $global:array) {
$avg = 0
$server = $($str -split ":")[0]
$PingServer = Test-Connection -Count 3 $server
$avg = ($PingServer | Measure-Object ResponseTime -Average)
$calc = [System.Math]::Round($avg.Average)
$output = "{000} | " -f $($calc) + $server
$Output
}
}
TestNetwork | Sort numerical -Descending `
```
and here are the results I get
```
75 | Server
73 | Server
110 | Server
``` | 2018/04/25 | ['https://Stackoverflow.com/questions/50032109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9631948/'] | There are several ways to address your problem.
You could [format](http://social.technet.microsoft.com/wiki/contents/articles/7855.using-the-f-format-operator-in-powershell.aspx) the number in a way that aligns integer sort order and string sort order as [LotPings suggested](https://stackoverflow.com/questions/50032109/how-do-i-sort-a-string-by-its-numerical-value-in-powershell#comment87081424_50032109):
```
'{0,3} | {1}' -f $calc, $server
```
You could also extract the number from the string, convert it back to an integer, and use that as the sorting property:
```
... | Sort-Object {[int]($_ -replace '(\d+).*', '$1')} -Descending
```
However, I wouldn't advise either approach. The PoSh way of doing things is to work with objects as [Olaf pointed out](https://stackoverflow.com/questions/50032109/how-do-i-sort-a-string-by-its-numerical-value-in-powershell#comment87080444_50032109), so wrap your data in custom objects and convert them to strings only if you have a reason to do so (e.g. to create text output):
```
foreach ($str in $global:array) {
...
New-Object -Type PSObject -Property ([ordered]@{
'ComputerName' = $server
'ResponseTime' = $calc
})
}
```
That way you can "naturally" sort your data:
```
TestNetwork | Sort ResponseTime -Descending | ForEach-Object {
'{0,3} | {1}' -f $_.ResponseTime, $_.ComputerName
}
```
or
```
TestNetwork | Sort ResponseTime -Descending | Export-Csv 'output.csv' -NoType
``` | Cast string to integer
```
TestNetwork | Sort {[int]($_.numerical)} -Descending
``` |
11,824,664 | Is there a way to render background texture with alpha in a webpage? I want to have texture on top of a gradient so I can see through it.
I'm not using canvas for this (although I do use canvas for some other animation effect) | 2012/08/06 | ['https://Stackoverflow.com/questions/11824664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335999/'] | You can achieve that with CSS3 Multiple Backgrounds and CSS3 Gradients. Here is a [good article](http://snook.ca/archives/html_and_css/multiple-bg-css-gradients "CSS Backgrounds and Gradients") on the subject.
**Edit**: To clarify, you basically need to just define two backgrounds on the object. First one would be the gradient while the second would be the alpha texture. | You could just use a big div as background and add the gradient and the png inside the div and then use css to resize and position |
11,824,664 | Is there a way to render background texture with alpha in a webpage? I want to have texture on top of a gradient so I can see through it.
I'm not using canvas for this (although I do use canvas for some other animation effect) | 2012/08/06 | ['https://Stackoverflow.com/questions/11824664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335999/'] | You can achieve that with CSS3 Multiple Backgrounds and CSS3 Gradients. Here is a [good article](http://snook.ca/archives/html_and_css/multiple-bg-css-gradients "CSS Backgrounds and Gradients") on the subject.
**Edit**: To clarify, you basically need to just define two backgrounds on the object. First one would be the gradient while the second would be the alpha texture. | You don't need CSS3 for this. Use a seamless background tile on `html` and an alpha gradient on the `body`.
```
html {background: #fff url(path/to/bg-tile.png) repeat 0 0;}
body {background: transparent url(path/to/gradient.png) repeat-x 0 0;}
```
[Multiple background images are not supported in IE<9](http://caniuse.com/#feat=multibackgrounds) |
11,824,664 | Is there a way to render background texture with alpha in a webpage? I want to have texture on top of a gradient so I can see through it.
I'm not using canvas for this (although I do use canvas for some other animation effect) | 2012/08/06 | ['https://Stackoverflow.com/questions/11824664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335999/'] | You don't need CSS3 for this. Use a seamless background tile on `html` and an alpha gradient on the `body`.
```
html {background: #fff url(path/to/bg-tile.png) repeat 0 0;}
body {background: transparent url(path/to/gradient.png) repeat-x 0 0;}
```
[Multiple background images are not supported in IE<9](http://caniuse.com/#feat=multibackgrounds) | You could just use a big div as background and add the gradient and the png inside the div and then use css to resize and position |
65,119,282 | Assuming I had this result of `print_r` below `Array ( [0] => 10 [1] => 11 )` which is the result of months within a specific year *october* and *november*. I wonder how to return true if the array return in correctly order months until December example => `Array ( [0] => 8 [1] => 9 [2] => 10 [3] => 11 [4] => 12)` . and return false if array not in orderly months for example => `Array ( [0] => 2 [1] => 3 [2] => 10 [3] => 12` <-- months is skipping.
```
$sql4 = "SELECT monthClose
FROM tblAccAccountClosing
WHERE yearClose = '".$yearClose."'
AND settingType = 'month'
AND STATUS = 'open' ";
$GetResult4 = $pdo->FetchData($sql4, $pdo->DEFAULT_PDO_CONNECTIONS);
while ($row4 = $GetResult4->fetch()){
$monthsArray[] = $row4['monthClose'];
}
print_r ($monthsArray);
```
* There is no min on month, it could be start from any months.
* There is no duplicate data will return.
* Some example here.
```js
Array ( [0] => 9 [1] => 10 [2] => 11 ) --> return false (because result not until 12)
Array ( [0] => 1 [1] => 2 [2] => 10 [3] => 12 ) --> return false
Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 6 ) --> return false
Array ( [0] => 1 [1] => 12 ) --> return false
Array ( [0] => 7 [1] => 8 [2] => 9 [3] => 10 [4] => 11 [5] => 12) --> return true
Array ( [0] => 11 [1] => 12 ) --> return true
Array ( [0] => 12 ) --> return true
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 [10] => 11 [11] => 12) --> return true
```
Appreciate your help. | 2020/12/03 | ['https://Stackoverflow.com/questions/65119282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11393883/'] | A little hesitant to post an answer because the requirements for determining validity are vague but from your comments these are invalid:
* 3,4,6 (missing 5)
* 3,4,4,5 (duplicate 4)
* 0,1 (0 is invalid)
* 10,11,12,13 (13 is invalid)
* 9,10,11 (invalid because 12 is missing)
<http://sandbox.onlinephpfunctions.com/code/8967ae95c5751a8a75a1187d0470b6f527278453>
```
<?php
function areMonthsValid(array $input)
{
// Input is invalid if it contains < 1 or > 12
if (min($input) < 1 || max($input) > 12) {
return false;
}
// This is used as the source to compare against and we assume it is right.
// It will have a range of numbers starting from the min to 12.
$template = range(min($input), 12);
// Now, compare the 2 arrays and see if there are any differences.
// If there are differences you know that $input has a different list than $template.
// The order of these arrays matters.
// Empty = no differences
return empty(array_diff($template, $input));
// Using `array_diff` will not fail on [10,10,11,12]
// If you want that to fail, you can count the array values.
// return count($template) === count($input);
}
var_dump(areMonthsValid([3,10])); // false
var_dump(areMonthsValid([3,4,5,6])); // false
var_dump(areMonthsValid([3,10])); // false
var_dump(areMonthsValid([3,5,6])); // false
var_dump(areMonthsValid([3,5,5,6])); // false
var_dump(areMonthsValid([-2,-1,0,1])); // false
var_dump(areMonthsValid([10,11,12,13])); // false
var_dump(areMonthsValid([10,11,12])); // true
``` | Try this solution:
```
function isValidOrder(array $array): bool {
$prevElement = $array[0] - 1;
foreach($array as $element) {
if (($prevElement + 1) !== $element) {
return false;
}
$prevElement++;
}
return true;
}
``` |
65,119,282 | Assuming I had this result of `print_r` below `Array ( [0] => 10 [1] => 11 )` which is the result of months within a specific year *october* and *november*. I wonder how to return true if the array return in correctly order months until December example => `Array ( [0] => 8 [1] => 9 [2] => 10 [3] => 11 [4] => 12)` . and return false if array not in orderly months for example => `Array ( [0] => 2 [1] => 3 [2] => 10 [3] => 12` <-- months is skipping.
```
$sql4 = "SELECT monthClose
FROM tblAccAccountClosing
WHERE yearClose = '".$yearClose."'
AND settingType = 'month'
AND STATUS = 'open' ";
$GetResult4 = $pdo->FetchData($sql4, $pdo->DEFAULT_PDO_CONNECTIONS);
while ($row4 = $GetResult4->fetch()){
$monthsArray[] = $row4['monthClose'];
}
print_r ($monthsArray);
```
* There is no min on month, it could be start from any months.
* There is no duplicate data will return.
* Some example here.
```js
Array ( [0] => 9 [1] => 10 [2] => 11 ) --> return false (because result not until 12)
Array ( [0] => 1 [1] => 2 [2] => 10 [3] => 12 ) --> return false
Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 6 ) --> return false
Array ( [0] => 1 [1] => 12 ) --> return false
Array ( [0] => 7 [1] => 8 [2] => 9 [3] => 10 [4] => 11 [5] => 12) --> return true
Array ( [0] => 11 [1] => 12 ) --> return true
Array ( [0] => 12 ) --> return true
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 [10] => 11 [11] => 12) --> return true
```
Appreciate your help. | 2020/12/03 | ['https://Stackoverflow.com/questions/65119282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11393883/'] | A little hesitant to post an answer because the requirements for determining validity are vague but from your comments these are invalid:
* 3,4,6 (missing 5)
* 3,4,4,5 (duplicate 4)
* 0,1 (0 is invalid)
* 10,11,12,13 (13 is invalid)
* 9,10,11 (invalid because 12 is missing)
<http://sandbox.onlinephpfunctions.com/code/8967ae95c5751a8a75a1187d0470b6f527278453>
```
<?php
function areMonthsValid(array $input)
{
// Input is invalid if it contains < 1 or > 12
if (min($input) < 1 || max($input) > 12) {
return false;
}
// This is used as the source to compare against and we assume it is right.
// It will have a range of numbers starting from the min to 12.
$template = range(min($input), 12);
// Now, compare the 2 arrays and see if there are any differences.
// If there are differences you know that $input has a different list than $template.
// The order of these arrays matters.
// Empty = no differences
return empty(array_diff($template, $input));
// Using `array_diff` will not fail on [10,10,11,12]
// If you want that to fail, you can count the array values.
// return count($template) === count($input);
}
var_dump(areMonthsValid([3,10])); // false
var_dump(areMonthsValid([3,4,5,6])); // false
var_dump(areMonthsValid([3,10])); // false
var_dump(areMonthsValid([3,5,6])); // false
var_dump(areMonthsValid([3,5,5,6])); // false
var_dump(areMonthsValid([-2,-1,0,1])); // false
var_dump(areMonthsValid([10,11,12,13])); // false
var_dump(areMonthsValid([10,11,12])); // true
``` | Maybe you can try this solution
```
function isValidSequence(array $sequence) {
for($i=0; $i < count($sequence) - 1; ++$i) {
if ($sequence[$i+1] !== ($sequence[$i] + 1)) {
//if not in sequence
return false;
}
}
//return true if on sequence or only one element
return true;
}
``` |
67,631,531 | I need to write a script to "validate" email addresses by taking user input and checking that the string is separated into 2 segments by an '@' symbol (it's honestly pointless - I know).
I can figure out validating the '@' symbol, but I can't seem to figure out how to implement this to validate that the '@' separates the string into 2 segments. I honestly don't know where to start.
```
print ("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
print ("\n Welcome to my Email Address Validator!")
print (" You can use this tool to check the validation of email addresses.")
print("\n Please input the email address that you would like to validate.")
print ("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
def email_check():
address = str(input("\n Email Address: "))
if "@" in address:
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
print ("\n This is a valid email address!")
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
return email_check()
else:
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
print ("\n This is an invalid email address!\n No @ symbol identified!")
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
return email_check()
email_check()
``` | 2021/05/21 | ['https://Stackoverflow.com/questions/67631531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15861303/'] | Probably the simplest way to handle this is by using a regular expression (regex), as although it is possible with raw Python (namely by using str.split() and checking the returned values) your code will be much harder to parse.
Here is a regex that should only match with valid email addresses:
```
^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$
```
You can use [this](https://www.regextester.com/) tool to test that against your cases. It also offers explanations for each component of the expression when you hover over them.
And in use:
```
import re
def valid_email(address):
valid_email_regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
if not re.search(valid_email_regex, address):
return False
return True
``` | You can use str.split() and maybe use regular expressions.
<https://www.geeksforgeeks.org/python-string-split/>
However, instead of checking if there are spaces in email address, simply find and delete them using str.split(' ') and create valid email. |
67,631,531 | I need to write a script to "validate" email addresses by taking user input and checking that the string is separated into 2 segments by an '@' symbol (it's honestly pointless - I know).
I can figure out validating the '@' symbol, but I can't seem to figure out how to implement this to validate that the '@' separates the string into 2 segments. I honestly don't know where to start.
```
print ("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
print ("\n Welcome to my Email Address Validator!")
print (" You can use this tool to check the validation of email addresses.")
print("\n Please input the email address that you would like to validate.")
print ("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
def email_check():
address = str(input("\n Email Address: "))
if "@" in address:
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
print ("\n This is a valid email address!")
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
return email_check()
else:
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
print ("\n This is an invalid email address!\n No @ symbol identified!")
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
return email_check()
email_check()
``` | 2021/05/21 | ['https://Stackoverflow.com/questions/67631531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15861303/'] | Probably the simplest way to handle this is by using a regular expression (regex), as although it is possible with raw Python (namely by using str.split() and checking the returned values) your code will be much harder to parse.
Here is a regex that should only match with valid email addresses:
```
^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$
```
You can use [this](https://www.regextester.com/) tool to test that against your cases. It also offers explanations for each component of the expression when you hover over them.
And in use:
```
import re
def valid_email(address):
valid_email_regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
if not re.search(valid_email_regex, address):
return False
return True
``` | You can use regular expressions to check if the String has an '@' symbol in the middle:
```
import re
address = str(input("\n Email Address: "))
if(re.match('.+@.+', address)):
print("address has '@' in the middle")
```
`.+@.+` is a regular expression that checks if the String has 1 or more characters (`.+`) before and after the symbol '@'.
To check if the String does not contain whitespaces, simply use the `not in` operator:
```
if(' ' not in address):
print("address does not contain whitespaces")
``` |
56,455,406 | After adding $table->engine = 'MyISAM'; seem foreign key is not working anymore. This my main table
```
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'MyISAM';
$table->integer('id');
$table->string('user_id',20);
$table->string('name');
$table->primary(['user_id','id']);
$table->rememberToken();
$table->timestamps();
});
DB::statement('ALTER TABLE users CHANGE id id INT(11) NOT NULL
AUTO_INCREMENT');
}
```
Foreign key table
```
public function up()
{
Schema::create('useraccesses', function (Blueprint $table) {
$table->increments('id');
$table->string('user_id',20);
$table->datetime('accessTime')->nullable();
$table->datetime('quittime')->nullable();
$table->datetime('activeHour')->nullable();
$table->text('token')->nullable();
$table->foreign('user_id')
->references('user_id')->on('users')
->onDelete('cascade');
$table->timestamps();
});
}
```
Thanks | 2019/06/05 | ['https://Stackoverflow.com/questions/56455406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10939437/'] | Change Jquery
```
$('li.has-ul a').click(function() {
$(this).parent().find('.sub-ul').slideToggle(500);
$(this).parent().toggleClass('active');
/*event.preventDefault();*/
});
```
<https://jsfiddle.net/lalji1051/kp8x4e7w/4/> | I hope this will help you.
```
$('li.has-ul a').click(function() {
$(this).siblings('.sub-ul').slideToggle(500);
$(this).parent().toggleClass('active');
event.preventDefault();
});
``` |
25,342,121 | I have the following (intended to be valid) XML:
```
<Series>
<A>
<id>1</id>
</A>
<B>
<id>1</id>
</B>
<B>
<id>1</id>
</B>
<B>
<id>2</id>
</B>
</Series>
```
Using XSD 1.1 and XPath 2.0, I want to assert the maximum number of elements named "B" that share the same "id" value as "A". Specifically, I want to limit the number of elements of name "B" that can have "id"=1, to specifically 2 occurrences. I don't care how many elements named B there are with other "id" values that don't match A's id="1" (so there could be a million of `<B><id>2</id></B>`, and it would still validate.
Here's my attempted XML Schema 1.1 to enforce this, with an XPath 2.0 expression in the assert directive:
```
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Series" type="series"/>
<xs:complexType name="series">
<xs:sequence>
<xs:element name="A" type="a"/>
<xs:element name="B" type="b" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="a">
<xs:sequence>
<xs:element name="id" type="xs:string"/>
</xs:sequence>
<xs:assert test="count(following-sibling::element(B)[id/text() = ./id/text()]) eq 2"/>
</xs:complexType>
<xs:complexType name="b">
<xs:sequence>
<xs:element name="id" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
```
But my assertion always fails with a cvc assertion error message. If I try to relax the assert to just `<xs:assert test="count(following-sibling::element(B)) ge 1"/>`, it still fails, so it seems like XML Schema 1.1 can't handle all XPath 2.0 constructs?
In general, is there a way to make assertions on a sibling in XML Schema 1.1? Thank you! | 2014/08/16 | ['https://Stackoverflow.com/questions/25342121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1336944/'] | XML Schema 1.1 assertions *can* handle all of XPath 2.0, but according to the spec ([section 3.13.4](http://www.w3.org/TR/xmlschema11-1/#assertion-validation))
>
> 1.3 From the "partial" ·post-schema-validation infoset·, a data model instance is constructed as described in [XDM]. The root node of the [XDM] instance is constructed from E; **the data model instance contains only that node and nodes constructed from the [attributes], [children], and descendants of E.**
>
>
> Note: It is a consequence of this construction that **attempts to refer, in an assertion, to the siblings or ancestors of E, or to any part of the input document outside of E itself, will be unsuccessful**. Such attempted references are not in themselves errors, but the data model instance used to evaluate them does not include any representation of any parts of the document outside of E, so they cannot be referred to.
>
>
>
(My bold). When evaluating an assertion you only have the sub tree rooted at the element that hosts the assertion, so if you want to assert a relation between elements in different parts of the tree you must put the assertion on one of their common ancestors.
I presume it was designed like this to allow a validating parser to evaluate assertions during parsing, at the end of the relevant element, rather than having to wait until the whole tree has been built and then evaluating all assertions en masse. | I found an answer to the question of how to control the number of permissible siblings. The key was to not put the assert within the sibling's type, but in the parent. The assert clause was also changed because of this to:
`every $aid in child::element(A)/id satisfies (count(child::element(B)[child::id = $aid]) le 2)`. As for the more general question I posed at the end about making assertions on a sibling in XSD 1.1, I haven't started to figure that out.
```
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Series" type="series"/>
<xs:complexType name="series">
<xs:sequence>
<xs:element name="A" type="a"/>
<xs:element name="B" type="b" maxOccurs="unbounded"/>
</xs:sequence>
<xs:assert test="every $aid in child::element(A)/id satisfies (count(child::element(B)[child::id = $aid]) le 2)"/>
</xs:complexType>
<xs:complexType name="a">
<xs:sequence>
<xs:element name="id" type="xs:string"/
</xs:sequence>
</xs:complexType>
<xs:complexType name="b">
<xs:sequence>
<xs:element name="id" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
``` |
22,296,301 | I was wondering what is the best way to add a border to my elements without extending its dimensions.
As far as I know, there are two ways to achieve it: `box-sizing:border-box;` and an inset `box-shadow`. Which one is wise to use and why? | 2014/03/10 | ['https://Stackoverflow.com/questions/22296301', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1211785/'] | Well `box-shadow` isn't a border, it's a shadow, so this question pretty much answers itself.
If you wish to add a border without increasing an element's dimensions, you'd use `box-sizing: border-box`, as this is what it's designed for.
From [the specification](http://www.w3.org/TR/2004/CR-css3-ui-20040511/#box-sizing):
>
> The specified width and height (and respective min/max properties) on this element determine the border box of the element. That is, any padding or border specified on the element is laid out and drawn inside this specified width and height.
>
>
>
Do note, however, that Firefox only supports the prefixed version: `-moz-box-sizing: ...`. | I would suggest to use `box-sixing:border-box;` because it's not affecting the content of the element in connection to a usual CSS border. An inset-shadow might overlap the contents. In addition to that there's a better browser support for `box-sizing:border-box` like Mathias commented. |
22,296,301 | I was wondering what is the best way to add a border to my elements without extending its dimensions.
As far as I know, there are two ways to achieve it: `box-sizing:border-box;` and an inset `box-shadow`. Which one is wise to use and why? | 2014/03/10 | ['https://Stackoverflow.com/questions/22296301', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1211785/'] | I would suggest to use `box-sixing:border-box;` because it's not affecting the content of the element in connection to a usual CSS border. An inset-shadow might overlap the contents. In addition to that there's a better browser support for `box-sizing:border-box` like Mathias commented. | The official way of course is to use `box-sizing: border-box`. This will include both the border and the padding in the width and height of the element.
If you use a shadow with a spread distance, you can get the same effect as a border, except that the shadow is not part of the dimensions of the element, so it may overlap content outside the element for a regular shadow and content inside the element if using an `inset` shadow. It will also differ from using `box-sizing` in that any padding will increase the size of the element.
An advantage of using a `box-shadow` is that you can achieve [multiple faux-borders](http://dropshado.ws/post/1592190942/multiple-borders-with-box-shadow). You can’t do this with the regular `border` property. |
22,296,301 | I was wondering what is the best way to add a border to my elements without extending its dimensions.
As far as I know, there are two ways to achieve it: `box-sizing:border-box;` and an inset `box-shadow`. Which one is wise to use and why? | 2014/03/10 | ['https://Stackoverflow.com/questions/22296301', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1211785/'] | Well `box-shadow` isn't a border, it's a shadow, so this question pretty much answers itself.
If you wish to add a border without increasing an element's dimensions, you'd use `box-sizing: border-box`, as this is what it's designed for.
From [the specification](http://www.w3.org/TR/2004/CR-css3-ui-20040511/#box-sizing):
>
> The specified width and height (and respective min/max properties) on this element determine the border box of the element. That is, any padding or border specified on the element is laid out and drawn inside this specified width and height.
>
>
>
Do note, however, that Firefox only supports the prefixed version: `-moz-box-sizing: ...`. | The official way of course is to use `box-sizing: border-box`. This will include both the border and the padding in the width and height of the element.
If you use a shadow with a spread distance, you can get the same effect as a border, except that the shadow is not part of the dimensions of the element, so it may overlap content outside the element for a regular shadow and content inside the element if using an `inset` shadow. It will also differ from using `box-sizing` in that any padding will increase the size of the element.
An advantage of using a `box-shadow` is that you can achieve [multiple faux-borders](http://dropshado.ws/post/1592190942/multiple-borders-with-box-shadow). You can’t do this with the regular `border` property. |
9,979,467 | I am using `pdb` (actually `ipdb`) to debug my Django `models.py`. In particular I am trying to debug these lines of code:
```
def add_can_view( sender, **kwargs ) :
#import ipdb; ipdb.set_trace()
for content_type in ContentType.objects.all():
Permission.objects.create(
content_type = content_type,
codename = 'view_{}'.format( content_type.model ),
name = 'Can view {}'.format( content_type.name )
)
post_syncdb.connect( add_can_view )
```
The code above, which was provided in [this question](https://stackoverflow.com/questions/9939604/is-there-a-way-to-apply-a-meta-permission-to-every-model-in-a-django-app), has an `IntegrityError` error when I run `python manage.py syncdb`:
```
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (11, 0))
---------------------------------------------------------------------------
IntegrityError Traceback (most recent call last)
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
173 else:
174 filename = fname
--> 175 __builtin__.execfile(filename, *where)
/Users/hobbes3/Sites/mysite/manage.py in <module>()
8 from django.core.management import execute_from_command_line
9
---> 10 execute_from_command_line(sys.argv)
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/__init__.pyc in execute_from_command_line(argv)
441 """
442 utility = ManagementUtility(argv)
--> 443 utility.execute()
444
445 def execute_manager(settings_mod, argv=None):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/__init__.pyc in execute(self)
380 sys.stdout.write(self.main_help_text() + '\n')
381 else:
--> 382 self.fetch_command(subcommand).run_from_argv(self.argv)
383
384 def setup_environ(settings_mod, original_settings_path=None):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in run_from_argv(self, argv)
194 options, args = parser.parse_args(argv[2:])
195 handle_default_options(options)
--> 196 self.execute(*args, **options.__dict__)
197
198 def execute(self, *args, **options):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in execute(self, *args, **options)
230 if self.requires_model_validation:
231 self.validate()
--> 232 output = self.handle(*args, **options)
233 if output:
234 if self.output_transaction:
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in handle(self, *args, **options)
369 if args:
370 raise CommandError("Command doesn't accept any arguments")
--> 371 return self.handle_noargs(**options)
372
373 def handle_noargs(self, **options):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/management/commands/syncdb.pyc in handle_noargs(self, migrate_all, **options)
88
89 # OK, run the actual syncdb
---> 90 syncdb.Command().execute(**options)
91
92 settings.INSTALLED_APPS = old_installed
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in execute(self, *args, **options)
230 if self.requires_model_validation:
231 self.validate()
--> 232 output = self.handle(*args, **options)
233 if output:
234 if self.output_transaction:
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in handle(self, *args, **options)
369 if args:
370 raise CommandError("Command doesn't accept any arguments")
--> 371 return self.handle_noargs(**options)
372
373 def handle_noargs(self, **options):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/commands/syncdb.pyc in handle_noargs(self, **options)
108 # Send the post_syncdb signal, so individual apps can do whatever they need
109 # to do at this point.
--> 110 emit_post_sync_signal(created_models, verbosity, interactive, db)
111
112 # The connection may have been closed by a syncdb handler.
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/sql.pyc in emit_post_sync_signal(created_models, verbosity, interactive, db)
187 models.signals.post_syncdb.send(sender=app, app=app,
188 created_models=created_models, verbosity=verbosity,
--> 189 interactive=interactive, db=db)
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/dispatch/dispatcher.pyc in send(self, sender, **named)
170
171 for receiver in self._live_receivers(_make_id(sender)):
--> 172 response = receiver(signal=self, sender=sender, **named)
173 responses.append((receiver, response))
174 return responses
/Users/hobbes3/Sites/mysite/doors/signals.py in add_can_view(sender, **kwargs)
8 content_type = content_type,
9 codename = 'view_{}'.format( content_type.model ),
---> 10 name = 'Can view {}'.format( content_type.name )
11 )
12
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/manager.pyc in create(self, **kwargs)
135
136 def create(self, **kwargs):
--> 137 return self.get_query_set().create(**kwargs)
138
139 def bulk_create(self, *args, **kwargs):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/query.pyc in create(self, **kwargs)
375 obj = self.model(**kwargs)
376 self._for_write = True
--> 377 obj.save(force_insert=True, using=self.db)
378 return obj
379
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/base.pyc in save(self, force_insert, force_update, using)
461 if force_insert and force_update:
462 raise ValueError("Cannot force both insert and updating in model saving.")
--> 463 self.save_base(using=using, force_insert=force_insert, force_update=force_update)
464
465 save.alters_data = True
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/base.pyc in save_base(self, raw, cls, origin, force_insert, force_update, using)
549
550 update_pk = bool(meta.has_auto_field and not pk_set)
--> 551 result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
552
553 if update_pk:
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/manager.pyc in _insert(self, objs, fields, **kwargs)
201
202 def _insert(self, objs, fields, **kwargs):
--> 203 return insert_query(self.model, objs, fields, **kwargs)
204
205 def _update(self, values, **kwargs):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/query.pyc in insert_query(model, objs, fields, return_id, raw, using)
1574 query = sql.InsertQuery(model)
1575 query.insert_values(fields, objs, raw=raw)
-> 1576 return query.get_compiler(using=using).execute_sql(return_id)
1577
1578
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/sql/compiler.pyc in execute_sql(self, return_id)
908 cursor = self.connection.cursor()
909 for sql, params in self.as_sql():
--> 910 cursor.execute(sql, params)
911 if not (return_id and cursor):
912 return
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/backends/util.pyc in execute(self, sql, params)
38 start = time()
39 try:
---> 40 return self.cursor.execute(sql, params)
41 finally:
42 stop = time()
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.pyc in execute(self, query, args)
50 def execute(self, query, args=None):
51 try:
---> 52 return self.cursor.execute(query, args)
53 except Database.IntegrityError, e:
54 raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
IntegrityError: duplicate key value violates unique constraint "auth_permission_content_type_id_codename_key"
DETAIL: Key (content_type_id, codename)=(2, view_group) already exists.
```
I have a feeling that somehow there is a duplicate `content_type` and the error occurs when I try to apply the permission twice to `content_type_id 2`, which is `auth.group`. So when after I uncomment the `import ipdb` line, I want to check out some objects such as `content_type`, but if I type that, then all I get is `<ContentType: content type>`.
I know I can simply go look at the [documentation](https://docs.djangoproject.com/en/1.4/ref/contrib/contenttypes/) to see the model, but how would you get a list of fields and methods without knowing what the class is?
Also bonus points for solving this error lol. | 2012/04/02 | ['https://Stackoverflow.com/questions/9979467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150923/'] | Use `dir` (e.g. `dir(content_type)`) to get a list of attributes (including methods).
In relation to django models, there is also a lot of information inside the `_meta` property. Explore that with `dir(my_model_object._meta)`. | Your choices are:
1. [dir](http://docs.python.org/library/functions.html#dir) to get a list of the attributes and methods of an object
2. `content_type.__class__` to learn the class of the object
3. [help](http://docs.python.org/library/functions.html#help) to show the documentation in the console so you don't have to look it up |
9,979,467 | I am using `pdb` (actually `ipdb`) to debug my Django `models.py`. In particular I am trying to debug these lines of code:
```
def add_can_view( sender, **kwargs ) :
#import ipdb; ipdb.set_trace()
for content_type in ContentType.objects.all():
Permission.objects.create(
content_type = content_type,
codename = 'view_{}'.format( content_type.model ),
name = 'Can view {}'.format( content_type.name )
)
post_syncdb.connect( add_can_view )
```
The code above, which was provided in [this question](https://stackoverflow.com/questions/9939604/is-there-a-way-to-apply-a-meta-permission-to-every-model-in-a-django-app), has an `IntegrityError` error when I run `python manage.py syncdb`:
```
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (11, 0))
---------------------------------------------------------------------------
IntegrityError Traceback (most recent call last)
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
173 else:
174 filename = fname
--> 175 __builtin__.execfile(filename, *where)
/Users/hobbes3/Sites/mysite/manage.py in <module>()
8 from django.core.management import execute_from_command_line
9
---> 10 execute_from_command_line(sys.argv)
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/__init__.pyc in execute_from_command_line(argv)
441 """
442 utility = ManagementUtility(argv)
--> 443 utility.execute()
444
445 def execute_manager(settings_mod, argv=None):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/__init__.pyc in execute(self)
380 sys.stdout.write(self.main_help_text() + '\n')
381 else:
--> 382 self.fetch_command(subcommand).run_from_argv(self.argv)
383
384 def setup_environ(settings_mod, original_settings_path=None):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in run_from_argv(self, argv)
194 options, args = parser.parse_args(argv[2:])
195 handle_default_options(options)
--> 196 self.execute(*args, **options.__dict__)
197
198 def execute(self, *args, **options):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in execute(self, *args, **options)
230 if self.requires_model_validation:
231 self.validate()
--> 232 output = self.handle(*args, **options)
233 if output:
234 if self.output_transaction:
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in handle(self, *args, **options)
369 if args:
370 raise CommandError("Command doesn't accept any arguments")
--> 371 return self.handle_noargs(**options)
372
373 def handle_noargs(self, **options):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/management/commands/syncdb.pyc in handle_noargs(self, migrate_all, **options)
88
89 # OK, run the actual syncdb
---> 90 syncdb.Command().execute(**options)
91
92 settings.INSTALLED_APPS = old_installed
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in execute(self, *args, **options)
230 if self.requires_model_validation:
231 self.validate()
--> 232 output = self.handle(*args, **options)
233 if output:
234 if self.output_transaction:
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in handle(self, *args, **options)
369 if args:
370 raise CommandError("Command doesn't accept any arguments")
--> 371 return self.handle_noargs(**options)
372
373 def handle_noargs(self, **options):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/commands/syncdb.pyc in handle_noargs(self, **options)
108 # Send the post_syncdb signal, so individual apps can do whatever they need
109 # to do at this point.
--> 110 emit_post_sync_signal(created_models, verbosity, interactive, db)
111
112 # The connection may have been closed by a syncdb handler.
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/sql.pyc in emit_post_sync_signal(created_models, verbosity, interactive, db)
187 models.signals.post_syncdb.send(sender=app, app=app,
188 created_models=created_models, verbosity=verbosity,
--> 189 interactive=interactive, db=db)
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/dispatch/dispatcher.pyc in send(self, sender, **named)
170
171 for receiver in self._live_receivers(_make_id(sender)):
--> 172 response = receiver(signal=self, sender=sender, **named)
173 responses.append((receiver, response))
174 return responses
/Users/hobbes3/Sites/mysite/doors/signals.py in add_can_view(sender, **kwargs)
8 content_type = content_type,
9 codename = 'view_{}'.format( content_type.model ),
---> 10 name = 'Can view {}'.format( content_type.name )
11 )
12
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/manager.pyc in create(self, **kwargs)
135
136 def create(self, **kwargs):
--> 137 return self.get_query_set().create(**kwargs)
138
139 def bulk_create(self, *args, **kwargs):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/query.pyc in create(self, **kwargs)
375 obj = self.model(**kwargs)
376 self._for_write = True
--> 377 obj.save(force_insert=True, using=self.db)
378 return obj
379
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/base.pyc in save(self, force_insert, force_update, using)
461 if force_insert and force_update:
462 raise ValueError("Cannot force both insert and updating in model saving.")
--> 463 self.save_base(using=using, force_insert=force_insert, force_update=force_update)
464
465 save.alters_data = True
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/base.pyc in save_base(self, raw, cls, origin, force_insert, force_update, using)
549
550 update_pk = bool(meta.has_auto_field and not pk_set)
--> 551 result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
552
553 if update_pk:
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/manager.pyc in _insert(self, objs, fields, **kwargs)
201
202 def _insert(self, objs, fields, **kwargs):
--> 203 return insert_query(self.model, objs, fields, **kwargs)
204
205 def _update(self, values, **kwargs):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/query.pyc in insert_query(model, objs, fields, return_id, raw, using)
1574 query = sql.InsertQuery(model)
1575 query.insert_values(fields, objs, raw=raw)
-> 1576 return query.get_compiler(using=using).execute_sql(return_id)
1577
1578
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/sql/compiler.pyc in execute_sql(self, return_id)
908 cursor = self.connection.cursor()
909 for sql, params in self.as_sql():
--> 910 cursor.execute(sql, params)
911 if not (return_id and cursor):
912 return
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/backends/util.pyc in execute(self, sql, params)
38 start = time()
39 try:
---> 40 return self.cursor.execute(sql, params)
41 finally:
42 stop = time()
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.pyc in execute(self, query, args)
50 def execute(self, query, args=None):
51 try:
---> 52 return self.cursor.execute(query, args)
53 except Database.IntegrityError, e:
54 raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
IntegrityError: duplicate key value violates unique constraint "auth_permission_content_type_id_codename_key"
DETAIL: Key (content_type_id, codename)=(2, view_group) already exists.
```
I have a feeling that somehow there is a duplicate `content_type` and the error occurs when I try to apply the permission twice to `content_type_id 2`, which is `auth.group`. So when after I uncomment the `import ipdb` line, I want to check out some objects such as `content_type`, but if I type that, then all I get is `<ContentType: content type>`.
I know I can simply go look at the [documentation](https://docs.djangoproject.com/en/1.4/ref/contrib/contenttypes/) to see the model, but how would you get a list of fields and methods without knowing what the class is?
Also bonus points for solving this error lol. | 2012/04/02 | ['https://Stackoverflow.com/questions/9979467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150923/'] | Your choices are:
1. [dir](http://docs.python.org/library/functions.html#dir) to get a list of the attributes and methods of an object
2. `content_type.__class__` to learn the class of the object
3. [help](http://docs.python.org/library/functions.html#help) to show the documentation in the console so you don't have to look it up | Since you're using `ipdb` (and not `pdb`), a faster alternative to `dir` is using the built-in tab completion:
```
ipdb> foo=""
ipdb> foo. #press tab after writing the dot
foo.capitalize foo.islower foo.rpartition
foo.center foo.isspace foo.rsplit
foo.count foo.istitle foo.rstrip
foo.decode foo.isupper foo.split
foo.encode foo.join foo.splitlines
foo.endswith foo.ljust foo.startswith
foo.expandtabs foo.lower foo.strip
foo.find foo.lstrip foo.swapcase
foo.format foo.partition foo.title
foo.index foo.replace foo.translate
foo.isalnum foo.rfind foo.upper
foo.isalpha foo.rindex foo.zfill
foo.isdigit foo.rjusthere
```
In case you don't know about it, you can also use tab completion to complete variable names |
9,979,467 | I am using `pdb` (actually `ipdb`) to debug my Django `models.py`. In particular I am trying to debug these lines of code:
```
def add_can_view( sender, **kwargs ) :
#import ipdb; ipdb.set_trace()
for content_type in ContentType.objects.all():
Permission.objects.create(
content_type = content_type,
codename = 'view_{}'.format( content_type.model ),
name = 'Can view {}'.format( content_type.name )
)
post_syncdb.connect( add_can_view )
```
The code above, which was provided in [this question](https://stackoverflow.com/questions/9939604/is-there-a-way-to-apply-a-meta-permission-to-every-model-in-a-django-app), has an `IntegrityError` error when I run `python manage.py syncdb`:
```
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (11, 0))
---------------------------------------------------------------------------
IntegrityError Traceback (most recent call last)
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
173 else:
174 filename = fname
--> 175 __builtin__.execfile(filename, *where)
/Users/hobbes3/Sites/mysite/manage.py in <module>()
8 from django.core.management import execute_from_command_line
9
---> 10 execute_from_command_line(sys.argv)
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/__init__.pyc in execute_from_command_line(argv)
441 """
442 utility = ManagementUtility(argv)
--> 443 utility.execute()
444
445 def execute_manager(settings_mod, argv=None):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/__init__.pyc in execute(self)
380 sys.stdout.write(self.main_help_text() + '\n')
381 else:
--> 382 self.fetch_command(subcommand).run_from_argv(self.argv)
383
384 def setup_environ(settings_mod, original_settings_path=None):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in run_from_argv(self, argv)
194 options, args = parser.parse_args(argv[2:])
195 handle_default_options(options)
--> 196 self.execute(*args, **options.__dict__)
197
198 def execute(self, *args, **options):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in execute(self, *args, **options)
230 if self.requires_model_validation:
231 self.validate()
--> 232 output = self.handle(*args, **options)
233 if output:
234 if self.output_transaction:
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in handle(self, *args, **options)
369 if args:
370 raise CommandError("Command doesn't accept any arguments")
--> 371 return self.handle_noargs(**options)
372
373 def handle_noargs(self, **options):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/South-0.7.4-py2.7.egg/south/management/commands/syncdb.pyc in handle_noargs(self, migrate_all, **options)
88
89 # OK, run the actual syncdb
---> 90 syncdb.Command().execute(**options)
91
92 settings.INSTALLED_APPS = old_installed
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in execute(self, *args, **options)
230 if self.requires_model_validation:
231 self.validate()
--> 232 output = self.handle(*args, **options)
233 if output:
234 if self.output_transaction:
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/base.pyc in handle(self, *args, **options)
369 if args:
370 raise CommandError("Command doesn't accept any arguments")
--> 371 return self.handle_noargs(**options)
372
373 def handle_noargs(self, **options):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/commands/syncdb.pyc in handle_noargs(self, **options)
108 # Send the post_syncdb signal, so individual apps can do whatever they need
109 # to do at this point.
--> 110 emit_post_sync_signal(created_models, verbosity, interactive, db)
111
112 # The connection may have been closed by a syncdb handler.
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/core/management/sql.pyc in emit_post_sync_signal(created_models, verbosity, interactive, db)
187 models.signals.post_syncdb.send(sender=app, app=app,
188 created_models=created_models, verbosity=verbosity,
--> 189 interactive=interactive, db=db)
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/dispatch/dispatcher.pyc in send(self, sender, **named)
170
171 for receiver in self._live_receivers(_make_id(sender)):
--> 172 response = receiver(signal=self, sender=sender, **named)
173 responses.append((receiver, response))
174 return responses
/Users/hobbes3/Sites/mysite/doors/signals.py in add_can_view(sender, **kwargs)
8 content_type = content_type,
9 codename = 'view_{}'.format( content_type.model ),
---> 10 name = 'Can view {}'.format( content_type.name )
11 )
12
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/manager.pyc in create(self, **kwargs)
135
136 def create(self, **kwargs):
--> 137 return self.get_query_set().create(**kwargs)
138
139 def bulk_create(self, *args, **kwargs):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/query.pyc in create(self, **kwargs)
375 obj = self.model(**kwargs)
376 self._for_write = True
--> 377 obj.save(force_insert=True, using=self.db)
378 return obj
379
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/base.pyc in save(self, force_insert, force_update, using)
461 if force_insert and force_update:
462 raise ValueError("Cannot force both insert and updating in model saving.")
--> 463 self.save_base(using=using, force_insert=force_insert, force_update=force_update)
464
465 save.alters_data = True
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/base.pyc in save_base(self, raw, cls, origin, force_insert, force_update, using)
549
550 update_pk = bool(meta.has_auto_field and not pk_set)
--> 551 result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
552
553 if update_pk:
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/manager.pyc in _insert(self, objs, fields, **kwargs)
201
202 def _insert(self, objs, fields, **kwargs):
--> 203 return insert_query(self.model, objs, fields, **kwargs)
204
205 def _update(self, values, **kwargs):
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/query.pyc in insert_query(model, objs, fields, return_id, raw, using)
1574 query = sql.InsertQuery(model)
1575 query.insert_values(fields, objs, raw=raw)
-> 1576 return query.get_compiler(using=using).execute_sql(return_id)
1577
1578
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/models/sql/compiler.pyc in execute_sql(self, return_id)
908 cursor = self.connection.cursor()
909 for sql, params in self.as_sql():
--> 910 cursor.execute(sql, params)
911 if not (return_id and cursor):
912 return
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/backends/util.pyc in execute(self, sql, params)
38 start = time()
39 try:
---> 40 return self.cursor.execute(sql, params)
41 finally:
42 stop = time()
/Users/hobbes3/.virtualenvs/doors/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.pyc in execute(self, query, args)
50 def execute(self, query, args=None):
51 try:
---> 52 return self.cursor.execute(query, args)
53 except Database.IntegrityError, e:
54 raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
IntegrityError: duplicate key value violates unique constraint "auth_permission_content_type_id_codename_key"
DETAIL: Key (content_type_id, codename)=(2, view_group) already exists.
```
I have a feeling that somehow there is a duplicate `content_type` and the error occurs when I try to apply the permission twice to `content_type_id 2`, which is `auth.group`. So when after I uncomment the `import ipdb` line, I want to check out some objects such as `content_type`, but if I type that, then all I get is `<ContentType: content type>`.
I know I can simply go look at the [documentation](https://docs.djangoproject.com/en/1.4/ref/contrib/contenttypes/) to see the model, but how would you get a list of fields and methods without knowing what the class is?
Also bonus points for solving this error lol. | 2012/04/02 | ['https://Stackoverflow.com/questions/9979467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150923/'] | Use `dir` (e.g. `dir(content_type)`) to get a list of attributes (including methods).
In relation to django models, there is also a lot of information inside the `_meta` property. Explore that with `dir(my_model_object._meta)`. | Since you're using `ipdb` (and not `pdb`), a faster alternative to `dir` is using the built-in tab completion:
```
ipdb> foo=""
ipdb> foo. #press tab after writing the dot
foo.capitalize foo.islower foo.rpartition
foo.center foo.isspace foo.rsplit
foo.count foo.istitle foo.rstrip
foo.decode foo.isupper foo.split
foo.encode foo.join foo.splitlines
foo.endswith foo.ljust foo.startswith
foo.expandtabs foo.lower foo.strip
foo.find foo.lstrip foo.swapcase
foo.format foo.partition foo.title
foo.index foo.replace foo.translate
foo.isalnum foo.rfind foo.upper
foo.isalpha foo.rindex foo.zfill
foo.isdigit foo.rjusthere
```
In case you don't know about it, you can also use tab completion to complete variable names |
68,651,869 | I'm working on a project where there are four turtles in the middle of a circle, and they each follow a random path until one of them gets out. The last part is that if two or more turtles bump into each other, they go two steps back towards the center. I have everything except that, and I'm not sure how to proceed. Below is the code I have so far. Can anyone help? Thanks!
```
from random import randrange
import matplotlib.pyplot as plt
import numpy as np
def turtle1234():
x_points = []
y_points = []
x2_points = []
y2_points = []
x3_points = []
y3_points = []
x4_points = []
y4_points = []
x = 0
y = 0
x2 = 0
y2 = 0
x3 = 0
y3 = 0
x4 = 0
y4 = 0
while True:
x = x + randrange(-1,2)
y = y + randrange(-1,2)
x2 = x2 + randrange(-1,2)
y2 = y2 + randrange(-1,2)
x3 = x3 + randrange(-1,2)
y3 = y3 + randrange(-1,2)
x4 = x4 + randrange(-1,2)
y4 = y4 + randrange(-1,2)
x_points.append(x)
y_points.append(y)
x2_points.append(x2)
y2_points.append(y2)
x3_points.append(x3)
y3_points.append(y3)
x4_points.append(x4)
y4_points.append(y4)
if x**2+y**2 > 100**2:
print(x,y)
print('Turtle 1 is outside the circle first')
break
if x2**2+y2**2 > 100**2:
print(x2,y2)
print('Turtle 2 is outside the circle first')
break
if x3**2+y3**2 > 100**2:
print(x3,y3)
print('Turtle 3 is outside the circle first')
break
if x4**2+y4**2 > 100**2:
print(x4,y4)
print('Turtle 4 is outside the circle first')
break
plt.plot(x_points,y_points)
plt.plot(x2_points,y2_points)
plt.plot(x3_points,y3_points)
plt.plot(x4_points,y4_points)
x = np.linspace(-100,100,1000)
turtle1234()
plt.plot(x,-np.sqrt(100**2-x**2), color = 'b')
plt.plot(x, np.sqrt(100**2-x**2), color = 'b')
``` | 2021/08/04 | ['https://Stackoverflow.com/questions/68651869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440183/'] | You can't run background jobs on Cloud Run. Wrap it in a webserver as proposed by MBHA if the process take less than 1h.
Else you can you GKE Autopilot to run your container for a while. you pay only when your container run. And the first cluster is free. You can have a try on it!
As hack you can run your container in Cloud Build also, or in Vertex AI custom container training. | I've run in to a similar issue with building custom image on MAC + deploying in to Cloud Run. In my case, it turned out to be the docker platform causing the problem. The way I isolated this was by building the same image in Cloud Shell and that would work perfectly fine in Cloud Run.
Now, if you need to build it locally on MAC go ahead and test it by changing the Docker platform:
```
export DOCKER_DEFAULT_PLATFORM=linux/amd64
docker build -t mytag:myver .
```
Once the image has been built, you can inspect the architecture:
```
docker image inspect mytag:myver | grep -i Architecture
```
Then deploy it to Cloud Run. |
68,651,869 | I'm working on a project where there are four turtles in the middle of a circle, and they each follow a random path until one of them gets out. The last part is that if two or more turtles bump into each other, they go two steps back towards the center. I have everything except that, and I'm not sure how to proceed. Below is the code I have so far. Can anyone help? Thanks!
```
from random import randrange
import matplotlib.pyplot as plt
import numpy as np
def turtle1234():
x_points = []
y_points = []
x2_points = []
y2_points = []
x3_points = []
y3_points = []
x4_points = []
y4_points = []
x = 0
y = 0
x2 = 0
y2 = 0
x3 = 0
y3 = 0
x4 = 0
y4 = 0
while True:
x = x + randrange(-1,2)
y = y + randrange(-1,2)
x2 = x2 + randrange(-1,2)
y2 = y2 + randrange(-1,2)
x3 = x3 + randrange(-1,2)
y3 = y3 + randrange(-1,2)
x4 = x4 + randrange(-1,2)
y4 = y4 + randrange(-1,2)
x_points.append(x)
y_points.append(y)
x2_points.append(x2)
y2_points.append(y2)
x3_points.append(x3)
y3_points.append(y3)
x4_points.append(x4)
y4_points.append(y4)
if x**2+y**2 > 100**2:
print(x,y)
print('Turtle 1 is outside the circle first')
break
if x2**2+y2**2 > 100**2:
print(x2,y2)
print('Turtle 2 is outside the circle first')
break
if x3**2+y3**2 > 100**2:
print(x3,y3)
print('Turtle 3 is outside the circle first')
break
if x4**2+y4**2 > 100**2:
print(x4,y4)
print('Turtle 4 is outside the circle first')
break
plt.plot(x_points,y_points)
plt.plot(x2_points,y2_points)
plt.plot(x3_points,y3_points)
plt.plot(x4_points,y4_points)
x = np.linspace(-100,100,1000)
turtle1234()
plt.plot(x,-np.sqrt(100**2-x**2), color = 'b')
plt.plot(x, np.sqrt(100**2-x**2), color = 'b')
``` | 2021/08/04 | ['https://Stackoverflow.com/questions/68651869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440183/'] | You can't run background jobs on Cloud Run. Wrap it in a webserver as proposed by MBHA if the process take less than 1h.
Else you can you GKE Autopilot to run your container for a while. you pay only when your container run. And the first cluster is free. You can have a try on it!
As hack you can run your container in Cloud Build also, or in Vertex AI custom container training. | The explanation is in your question:
>
> I am running a background task, nothing to expose
>
>
>
A cloud run application, so your container, must be listening for incoming HTTP requests as stated in the [Container runtime contract](https://cloud.google.com/run/docs/reference/container-contract#port). That's why in all cloud run examples, java in your case, spring boot is used with `@RestController`. Other explanation can be found in [this answer](https://stackoverflow.com/a/55662223/8569928).
**Update:**
So the solution is either to
* add a webserver to your code and wrap it with spring boot and controller logic
* use Cloud Function rather than Cloud Run and get rid of the Dockerfile and in the same time have simpler code and less configuration |
45,684,925 | I have a drop down in my form (<https://ant.design/components/select>). In this select drop down I have the onChange to call a function. Inside 'onChange' I want to pass the event as a parameter to my function. The problem is: when the onChange occurs, only the selected value is passed, but I want the entire event.
**Here is the code:**
```
export default class MyForm extends Component {
constructor() {
super();
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange = (event) => {
console.log(event); // here I'm receiving only the value selected (1 or 2)
}
render() {
render(
<Form>
<Select onChange={this.handleOnChange}>
<Option value="1">text 1</Option>
<Option value="2">text 2</Option>
</Select>
</Form>
)
}
}
```
In the console.log() I'm receiving only the selected value. Is there a way to pass the entire event object to the function handleOnChange()? | 2017/08/15 | ['https://Stackoverflow.com/questions/45684925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4956634/'] | I found a solution. Just use: onSelect(), passing the value and the event.
```
handleOnChange = (value, event) => {
...code here
}
render() {
render(
<Form>
<Select onSelect={(value, event) => this.handleOnChange(value, event)}>
<Option value="1">text 1</Option>
<Option value="2">text 2</Option>
</Select>
</Form>
)
}
``` | The `Select` component that you use is the one that handle the `onChange` and call your "outer" function.
What you can try is use the synthetic event variable inside your function, it might work:
```
handleOnChange = (selectedValue) => {
console.log(selectedValue); // The value from the inner component
console.log(event); // usually you have access to this variable
}
``` |
45,684,925 | I have a drop down in my form (<https://ant.design/components/select>). In this select drop down I have the onChange to call a function. Inside 'onChange' I want to pass the event as a parameter to my function. The problem is: when the onChange occurs, only the selected value is passed, but I want the entire event.
**Here is the code:**
```
export default class MyForm extends Component {
constructor() {
super();
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange = (event) => {
console.log(event); // here I'm receiving only the value selected (1 or 2)
}
render() {
render(
<Form>
<Select onChange={this.handleOnChange}>
<Option value="1">text 1</Option>
<Option value="2">text 2</Option>
</Select>
</Form>
)
}
}
```
In the console.log() I'm receiving only the selected value. Is there a way to pass the entire event object to the function handleOnChange()? | 2017/08/15 | ['https://Stackoverflow.com/questions/45684925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4956634/'] | The `Select` component that you use is the one that handle the `onChange` and call your "outer" function.
What you can try is use the synthetic event variable inside your function, it might work:
```
handleOnChange = (selectedValue) => {
console.log(selectedValue); // The value from the inner component
console.log(event); // usually you have access to this variable
}
``` | Try this, if you dont want to bind in callback in Select onSelect/onChange:
```
toggleActive = name => event => {
console.log("name: ",name) // prints "name: Active!"
console.log("event: ",event) // event is some data
}
<Select
mode="multiple"
style={{ width: '91%' }}
placeholder="Stuff"
value={this.props.value}
onChange={this.toggleActive("Active!")}
>
``` |
45,684,925 | I have a drop down in my form (<https://ant.design/components/select>). In this select drop down I have the onChange to call a function. Inside 'onChange' I want to pass the event as a parameter to my function. The problem is: when the onChange occurs, only the selected value is passed, but I want the entire event.
**Here is the code:**
```
export default class MyForm extends Component {
constructor() {
super();
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange = (event) => {
console.log(event); // here I'm receiving only the value selected (1 or 2)
}
render() {
render(
<Form>
<Select onChange={this.handleOnChange}>
<Option value="1">text 1</Option>
<Option value="2">text 2</Option>
</Select>
</Form>
)
}
}
```
In the console.log() I'm receiving only the selected value. Is there a way to pass the entire event object to the function handleOnChange()? | 2017/08/15 | ['https://Stackoverflow.com/questions/45684925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4956634/'] | I found a solution. Just use: onSelect(), passing the value and the event.
```
handleOnChange = (value, event) => {
...code here
}
render() {
render(
<Form>
<Select onSelect={(value, event) => this.handleOnChange(value, event)}>
<Option value="1">text 1</Option>
<Option value="2">text 2</Option>
</Select>
</Form>
)
}
``` | Try this, if you dont want to bind in callback in Select onSelect/onChange:
```
toggleActive = name => event => {
console.log("name: ",name) // prints "name: Active!"
console.log("event: ",event) // event is some data
}
<Select
mode="multiple"
style={{ width: '91%' }}
placeholder="Stuff"
value={this.props.value}
onChange={this.toggleActive("Active!")}
>
``` |
34,570 | I am using
```
truffle migrate --reset --compile-all
```
to deploy the contract to local network
but in order to use ***new web3.eth.Contract(jsonInterface[, address][, options])***, i should be able to know the contract address,
so how could know the address which truffle is deploying? | 2017/12/28 | ['https://ethereum.stackexchange.com/questions/34570', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/22913/'] | There are a few ways to do this:
1) In your blockchain node (testrpc|ganache or your test/live network with geth/parity), the contract deployments will be logged and you can see the address created then
```
Transaction: 0xc2471aa6d1e020921d41247ac2a86eb5ad2447e93450347365a25f8d632e34bd
Contract created: 0x98445ab3eaafdd2293981525631730c64adec41a // <--- contract address
Gas usage: 245439
Block Number: 20
Block Time: Thu Dec 28 2017 19:43:44 GMT+0800 (+08)
```
2 & 3) You can get the address via the artifact after the contract is deployed, either from the artifact directly or by using the artifact and getting the contract instance.
**Example: log from deployment file: (migrations/2\_deploy\_contracts.js)**
*(Note: I've used the deployment file as the example, but you can retrieve the address from any javascript file where you've imported and made available the artifact)*
```
var SimpleStorage = artifacts.require("./SimpleStorage.sol");
module.exports = function(deployer) {
deployer.deploy(SimpleStorage)
// Option 2) Console log the address:
.then(() => console.log(SimpleStorage.address))
// Option 3) Retrieve the contract instance and get the address from that:
.then(() => SimpleStorage.deployed())
.then(_instance => console.log(_instance.address));
};
``` | If the contract is being deployed you can obviously read it from the log. What if the contract has deployed but you did not take a record of it? There are a few ways to do it:
```
1. Using etherscan (or Rinkeby scan, Ropsten scan etc..) and search your wallet address used for deployment of the contract. But what if I don't recall the wallet address used? You can get it from truffle.js (or truffle-config.js) in your project folder. Or
2. You can reconnect to the deployed contract using truffle and retrieve the address:
$truffle console --network rinkeby
truffle(rinkeby)>myToken = await MyToken.deployed()
truffle(rinkeby)>await myToken.address
```
This will do it! Remember to replace "MyToken" with your token's contract name, and replace "rinkeby" with your network name such as: ropsten etc.. |
34,570 | I am using
```
truffle migrate --reset --compile-all
```
to deploy the contract to local network
but in order to use ***new web3.eth.Contract(jsonInterface[, address][, options])***, i should be able to know the contract address,
so how could know the address which truffle is deploying? | 2017/12/28 | ['https://ethereum.stackexchange.com/questions/34570', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/22913/'] | There are a few ways to do this:
1) In your blockchain node (testrpc|ganache or your test/live network with geth/parity), the contract deployments will be logged and you can see the address created then
```
Transaction: 0xc2471aa6d1e020921d41247ac2a86eb5ad2447e93450347365a25f8d632e34bd
Contract created: 0x98445ab3eaafdd2293981525631730c64adec41a // <--- contract address
Gas usage: 245439
Block Number: 20
Block Time: Thu Dec 28 2017 19:43:44 GMT+0800 (+08)
```
2 & 3) You can get the address via the artifact after the contract is deployed, either from the artifact directly or by using the artifact and getting the contract instance.
**Example: log from deployment file: (migrations/2\_deploy\_contracts.js)**
*(Note: I've used the deployment file as the example, but you can retrieve the address from any javascript file where you've imported and made available the artifact)*
```
var SimpleStorage = artifacts.require("./SimpleStorage.sol");
module.exports = function(deployer) {
deployer.deploy(SimpleStorage)
// Option 2) Console log the address:
.then(() => console.log(SimpleStorage.address))
// Option 3) Retrieve the contract instance and get the address from that:
.then(() => SimpleStorage.deployed())
.then(_instance => console.log(_instance.address));
};
``` | You can find the contract address in your build .json files. For example build/contracts/deployedContract.json Just search the file for address.
If you deployed the contract and lost the address/build.json you can simply retrieve it by truffle commands. You just need the name of the deployed contract.
For example, I deployed **NewContract** but lost his address.
```
truffle console --network private
truffle(private)>
truffle(private)> let contract = await NewContract.deployed()
truffle(private)> contract.address
'0xb0B8956f1B95a562bC7CF3e77Ec8BeA712321315'
```
And that is it, you have your address |
34,570 | I am using
```
truffle migrate --reset --compile-all
```
to deploy the contract to local network
but in order to use ***new web3.eth.Contract(jsonInterface[, address][, options])***, i should be able to know the contract address,
so how could know the address which truffle is deploying? | 2017/12/28 | ['https://ethereum.stackexchange.com/questions/34570', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/22913/'] | If the contract is being deployed you can obviously read it from the log. What if the contract has deployed but you did not take a record of it? There are a few ways to do it:
```
1. Using etherscan (or Rinkeby scan, Ropsten scan etc..) and search your wallet address used for deployment of the contract. But what if I don't recall the wallet address used? You can get it from truffle.js (or truffle-config.js) in your project folder. Or
2. You can reconnect to the deployed contract using truffle and retrieve the address:
$truffle console --network rinkeby
truffle(rinkeby)>myToken = await MyToken.deployed()
truffle(rinkeby)>await myToken.address
```
This will do it! Remember to replace "MyToken" with your token's contract name, and replace "rinkeby" with your network name such as: ropsten etc.. | You can find the contract address in your build .json files. For example build/contracts/deployedContract.json Just search the file for address.
If you deployed the contract and lost the address/build.json you can simply retrieve it by truffle commands. You just need the name of the deployed contract.
For example, I deployed **NewContract** but lost his address.
```
truffle console --network private
truffle(private)>
truffle(private)> let contract = await NewContract.deployed()
truffle(private)> contract.address
'0xb0B8956f1B95a562bC7CF3e77Ec8BeA712321315'
```
And that is it, you have your address |
14,248,725 | I want to generate some binary arrays to control the brightness of an LED without a controller. Rather than generate the pulse widths on the microcontroller (which would take up instruction cycles that should be used for other things), I'll hard-code them as a look-up table, and loop through the binary array over and over, setting the LED either on or off at that instruction.
Assuming I have an array length of 4, I would have 5 brightness levels:
```
{{ 0, 0, 0, 0 },
{ 1, 0, 0, 0 },
{ 1, 0, 1, 0 },
{ 1, 1, 1, 0 },
{ 1, 1, 1, 1 }}
```
Notice that I have tried to distribute the 1's as evenly as possible throughout the array, which is not always possible but small anomalies shouldn't be visible to the human eye.
Let's say I have an array length of 8, and I want a brightness of 5/8:
```
{ 1, 0, 1, 1, 0, 1, 1, 0 };
```
This seems like a good spread, but I could have also used:
```
{ 1, 0, 1, 1, 1, 0, 1, 0 };
```
Which is better? The average brightness is, of course, the same. The number of changes from one state to another is also the same. The standard deviation is the same. Looking at the *runs*, however, the first example has a much lower variance of run length which means it's more uniform and, therefore, better.
Anyway. I need an algorithm to generate these arrays for a given length and brightness. If possible, the algorithm should find an optimal array - one that's as uniform as possible.
It's not as simple as it sounds. To be honest, I'm tempted to just write a brute-force algorithm that compares all possibilities and returns the best.
I was even considering putting together an Integer Programming model, but that seems like overkill for this problem.
Unless someone has a better idea?
**Edit:**
It turns out that `{ 1, 1, 1, 1, 0, 0, 0, 0 }` has the same *run variance* as `{ 1, 0, 1, 0, 1, 0, 1, 0 }`, so the metric needs to be a little more complicated as the second example is clearly superior to the first. (For longer array lengths, some LED flicker might be visible of the 1's are bunched up). | 2013/01/10 | ['https://Stackoverflow.com/questions/14248725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1002358/'] | Ok here it is. Basically, what you want to do is minimize the maximum run length of 0 or 1. The general idea is to distribute what we can. For the remainder, just jam it in at the front.
N = # of total bits
n = # of 1s
```
void pwm(int N, int n, char* z = 0) {
if (n == 0) {
// degenerate case!
for (int i = 0; i < N; i++) {
printf("0");
}
printf("\n");
return;
} else if (n == N) {
// degenerate case!
for (int i = 0; i < N; i++) {
printf("1");
}
printf("\n");
return;
}
int m = N - n;
int sep = m/n;
int rem = m%n;
int pre;
int i,j;
std::list<char> clist;
if (z == 0) {
// if more 1 than 0, then flip
if (sep > 0) pwm(N,n,"01");
else pwm(N,N-n,"10");
return;
}
pre = sep/2;
for (j = 0; j < pre; j++)
clist.push_back(z[0]);
if (rem > 0) {
clist.push_back(z[0]);
rem--;
}
for (i = 0; i < n; i++) {
if (i!=0) {
for (j = 0; j < sep; j++)
clist.push_back(z[0]);
if (rem > 0) {
clist.push_back(z[0]);
rem--;
}
}
clist.push_back(z[1]);
}
for (j = 0; j < sep-pre; j++)
clist.push_back(z[0]);
// output the data so we can see
char* res = new char[N+1];
memset(res, ' ', N);
res[N] = 0;
char* u = res;
for (std::list<char>::iterator cli = clist.begin(); cli != clist.end(); cli++) {
(*u) = *cli;
u++;
}
printf("%s\n", res);
delete [] res;
}
```
Here's an output for N=25:
```
0000000000000000000000000
0000000000001000000000000
0000001000000000001000000
0000100000001000000010000
0001000001000001000001000
0010000100001000010000100
0010001000100010001000100
0010001000100010010010010
0010010010010010010010010
0100100100100100100101010
0100100100100101010101010
0100100101010101010101010
0101010101010101010101010
1010101010101010101010101
1011011010101010101010101
1011011011011010101010101
1011011011011011011010101
1101101101101101101101101
1101110111011101101101101
1101110111011101110111011
1101111011110111101111011
1110111110111110111110111
1111011111110111111101111
1111110111111111110111111
1111111111110111111111111
``` | Assume you need to light up k points in a grid of n points. You can follow the following probabilistic approach.
```
remk=k
remn=n
for i in range(n):
x[i] = 1 if rand()< remk*1.0/remn else 0
remk-=x[i]
remn-=1
```
x is the array that contains lighting arrangement. |
6,595,424 | while typing a command like #ifconfig 10.0.0.10 up is it possible to see all "possible" prints inside kernel.
I know something like echo t > /proc/sysrq-trigger will give you stack trace with respect to processes running in a system.
What I am interested in is, with respect to a 'specific command' how can I get the kernel functions(stack trace) that gets executed?
I know about debuggers like kgdb,but I am interested in quick ways like sysrq methods if any.
Thanks. | 2011/07/06 | ['https://Stackoverflow.com/questions/6595424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124330/'] | `tail -f /var/log/kern.log` should display any interaction that occurrs in the kernel.
It is more or less an equivalent to the `dmesg` command. | `strace ifconfig 10.0.0.10 up` will show all system calls called by ifconfig, but will not get inside kernel's calls |
6,595,424 | while typing a command like #ifconfig 10.0.0.10 up is it possible to see all "possible" prints inside kernel.
I know something like echo t > /proc/sysrq-trigger will give you stack trace with respect to processes running in a system.
What I am interested in is, with respect to a 'specific command' how can I get the kernel functions(stack trace) that gets executed?
I know about debuggers like kgdb,but I am interested in quick ways like sysrq methods if any.
Thanks. | 2011/07/06 | ['https://Stackoverflow.com/questions/6595424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124330/'] | The answer to your question is "ftrace". It is not a tool, not a command, but just a kernel feature built into most modern linux kernel.
For example, here you can use ftrace to understand how swap space are implemented (see all the key functions executed and its sequence inside the pastebin files indicated below):
<http://tthtlc.wordpress.com/2013/11/19/using-ftrace-to-understanding-linux-kernel-api/>
Read this carefully and you can see there are many ways of using ftrace (one is dump kernel stack trace which you requested, another is identifying executed function flow):
<http://lwn.net/Articles/366796/>
If you don't want to use ftrace, another option is to use QEMU: installing Linux inside the qemu guest is needed, and it is a lot more powerful, as you can use gdb to step through every lines (in C source code) or assembly.
<https://tthtlc.wordpress.com/2014/01/14/how-to-do-kernel-debugging-via-gdb-over-serial-port-via-qemu/>
Just in case you want to google further, this is called "kgdb", or gdbserver, and outside the qemu you are running a gdb client. | `tail -f /var/log/kern.log` should display any interaction that occurrs in the kernel.
It is more or less an equivalent to the `dmesg` command. |
6,595,424 | while typing a command like #ifconfig 10.0.0.10 up is it possible to see all "possible" prints inside kernel.
I know something like echo t > /proc/sysrq-trigger will give you stack trace with respect to processes running in a system.
What I am interested in is, with respect to a 'specific command' how can I get the kernel functions(stack trace) that gets executed?
I know about debuggers like kgdb,but I am interested in quick ways like sysrq methods if any.
Thanks. | 2011/07/06 | ['https://Stackoverflow.com/questions/6595424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124330/'] | The answer to your question is "ftrace". It is not a tool, not a command, but just a kernel feature built into most modern linux kernel.
For example, here you can use ftrace to understand how swap space are implemented (see all the key functions executed and its sequence inside the pastebin files indicated below):
<http://tthtlc.wordpress.com/2013/11/19/using-ftrace-to-understanding-linux-kernel-api/>
Read this carefully and you can see there are many ways of using ftrace (one is dump kernel stack trace which you requested, another is identifying executed function flow):
<http://lwn.net/Articles/366796/>
If you don't want to use ftrace, another option is to use QEMU: installing Linux inside the qemu guest is needed, and it is a lot more powerful, as you can use gdb to step through every lines (in C source code) or assembly.
<https://tthtlc.wordpress.com/2014/01/14/how-to-do-kernel-debugging-via-gdb-over-serial-port-via-qemu/>
Just in case you want to google further, this is called "kgdb", or gdbserver, and outside the qemu you are running a gdb client. | `strace ifconfig 10.0.0.10 up` will show all system calls called by ifconfig, but will not get inside kernel's calls |
15,767 | I can already figure out the melody of a song by 'trial and error' along the C major scale just because it is easier on that scale and eventually become okay at guessing melody. This is fun enough on the recorder but I couldn't figure out how do I make a full use of string instrument such as ukulele. To sum everything up, I only have experience on playing one note at a time and if I try to play a song by ear I would pick up the easily distinguishable notes of the song. I don't know much about music theory other than reading a little bit of music notation, scales and notes that build a triad chord and everything is self taught. I just want to make those melody sound fuller on ukulele. Are there any way to make melody to sound interesting without referring to music score? | 2014/02/26 | ['https://music.stackexchange.com/questions/15767', 'https://music.stackexchange.com', 'https://music.stackexchange.com/users/9372/'] | Well `user9372`, there are several things that you can do to make the melody sound fuller or accompany yourself. The first thing that you should do is start learning some chords. Here is a chord chart that has plenty of ukulele chords.
<http://www.ukalady.com/Images/UkeChart.pdf>
As far as having to refer to a music score, you don't have to, but that really depends on your creativity, and your musical ability. Some people can cook without a recipe. It will be very helpful if you were to find a chord chart for the songs that you're playing. That way you can look at the pdf that I sent you and find out how to play the chords that you need for the song.
I would suggest getting familiar with basic chords, such as all of the major chords, and all of the minor chords. Extended chords such as 7ths and 9ths, or diminished and augmented chords can wait until you're familiar with major and minor triads.
If you want to do it yourself without using a chord chart for the song, you can pick chords to accompany your melody that share the same note as the melody. For starters, I would suggest picking a chord whose root note matches the note that you're playing. Obviously this is not the only or best way to harmonize a melody, but it can be simple enough and with major and minor chords you shouldn't run into too many harmonic issues and it could sound pretty decent. It will also help if you can identify the key, because if you're playing a Cminor chord for a song that is predominantly in Cmajor, you can have some serious issues.
[Basic Music Theory](http://www.basicmusictheory.com) has a lot of helpful information. If you can identify all of the notes in the song, you can look at the scales there and identify what scale your notes belong to. Most songs however, do not stay in one key, and it may prove difficult to grasp at first.
At any rate, good luck, and use the chord chart! It'll be very helpful. | One thing that really opened my eyes musically was the concept of "chord of the moment". I had a teacher that mentioned it in passing once, and it blew my mind that "real musicians" can change chords that fast!
Basically, as a song is played through, musicians are always changing chords, and potentially, the key of the song which changes the chord family. Each melody note sounds good when played over the correct "chord of the moment", or saying it in reverse, given a specific chord of the moment, basically anything within that chord can be used to progress the melody. There's no rule that says that ONLY those notes sound good, but as a general roadmap its a good place to start.
Another eye opener was understanding that chords within a key are (again, generally) made up of the notes within key's scale.
One time I asked "how to I know when a key change would sound good, and how do I know what key to change to". That really blew my mind. |
602 | I want to avoid duplicate titles/descriptions on pages (P1,P2...) so I want to add Page 1, Page 2 in the page title.
Is there a way to know if we are on pagination and which page it is, but outside of pagination tags? Maybe Stash or something like that?
Thank you | 2012/11/28 | ['https://expressionengine.stackexchange.com/questions/602', 'https://expressionengine.stackexchange.com', 'https://expressionengine.stackexchange.com/users/281/'] | I wrote a [plugin](https://github.com/tyssen/Page-Number.ee_addon) a while back to do this. It was the first one I wrote so apologies in advance if it's not up to scratch.
Example is included in the plugin usage, but basically, place `{exp:page_number url_segment="{segment_1}" limit="5"}` somewhere in your template.
Parameters:
**url\_segment:** the segment which contains your page number
**limit:** the same value you have in your channel entries tag which limits the number of entries shown per page | With Stash, inside you pagination tag pair you could do:
```
{paginate}
{exp:stash:set name="page_number"}
Page {current_page}
{/exp:stash:set}
{!-- any other pagination stuff here --}
{/paginate}
```
Which would give you "Page X" accessible as `{exp:stash:get name="page_number"}`.
Another potential is to use [Mo' Variables](http://devot-ee.com/add-ons/mo-variables), which provides a Pagination Detect Conditional and Page Offset as `{if paginated}` and `{page_offset}`, respectively.
So for example
```
{if paginated}This is a paginated view{/if}
```
But I just realized `{page_offset}` isn't going to be quite what you wanted. It will give you some multiple of whatever you have in your `limit` parameter so will not directly give you "Page 1" "Page 2" etc. |
46,006,705 | I need to get the OS version and Revision number using PowerShell on a list of remote systems.
I need the results that you get from [environment]::OSVersion.Version but on the remote systems.
when I run [environment]::OSVersion.Version
it returns
Major Minor Build Revision
6 1 7601 65536
the ultimate goal would be for it to look like this (where system name is the remote system I am querying.)
SystemName 6.1.7601.65536
my current code:
```
$expectedVersion = "6.1.7601.65536"
$computer = Get-content "C:\temp\servers.txt"
foreach ($computer in $computer)
{
$a=[environment]::OSVersion.Version
If ($a -lt $expectedVersion)
{
Write-Host "$computer $a is NOT Patched" -ForegroundColor Red
}
Else
{
Write-Host "$computer $a is Patched" -ForegroundColor Green
}}
```
which give me the following results:
System-01 6.1.7601.65536 is Patched
System-02 6.1.7601.65536 is Patched
System-41 6.1.7601.65536 is Patched
System-42 6.1.7601.65536 is Patched
the issue I am having is that the resulting OS version is only of the local system and not the remote systems.
I know this because it is being run from a Win 7 box against a long list of Server and only server OS which are different OS version numbers then what is showing up in the results.
what am I missing here. can you all help me tweak this to make it work against remote systems?
thanks | 2017/09/01 | ['https://Stackoverflow.com/questions/46006705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1232402/'] | (1) When you make a change to checkbox you need to check all checkboxes and update to textarea.
(2) function `updateAllChecked` will handle all the check and update.
(3) for check all, if it is checked, set all email checkboxes to checked and call `.change()` to trigger the change event.
```js
$("input[name=email]").change(function() {
updateAllChecked();
});
$("input[name=addall]").change(function() {
if (this.checked) {
$("input[name=email]").prop('checked', true).change();
} else {
$("input[name=email]").prop('checked', false).change();
}
});
function updateAllChecked() {
$('#recipients').text('');
$("input[name=email]").each(function() {
if (this.checked) {
let old_text = $('#recipients').text() ? $('#recipients').text() + ', ' : '';
$('#recipients').text(old_text + $(this).val());
}
})
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="email" value="email_1">email_1<br>
<input type="checkbox" name="email" value="email_2">email_2<br>
<input type="checkbox" name="email" value="email_3">email_3<br>
<input type="checkbox" name="email" value="email_4">email_4<br>
<br>
<input type="checkbox" name="addall">Add All Email<br>
<textarea id="recipients"></textarea>
``` | Try something like this, using an array with a final `join()` once your array is populated. I think it's a lot cleaner:
```
checkbox.onclick = (function(chk){
return function() {
var valueArray = [];
for (var j = 0; j < checkboxes.length; j++) {
if (checkboxes[j].checked) {
valueArray.push(checkboxes[j].value); //add value to array
}
}
textbox.value = valueArray.join(", "); //join with comma separators
}
})(checkbox);
```
You could also extract the function and invoke the extracted function rather than adding the content of the function to every checkbox, but w/out seeing your HTML, it's a little hard to discern exactly what you're doing and why you're looping the way you are. |
46,006,705 | I need to get the OS version and Revision number using PowerShell on a list of remote systems.
I need the results that you get from [environment]::OSVersion.Version but on the remote systems.
when I run [environment]::OSVersion.Version
it returns
Major Minor Build Revision
6 1 7601 65536
the ultimate goal would be for it to look like this (where system name is the remote system I am querying.)
SystemName 6.1.7601.65536
my current code:
```
$expectedVersion = "6.1.7601.65536"
$computer = Get-content "C:\temp\servers.txt"
foreach ($computer in $computer)
{
$a=[environment]::OSVersion.Version
If ($a -lt $expectedVersion)
{
Write-Host "$computer $a is NOT Patched" -ForegroundColor Red
}
Else
{
Write-Host "$computer $a is Patched" -ForegroundColor Green
}}
```
which give me the following results:
System-01 6.1.7601.65536 is Patched
System-02 6.1.7601.65536 is Patched
System-41 6.1.7601.65536 is Patched
System-42 6.1.7601.65536 is Patched
the issue I am having is that the resulting OS version is only of the local system and not the remote systems.
I know this because it is being run from a Win 7 box against a long list of Server and only server OS which are different OS version numbers then what is showing up in the results.
what am I missing here. can you all help me tweak this to make it work against remote systems?
thanks | 2017/09/01 | ['https://Stackoverflow.com/questions/46006705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1232402/'] | (1) When you make a change to checkbox you need to check all checkboxes and update to textarea.
(2) function `updateAllChecked` will handle all the check and update.
(3) for check all, if it is checked, set all email checkboxes to checked and call `.change()` to trigger the change event.
```js
$("input[name=email]").change(function() {
updateAllChecked();
});
$("input[name=addall]").change(function() {
if (this.checked) {
$("input[name=email]").prop('checked', true).change();
} else {
$("input[name=email]").prop('checked', false).change();
}
});
function updateAllChecked() {
$('#recipients').text('');
$("input[name=email]").each(function() {
if (this.checked) {
let old_text = $('#recipients').text() ? $('#recipients').text() + ', ' : '';
$('#recipients').text(old_text + $(this).val());
}
})
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="email" value="email_1">email_1<br>
<input type="checkbox" name="email" value="email_2">email_2<br>
<input type="checkbox" name="email" value="email_3">email_3<br>
<input type="checkbox" name="email" value="email_4">email_4<br>
<br>
<input type="checkbox" name="addall">Add All Email<br>
<textarea id="recipients"></textarea>
``` | Hi guys here is my html and php, I retrieve recipients email from db:
```
here is my html with php, I retrieve recipients email from db.: <?php
$i='';
if($result_applied_jobs): ?>
<div class="tg-wrap">
<table id="tg-s6tTH" class="tg" style="width: 100%;">
<tr><th style="width: 12%"><label><input type="checkbox" name="addall" id="addall"/> Select all</label></th><th style="width: 7%">Sl. No.</th><th style="width: 20%">Applicant's Name</th><th style="width: 25%">Job Title</th><th style="width: 13%">Apply Date</th><th>Cover Letter</th></tr><?php
foreach($result_applied_jobs as $row_applied_job):
$i++;
?>
<tr>
<td><input type="checkbox" value="<?php echo $row_applied_job->email;?>" name="email" id="email"></td>
<td><?php echo $i;?></td>
<td><a href="<?php echo base_url('candidate/'.$this->custom_encryption->encrypt_data($row_applied_job->job_seeker_ID));?>"><?php echo $row_applied_job->first_name.' '.$row_applied_job->last_name;?></a></td>
<td><a href="<?php echo base_url('jobs/'.$row_applied_job->job_slug);?>"><?php echo $row_applied_job->job_title;?></a></td>
<td><i class="fa fa-calendar-check-o" aria-hidden="true" style="color: #5f6f81"></i> <?php echo date_formats($row_applied_job->applied_date, 'M d, Y');?></td>
<td><?php echo $row_applied_job->c_letter;?></td>
</tr>
<?php endforeach; ?>
</table>
</div><?php
else:?>
<div class="alert alert-danger"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> No application received</div>
<?php endif;?>
```
here is another portion for textarea:
```
<textarea class="form-control" id="recipientss" readonly="" placeholder="check the checkbox against applicants you want to send a message"><?php echo set_value('recipients');?></textarea>
``` |
14,695,580 | I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.
The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.
The file I'm trying to access looks like this inside my visual studio solution explorer
AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)
**Here is the routing for the portable area:**
```
using System.Web.Mvc;
using MvcContrib.PortableAreas;
namespace AdHocReporting.Areas.AdHocReportBuilder
{
public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
{
public override string AreaName
{
get { return "AdHocReportBuilder"; }
}
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
RegisterRoutes(context);
RegisterAreaEmbeddedResources();
}
private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_content",
base.AreaRoutePrefix + "/Content/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
new[] { "MvcContrib.PortableAreas" }
);
context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
**Here is the Web sites Global.aspx that has the reference to the portable area**
```
namespace AdHocReportingSite
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
PortableAreaRegistration.RegisterEmbeddedViewEngine();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
**here is an image of what my solution explore looks like:**
![Solution Explorer](https://i.stack.imgur.com/6P0TK.png) | 2013/02/04 | ['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/'] | See below for my original answer - that pattern has worked well, but recently I've started using a different approach to Service/Activity communication:
* Use a [bound service](https://developer.android.com/guide/components/bound-services.html) which enables the Activity to get a direct
reference to the Service, thus allowing direct calls on it, rather
than using Intents.
* Use RxJava to execute asynchronous operations.
* If the Service needs to continue background operations even when no
Activity is running, also start the service from the Application
class so that it does not get stopped when unbound.
The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are
* No need for data objects to implement Parcelable - this is particularly important to me as I am now sharing code between Android and iOS (using RoboVM)
* RxJava provides canned (and cross-platform) scheduling, and easy composition of sequential asynchronous operations.
* This should be more efficient than using a LocalBroadcast, though the overhead of using RxJava may outweigh that.
Some example code. First the service:
```
public class AndroidBmService extends Service implements BmService {
private static final int PRESSURE_RATE = 500000; // microseconds between pressure updates
private SensorManager sensorManager;
private SensorEventListener pressureListener;
private ObservableEmitter<Float> pressureObserver;
private Observable<Float> pressureObservable;
public class LocalBinder extends Binder {
public AndroidBmService getService() {
return AndroidBmService.this;
}
}
private IBinder binder = new LocalBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
logMsg("Service bound");
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if(pressureSensor != null)
sensorManager.registerListener(pressureListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if(pressureObserver != null) {
float lastPressure = event.values[0];
float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45);
pressureObserver.onNext(lastPressureAltitude);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}, pressureSensor, PRESSURE_RATE);
}
@Override
public Observable<Float> observePressure() {
if(pressureObservable == null) {
pressureObservable = Observable.create(emitter -> pressureObserver = emitter);
pressureObservable = pressureObservable.share();
}
return pressureObservable;
}
@Override
public void onDestroy() {
if(pressureListener != null)
sensorManager.unregisterListener(pressureListener);
}
}
```
And an Activity that binds to the service and receives pressure altitude updates:
```
public class TestActivity extends AppCompatActivity {
private ContentTestBinding binding;
private ServiceConnection serviceConnection;
private AndroidBmService service;
private Disposable disposable;
@Override
protected void onDestroy() {
if(disposable != null)
disposable.dispose();
unbindService(serviceConnection);
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.content_test);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
logMsg("BlueMAX service bound");
service = ((AndroidBmService.LocalBinder)iBinder).getService();
disposable = service.observePressure()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(altitude ->
binding.altitude.setText(
String.format(Locale.US,
"Pressure Altitude %d feet",
altitude.intValue())));
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
logMsg("Service disconnected");
}
};
bindService(new Intent(
this, AndroidBmService.class),
serviceConnection, BIND_AUTO_CREATE);
}
}
```
The layout for this Activity is:
```
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.controlj.mfgtest.TestActivity">
<TextView
tools:text="Pressure"
android:id="@+id/altitude"
android:gravity="center_horizontal"
android:layout_gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
```
If the service needs to run in the background without a bound Activity it can be started from the Application class as well in `OnCreate()` using [`Context#startService()`](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)).
---
**My Original Answer (from 2013):**
**In your service:** (using COPA as service in example below).
Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster:
```
broadcaster = LocalBroadcastManager.getInstance(this);
```
When you want to notify the UI of something:
```
static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";
static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";
public void sendResult(String message) {
Intent intent = new Intent(COPA_RESULT);
if(message != null)
intent.putExtra(COPA_MESSAGE, message);
broadcaster.sendBroadcast(intent);
}
```
**In your Activity:**
Create a listener on onCreate:
```
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.copa);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s = intent.getStringExtra(COPAService.COPA_MESSAGE);
// do something here.
}
};
}
```
and register it in onStart:
```
@Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((receiver),
new IntentFilter(COPAService.COPA_RESULT)
);
}
@Override
protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onStop();
}
``` | My solution might not be the cleanest but it should work with no problems.
The logic is simply to create a static variable to store your data on the `Service` and update your view each second on your `Activity`.
Let's say that you have a `String` on your `Service` that you want to send it to a `TextView` on your `Activity`. It should look like this
Your Service:
```
public class TestService extends Service {
public static String myString = "";
// Do some stuff with myString
```
Your Activty:
```
public class TestActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
update();
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
update();
}
});
}
} catch (InterruptedException ignored) {}
}
};
t.start();
startService(new Intent(this, TestService.class));
}
private void update() {
// update your interface here
tv.setText(TestService.myString);
}
}
``` |
14,695,580 | I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.
The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.
The file I'm trying to access looks like this inside my visual studio solution explorer
AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)
**Here is the routing for the portable area:**
```
using System.Web.Mvc;
using MvcContrib.PortableAreas;
namespace AdHocReporting.Areas.AdHocReportBuilder
{
public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
{
public override string AreaName
{
get { return "AdHocReportBuilder"; }
}
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
RegisterRoutes(context);
RegisterAreaEmbeddedResources();
}
private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_content",
base.AreaRoutePrefix + "/Content/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
new[] { "MvcContrib.PortableAreas" }
);
context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
**Here is the Web sites Global.aspx that has the reference to the portable area**
```
namespace AdHocReportingSite
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
PortableAreaRegistration.RegisterEmbeddedViewEngine();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
**here is an image of what my solution explore looks like:**
![Solution Explorer](https://i.stack.imgur.com/6P0TK.png) | 2013/02/04 | ['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/'] | See below for my original answer - that pattern has worked well, but recently I've started using a different approach to Service/Activity communication:
* Use a [bound service](https://developer.android.com/guide/components/bound-services.html) which enables the Activity to get a direct
reference to the Service, thus allowing direct calls on it, rather
than using Intents.
* Use RxJava to execute asynchronous operations.
* If the Service needs to continue background operations even when no
Activity is running, also start the service from the Application
class so that it does not get stopped when unbound.
The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are
* No need for data objects to implement Parcelable - this is particularly important to me as I am now sharing code between Android and iOS (using RoboVM)
* RxJava provides canned (and cross-platform) scheduling, and easy composition of sequential asynchronous operations.
* This should be more efficient than using a LocalBroadcast, though the overhead of using RxJava may outweigh that.
Some example code. First the service:
```
public class AndroidBmService extends Service implements BmService {
private static final int PRESSURE_RATE = 500000; // microseconds between pressure updates
private SensorManager sensorManager;
private SensorEventListener pressureListener;
private ObservableEmitter<Float> pressureObserver;
private Observable<Float> pressureObservable;
public class LocalBinder extends Binder {
public AndroidBmService getService() {
return AndroidBmService.this;
}
}
private IBinder binder = new LocalBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
logMsg("Service bound");
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if(pressureSensor != null)
sensorManager.registerListener(pressureListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if(pressureObserver != null) {
float lastPressure = event.values[0];
float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45);
pressureObserver.onNext(lastPressureAltitude);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}, pressureSensor, PRESSURE_RATE);
}
@Override
public Observable<Float> observePressure() {
if(pressureObservable == null) {
pressureObservable = Observable.create(emitter -> pressureObserver = emitter);
pressureObservable = pressureObservable.share();
}
return pressureObservable;
}
@Override
public void onDestroy() {
if(pressureListener != null)
sensorManager.unregisterListener(pressureListener);
}
}
```
And an Activity that binds to the service and receives pressure altitude updates:
```
public class TestActivity extends AppCompatActivity {
private ContentTestBinding binding;
private ServiceConnection serviceConnection;
private AndroidBmService service;
private Disposable disposable;
@Override
protected void onDestroy() {
if(disposable != null)
disposable.dispose();
unbindService(serviceConnection);
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.content_test);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
logMsg("BlueMAX service bound");
service = ((AndroidBmService.LocalBinder)iBinder).getService();
disposable = service.observePressure()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(altitude ->
binding.altitude.setText(
String.format(Locale.US,
"Pressure Altitude %d feet",
altitude.intValue())));
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
logMsg("Service disconnected");
}
};
bindService(new Intent(
this, AndroidBmService.class),
serviceConnection, BIND_AUTO_CREATE);
}
}
```
The layout for this Activity is:
```
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.controlj.mfgtest.TestActivity">
<TextView
tools:text="Pressure"
android:id="@+id/altitude"
android:gravity="center_horizontal"
android:layout_gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
```
If the service needs to run in the background without a bound Activity it can be started from the Application class as well in `OnCreate()` using [`Context#startService()`](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)).
---
**My Original Answer (from 2013):**
**In your service:** (using COPA as service in example below).
Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster:
```
broadcaster = LocalBroadcastManager.getInstance(this);
```
When you want to notify the UI of something:
```
static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";
static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";
public void sendResult(String message) {
Intent intent = new Intent(COPA_RESULT);
if(message != null)
intent.putExtra(COPA_MESSAGE, message);
broadcaster.sendBroadcast(intent);
}
```
**In your Activity:**
Create a listener on onCreate:
```
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.copa);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s = intent.getStringExtra(COPAService.COPA_MESSAGE);
// do something here.
}
};
}
```
and register it in onStart:
```
@Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((receiver),
new IntentFilter(COPAService.COPA_RESULT)
);
}
@Override
protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onStop();
}
``` | I would use a [bound service](http://developer.android.com/guide/components/bound-services.html) to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there! |
14,695,580 | I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.
The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.
The file I'm trying to access looks like this inside my visual studio solution explorer
AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)
**Here is the routing for the portable area:**
```
using System.Web.Mvc;
using MvcContrib.PortableAreas;
namespace AdHocReporting.Areas.AdHocReportBuilder
{
public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
{
public override string AreaName
{
get { return "AdHocReportBuilder"; }
}
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
RegisterRoutes(context);
RegisterAreaEmbeddedResources();
}
private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_content",
base.AreaRoutePrefix + "/Content/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
new[] { "MvcContrib.PortableAreas" }
);
context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
**Here is the Web sites Global.aspx that has the reference to the portable area**
```
namespace AdHocReportingSite
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
PortableAreaRegistration.RegisterEmbeddedViewEngine();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
**here is an image of what my solution explore looks like:**
![Solution Explorer](https://i.stack.imgur.com/6P0TK.png) | 2013/02/04 | ['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/'] | ```
Callback from service to activity to update UI.
ResultReceiver receiver = new ResultReceiver(new Handler()) {
protected void onReceiveResult(int resultCode, Bundle resultData) {
//process results or update UI
}
}
Intent instructionServiceIntent = new Intent(context, InstructionService.class);
instructionServiceIntent.putExtra("receiver", receiver);
context.startService(instructionServiceIntent);
``` | My solution might not be the cleanest but it should work with no problems.
The logic is simply to create a static variable to store your data on the `Service` and update your view each second on your `Activity`.
Let's say that you have a `String` on your `Service` that you want to send it to a `TextView` on your `Activity`. It should look like this
Your Service:
```
public class TestService extends Service {
public static String myString = "";
// Do some stuff with myString
```
Your Activty:
```
public class TestActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
update();
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
update();
}
});
}
} catch (InterruptedException ignored) {}
}
};
t.start();
startService(new Intent(this, TestService.class));
}
private void update() {
// update your interface here
tv.setText(TestService.myString);
}
}
``` |
14,695,580 | I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.
The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.
The file I'm trying to access looks like this inside my visual studio solution explorer
AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)
**Here is the routing for the portable area:**
```
using System.Web.Mvc;
using MvcContrib.PortableAreas;
namespace AdHocReporting.Areas.AdHocReportBuilder
{
public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
{
public override string AreaName
{
get { return "AdHocReportBuilder"; }
}
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
RegisterRoutes(context);
RegisterAreaEmbeddedResources();
}
private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_content",
base.AreaRoutePrefix + "/Content/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
new[] { "MvcContrib.PortableAreas" }
);
context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
**Here is the Web sites Global.aspx that has the reference to the portable area**
```
namespace AdHocReportingSite
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
PortableAreaRegistration.RegisterEmbeddedViewEngine();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
**here is an image of what my solution explore looks like:**
![Solution Explorer](https://i.stack.imgur.com/6P0TK.png) | 2013/02/04 | ['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/'] | for me the simplest solution was to send a broadcast, in the activity oncreate i registered and defined the broadcast like this (updateUIReciver is defined as a class instance) :
```
IntentFilter filter = new IntentFilter();
filter.addAction("com.hello.action");
updateUIReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//UI update here
}
};
registerReceiver(updateUIReciver,filter);
```
And from the service you send the intent like this:
```
Intent local = new Intent();
local.setAction("com.hello.action");
this.sendBroadcast(local);
```
don't forget to unregister the recover in the activity on destroy :
```
unregisterReceiver(updateUIReciver);
``` | My solution might not be the cleanest but it should work with no problems.
The logic is simply to create a static variable to store your data on the `Service` and update your view each second on your `Activity`.
Let's say that you have a `String` on your `Service` that you want to send it to a `TextView` on your `Activity`. It should look like this
Your Service:
```
public class TestService extends Service {
public static String myString = "";
// Do some stuff with myString
```
Your Activty:
```
public class TestActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
update();
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
update();
}
});
}
} catch (InterruptedException ignored) {}
}
};
t.start();
startService(new Intent(this, TestService.class));
}
private void update() {
// update your interface here
tv.setText(TestService.myString);
}
}
``` |
14,695,580 | I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.
The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.
The file I'm trying to access looks like this inside my visual studio solution explorer
AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)
**Here is the routing for the portable area:**
```
using System.Web.Mvc;
using MvcContrib.PortableAreas;
namespace AdHocReporting.Areas.AdHocReportBuilder
{
public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
{
public override string AreaName
{
get { return "AdHocReportBuilder"; }
}
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
RegisterRoutes(context);
RegisterAreaEmbeddedResources();
}
private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_content",
base.AreaRoutePrefix + "/Content/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
new[] { "MvcContrib.PortableAreas" }
);
context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
**Here is the Web sites Global.aspx that has the reference to the portable area**
```
namespace AdHocReportingSite
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
PortableAreaRegistration.RegisterEmbeddedViewEngine();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
**here is an image of what my solution explore looks like:**
![Solution Explorer](https://i.stack.imgur.com/6P0TK.png) | 2013/02/04 | ['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/'] | I would use a [bound service](http://developer.android.com/guide/components/bound-services.html) to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there! | My solution might not be the cleanest but it should work with no problems.
The logic is simply to create a static variable to store your data on the `Service` and update your view each second on your `Activity`.
Let's say that you have a `String` on your `Service` that you want to send it to a `TextView` on your `Activity`. It should look like this
Your Service:
```
public class TestService extends Service {
public static String myString = "";
// Do some stuff with myString
```
Your Activty:
```
public class TestActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
update();
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
update();
}
});
}
} catch (InterruptedException ignored) {}
}
};
t.start();
startService(new Intent(this, TestService.class));
}
private void update() {
// update your interface here
tv.setText(TestService.myString);
}
}
``` |
14,695,580 | I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.
The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.
The file I'm trying to access looks like this inside my visual studio solution explorer
AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)
**Here is the routing for the portable area:**
```
using System.Web.Mvc;
using MvcContrib.PortableAreas;
namespace AdHocReporting.Areas.AdHocReportBuilder
{
public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
{
public override string AreaName
{
get { return "AdHocReportBuilder"; }
}
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
RegisterRoutes(context);
RegisterAreaEmbeddedResources();
}
private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_content",
base.AreaRoutePrefix + "/Content/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
new[] { "MvcContrib.PortableAreas" }
);
context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
**Here is the Web sites Global.aspx that has the reference to the portable area**
```
namespace AdHocReportingSite
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
PortableAreaRegistration.RegisterEmbeddedViewEngine();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
**here is an image of what my solution explore looks like:**
![Solution Explorer](https://i.stack.imgur.com/6P0TK.png) | 2013/02/04 | ['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/'] | Clyde's solution works, but it is a broadcast, which I am pretty sure will be less efficient than calling a method directly. I could be mistaken, but I think the broadcasts are meant more for inter-application communication.
I'm assuming you already know how to bind a service with an Activity.
I do something sort of like the code below to handle this kind of problem:
```
class MyService extends Service {
MyFragment mMyFragment = null;
MyFragment mMyOtherFragment = null;
private void networkLoop() {
...
//received new data for list.
if(myFragment != null)
myFragment.updateList();
}
...
//received new data for textView
if(myFragment !=null)
myFragment.updateText();
...
//received new data for textView
if(myOtherFragment !=null)
myOtherFragment.updateSomething();
...
}
}
class MyFragment extends Fragment {
public void onResume() {
super.onResume()
//Assuming your activity bound to your service
getActivity().mMyService.mMyFragment=this;
}
public void onPause() {
super.onPause()
//Assuming your activity bound to your service
getActivity().mMyService.mMyFragment=null;
}
public void updateList() {
runOnUiThread(new Runnable() {
public void run() {
//Update the list.
}
});
}
public void updateText() {
//as above
}
}
class MyOtherFragment extends Fragment {
public void onResume() {
super.onResume()
//Assuming your activity bound to your service
getActivity().mMyService.mMyOtherFragment=this;
}
public void onPause() {
super.onPause()
//Assuming your activity bound to your service
getActivity().mMyService.mMyOtherFragment=null;
}
public void updateSomething() {//etc... }
}
```
I left out bits for thread safety, which is essential. Make sure to use locks or something like that when checking and using or changing the fragment references on the service. | You could use android Jetpack's [LiveData](https://developer.android.com/topic/libraries/architecture/livedata)
As per the documentation:
>
> You can extend a `LiveData` object using the singleton pattern to wrap
> system services so that they can be shared in your app. The LiveData
> object connects to the system service once, and then any observer that
> needs the resource can just watch the LiveData object. For more
> information, see [Extend
> LiveData](https://developer.android.com/topic/libraries/architecture/livedata?hl=en#extend_livedata).
>
>
>
Below is what I did for communication between Service and Activity and also Service and Fragment.
In this example, I have:
* a class `SyncLogLiveData` extending `LiveData` that contains a `SpannableStringBuilder`
* a service `SyncService`
* a fragment `SyncFragment`
The Fragment "observes" the LiveData (ie SyncLogLiveData) and performs an action when the LiveData changes.
The LiveData is updated by the Service.
I could also update the LiveData from the Fragment in the same way but don't show it here.
**class `SyncLogLiveData`**
```java
public class SyncLogLiveData extends LiveData<SpannableStringBuilder> {
private static SyncLogLiveData sInstance;
private final static SpannableStringBuilder log = new SpannableStringBuilder("");
@MainThread
public static SyncLogLiveData get() {
if (sInstance == null) {
sInstance = new SyncLogLiveData();
}
return sInstance;
}
private SyncLogLiveData() {
}
public void appendLog(String text) {
log.append(text);
postValue(log);
}
public void appendLog(Spanned text) {
log.append(text);
postValue(log);
}
}
```
**in class `SyncService`**
This line of code will update the content of the LiveData
```java
SyncLogLiveData.get().appendLog(message);
```
You could also make direct use of `setValue(...)` or `postValue(...)` methods of `LiveData`
```java
SyncLogLiveData.get().setValue(message);
```
**class SyncFragment**
```java
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
//...
// Create the observer which updates the UI.
final Observer<SpannableStringBuilder> ETAObserver = new Observer<SpannableStringBuilder>() {
@Override
public void onChanged(@Nullable final SpannableStringBuilder spannableLog) {
// Update the UI, in this case, a TextView.
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
textViewLog.setText(spannableLog);
}
});
}
};
// Observe the LiveData, passing in this activity/fragment as the LifecycleOwner and the observer.
SyncLogLiveData.get().observe(getViewLifecycleOwner(), ETAObserver);
//...
}
```
From within an activity it works the same way, but for `.observe(...)`, you may use this instead
```java
SyncLogLiveData.get().observe(this, ETAObserver);
```
You could also fetch the current value of the LiveData this way at anytime in your code.
```java
SyncLogLiveData.get().getValue();
```
Hopefully this will help someone. There wasn't any mention of LiveData in this answer yet. |
14,695,580 | I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.
The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.
The file I'm trying to access looks like this inside my visual studio solution explorer
AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)
**Here is the routing for the portable area:**
```
using System.Web.Mvc;
using MvcContrib.PortableAreas;
namespace AdHocReporting.Areas.AdHocReportBuilder
{
public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
{
public override string AreaName
{
get { return "AdHocReportBuilder"; }
}
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
RegisterRoutes(context);
RegisterAreaEmbeddedResources();
}
private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_content",
base.AreaRoutePrefix + "/Content/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
new[] { "MvcContrib.PortableAreas" }
);
context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
**Here is the Web sites Global.aspx that has the reference to the portable area**
```
namespace AdHocReportingSite
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
PortableAreaRegistration.RegisterEmbeddedViewEngine();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
**here is an image of what my solution explore looks like:**
![Solution Explorer](https://i.stack.imgur.com/6P0TK.png) | 2013/02/04 | ['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/'] | See below for my original answer - that pattern has worked well, but recently I've started using a different approach to Service/Activity communication:
* Use a [bound service](https://developer.android.com/guide/components/bound-services.html) which enables the Activity to get a direct
reference to the Service, thus allowing direct calls on it, rather
than using Intents.
* Use RxJava to execute asynchronous operations.
* If the Service needs to continue background operations even when no
Activity is running, also start the service from the Application
class so that it does not get stopped when unbound.
The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are
* No need for data objects to implement Parcelable - this is particularly important to me as I am now sharing code between Android and iOS (using RoboVM)
* RxJava provides canned (and cross-platform) scheduling, and easy composition of sequential asynchronous operations.
* This should be more efficient than using a LocalBroadcast, though the overhead of using RxJava may outweigh that.
Some example code. First the service:
```
public class AndroidBmService extends Service implements BmService {
private static final int PRESSURE_RATE = 500000; // microseconds between pressure updates
private SensorManager sensorManager;
private SensorEventListener pressureListener;
private ObservableEmitter<Float> pressureObserver;
private Observable<Float> pressureObservable;
public class LocalBinder extends Binder {
public AndroidBmService getService() {
return AndroidBmService.this;
}
}
private IBinder binder = new LocalBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
logMsg("Service bound");
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if(pressureSensor != null)
sensorManager.registerListener(pressureListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if(pressureObserver != null) {
float lastPressure = event.values[0];
float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45);
pressureObserver.onNext(lastPressureAltitude);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}, pressureSensor, PRESSURE_RATE);
}
@Override
public Observable<Float> observePressure() {
if(pressureObservable == null) {
pressureObservable = Observable.create(emitter -> pressureObserver = emitter);
pressureObservable = pressureObservable.share();
}
return pressureObservable;
}
@Override
public void onDestroy() {
if(pressureListener != null)
sensorManager.unregisterListener(pressureListener);
}
}
```
And an Activity that binds to the service and receives pressure altitude updates:
```
public class TestActivity extends AppCompatActivity {
private ContentTestBinding binding;
private ServiceConnection serviceConnection;
private AndroidBmService service;
private Disposable disposable;
@Override
protected void onDestroy() {
if(disposable != null)
disposable.dispose();
unbindService(serviceConnection);
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.content_test);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
logMsg("BlueMAX service bound");
service = ((AndroidBmService.LocalBinder)iBinder).getService();
disposable = service.observePressure()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(altitude ->
binding.altitude.setText(
String.format(Locale.US,
"Pressure Altitude %d feet",
altitude.intValue())));
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
logMsg("Service disconnected");
}
};
bindService(new Intent(
this, AndroidBmService.class),
serviceConnection, BIND_AUTO_CREATE);
}
}
```
The layout for this Activity is:
```
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.controlj.mfgtest.TestActivity">
<TextView
tools:text="Pressure"
android:id="@+id/altitude"
android:gravity="center_horizontal"
android:layout_gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
```
If the service needs to run in the background without a bound Activity it can be started from the Application class as well in `OnCreate()` using [`Context#startService()`](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)).
---
**My Original Answer (from 2013):**
**In your service:** (using COPA as service in example below).
Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster:
```
broadcaster = LocalBroadcastManager.getInstance(this);
```
When you want to notify the UI of something:
```
static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";
static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";
public void sendResult(String message) {
Intent intent = new Intent(COPA_RESULT);
if(message != null)
intent.putExtra(COPA_MESSAGE, message);
broadcaster.sendBroadcast(intent);
}
```
**In your Activity:**
Create a listener on onCreate:
```
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.copa);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s = intent.getStringExtra(COPAService.COPA_MESSAGE);
// do something here.
}
};
}
```
and register it in onStart:
```
@Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((receiver),
new IntentFilter(COPAService.COPA_RESULT)
);
}
@Override
protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onStop();
}
``` | You could use android Jetpack's [LiveData](https://developer.android.com/topic/libraries/architecture/livedata)
As per the documentation:
>
> You can extend a `LiveData` object using the singleton pattern to wrap
> system services so that they can be shared in your app. The LiveData
> object connects to the system service once, and then any observer that
> needs the resource can just watch the LiveData object. For more
> information, see [Extend
> LiveData](https://developer.android.com/topic/libraries/architecture/livedata?hl=en#extend_livedata).
>
>
>
Below is what I did for communication between Service and Activity and also Service and Fragment.
In this example, I have:
* a class `SyncLogLiveData` extending `LiveData` that contains a `SpannableStringBuilder`
* a service `SyncService`
* a fragment `SyncFragment`
The Fragment "observes" the LiveData (ie SyncLogLiveData) and performs an action when the LiveData changes.
The LiveData is updated by the Service.
I could also update the LiveData from the Fragment in the same way but don't show it here.
**class `SyncLogLiveData`**
```java
public class SyncLogLiveData extends LiveData<SpannableStringBuilder> {
private static SyncLogLiveData sInstance;
private final static SpannableStringBuilder log = new SpannableStringBuilder("");
@MainThread
public static SyncLogLiveData get() {
if (sInstance == null) {
sInstance = new SyncLogLiveData();
}
return sInstance;
}
private SyncLogLiveData() {
}
public void appendLog(String text) {
log.append(text);
postValue(log);
}
public void appendLog(Spanned text) {
log.append(text);
postValue(log);
}
}
```
**in class `SyncService`**
This line of code will update the content of the LiveData
```java
SyncLogLiveData.get().appendLog(message);
```
You could also make direct use of `setValue(...)` or `postValue(...)` methods of `LiveData`
```java
SyncLogLiveData.get().setValue(message);
```
**class SyncFragment**
```java
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
//...
// Create the observer which updates the UI.
final Observer<SpannableStringBuilder> ETAObserver = new Observer<SpannableStringBuilder>() {
@Override
public void onChanged(@Nullable final SpannableStringBuilder spannableLog) {
// Update the UI, in this case, a TextView.
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
textViewLog.setText(spannableLog);
}
});
}
};
// Observe the LiveData, passing in this activity/fragment as the LifecycleOwner and the observer.
SyncLogLiveData.get().observe(getViewLifecycleOwner(), ETAObserver);
//...
}
```
From within an activity it works the same way, but for `.observe(...)`, you may use this instead
```java
SyncLogLiveData.get().observe(this, ETAObserver);
```
You could also fetch the current value of the LiveData this way at anytime in your code.
```java
SyncLogLiveData.get().getValue();
```
Hopefully this will help someone. There wasn't any mention of LiveData in this answer yet. |
14,695,580 | I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.
The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.
The file I'm trying to access looks like this inside my visual studio solution explorer
AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)
**Here is the routing for the portable area:**
```
using System.Web.Mvc;
using MvcContrib.PortableAreas;
namespace AdHocReporting.Areas.AdHocReportBuilder
{
public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
{
public override string AreaName
{
get { return "AdHocReportBuilder"; }
}
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
RegisterRoutes(context);
RegisterAreaEmbeddedResources();
}
private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_content",
base.AreaRoutePrefix + "/Content/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
new[] { "MvcContrib.PortableAreas" }
);
context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
**Here is the Web sites Global.aspx that has the reference to the portable area**
```
namespace AdHocReportingSite
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
PortableAreaRegistration.RegisterEmbeddedViewEngine();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
**here is an image of what my solution explore looks like:**
![Solution Explorer](https://i.stack.imgur.com/6P0TK.png) | 2013/02/04 | ['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/'] | I would use a [bound service](http://developer.android.com/guide/components/bound-services.html) to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there! | You could use android Jetpack's [LiveData](https://developer.android.com/topic/libraries/architecture/livedata)
As per the documentation:
>
> You can extend a `LiveData` object using the singleton pattern to wrap
> system services so that they can be shared in your app. The LiveData
> object connects to the system service once, and then any observer that
> needs the resource can just watch the LiveData object. For more
> information, see [Extend
> LiveData](https://developer.android.com/topic/libraries/architecture/livedata?hl=en#extend_livedata).
>
>
>
Below is what I did for communication between Service and Activity and also Service and Fragment.
In this example, I have:
* a class `SyncLogLiveData` extending `LiveData` that contains a `SpannableStringBuilder`
* a service `SyncService`
* a fragment `SyncFragment`
The Fragment "observes" the LiveData (ie SyncLogLiveData) and performs an action when the LiveData changes.
The LiveData is updated by the Service.
I could also update the LiveData from the Fragment in the same way but don't show it here.
**class `SyncLogLiveData`**
```java
public class SyncLogLiveData extends LiveData<SpannableStringBuilder> {
private static SyncLogLiveData sInstance;
private final static SpannableStringBuilder log = new SpannableStringBuilder("");
@MainThread
public static SyncLogLiveData get() {
if (sInstance == null) {
sInstance = new SyncLogLiveData();
}
return sInstance;
}
private SyncLogLiveData() {
}
public void appendLog(String text) {
log.append(text);
postValue(log);
}
public void appendLog(Spanned text) {
log.append(text);
postValue(log);
}
}
```
**in class `SyncService`**
This line of code will update the content of the LiveData
```java
SyncLogLiveData.get().appendLog(message);
```
You could also make direct use of `setValue(...)` or `postValue(...)` methods of `LiveData`
```java
SyncLogLiveData.get().setValue(message);
```
**class SyncFragment**
```java
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
//...
// Create the observer which updates the UI.
final Observer<SpannableStringBuilder> ETAObserver = new Observer<SpannableStringBuilder>() {
@Override
public void onChanged(@Nullable final SpannableStringBuilder spannableLog) {
// Update the UI, in this case, a TextView.
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
textViewLog.setText(spannableLog);
}
});
}
};
// Observe the LiveData, passing in this activity/fragment as the LifecycleOwner and the observer.
SyncLogLiveData.get().observe(getViewLifecycleOwner(), ETAObserver);
//...
}
```
From within an activity it works the same way, but for `.observe(...)`, you may use this instead
```java
SyncLogLiveData.get().observe(this, ETAObserver);
```
You could also fetch the current value of the LiveData this way at anytime in your code.
```java
SyncLogLiveData.get().getValue();
```
Hopefully this will help someone. There wasn't any mention of LiveData in this answer yet. |
14,695,580 | I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.
The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.
The file I'm trying to access looks like this inside my visual studio solution explorer
AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)
**Here is the routing for the portable area:**
```
using System.Web.Mvc;
using MvcContrib.PortableAreas;
namespace AdHocReporting.Areas.AdHocReportBuilder
{
public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
{
public override string AreaName
{
get { return "AdHocReportBuilder"; }
}
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
RegisterRoutes(context);
RegisterAreaEmbeddedResources();
}
private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_content",
base.AreaRoutePrefix + "/Content/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
new[] { "MvcContrib.PortableAreas" }
);
context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
**Here is the Web sites Global.aspx that has the reference to the portable area**
```
namespace AdHocReportingSite
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
PortableAreaRegistration.RegisterEmbeddedViewEngine();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
**here is an image of what my solution explore looks like:**
![Solution Explorer](https://i.stack.imgur.com/6P0TK.png) | 2013/02/04 | ['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/'] | See below for my original answer - that pattern has worked well, but recently I've started using a different approach to Service/Activity communication:
* Use a [bound service](https://developer.android.com/guide/components/bound-services.html) which enables the Activity to get a direct
reference to the Service, thus allowing direct calls on it, rather
than using Intents.
* Use RxJava to execute asynchronous operations.
* If the Service needs to continue background operations even when no
Activity is running, also start the service from the Application
class so that it does not get stopped when unbound.
The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are
* No need for data objects to implement Parcelable - this is particularly important to me as I am now sharing code between Android and iOS (using RoboVM)
* RxJava provides canned (and cross-platform) scheduling, and easy composition of sequential asynchronous operations.
* This should be more efficient than using a LocalBroadcast, though the overhead of using RxJava may outweigh that.
Some example code. First the service:
```
public class AndroidBmService extends Service implements BmService {
private static final int PRESSURE_RATE = 500000; // microseconds between pressure updates
private SensorManager sensorManager;
private SensorEventListener pressureListener;
private ObservableEmitter<Float> pressureObserver;
private Observable<Float> pressureObservable;
public class LocalBinder extends Binder {
public AndroidBmService getService() {
return AndroidBmService.this;
}
}
private IBinder binder = new LocalBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
logMsg("Service bound");
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if(pressureSensor != null)
sensorManager.registerListener(pressureListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if(pressureObserver != null) {
float lastPressure = event.values[0];
float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45);
pressureObserver.onNext(lastPressureAltitude);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}, pressureSensor, PRESSURE_RATE);
}
@Override
public Observable<Float> observePressure() {
if(pressureObservable == null) {
pressureObservable = Observable.create(emitter -> pressureObserver = emitter);
pressureObservable = pressureObservable.share();
}
return pressureObservable;
}
@Override
public void onDestroy() {
if(pressureListener != null)
sensorManager.unregisterListener(pressureListener);
}
}
```
And an Activity that binds to the service and receives pressure altitude updates:
```
public class TestActivity extends AppCompatActivity {
private ContentTestBinding binding;
private ServiceConnection serviceConnection;
private AndroidBmService service;
private Disposable disposable;
@Override
protected void onDestroy() {
if(disposable != null)
disposable.dispose();
unbindService(serviceConnection);
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.content_test);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
logMsg("BlueMAX service bound");
service = ((AndroidBmService.LocalBinder)iBinder).getService();
disposable = service.observePressure()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(altitude ->
binding.altitude.setText(
String.format(Locale.US,
"Pressure Altitude %d feet",
altitude.intValue())));
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
logMsg("Service disconnected");
}
};
bindService(new Intent(
this, AndroidBmService.class),
serviceConnection, BIND_AUTO_CREATE);
}
}
```
The layout for this Activity is:
```
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.controlj.mfgtest.TestActivity">
<TextView
tools:text="Pressure"
android:id="@+id/altitude"
android:gravity="center_horizontal"
android:layout_gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
```
If the service needs to run in the background without a bound Activity it can be started from the Application class as well in `OnCreate()` using [`Context#startService()`](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)).
---
**My Original Answer (from 2013):**
**In your service:** (using COPA as service in example below).
Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster:
```
broadcaster = LocalBroadcastManager.getInstance(this);
```
When you want to notify the UI of something:
```
static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";
static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";
public void sendResult(String message) {
Intent intent = new Intent(COPA_RESULT);
if(message != null)
intent.putExtra(COPA_MESSAGE, message);
broadcaster.sendBroadcast(intent);
}
```
**In your Activity:**
Create a listener on onCreate:
```
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.copa);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s = intent.getStringExtra(COPAService.COPA_MESSAGE);
// do something here.
}
};
}
```
and register it in onStart:
```
@Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((receiver),
new IntentFilter(COPAService.COPA_RESULT)
);
}
@Override
protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onStop();
}
``` | for me the simplest solution was to send a broadcast, in the activity oncreate i registered and defined the broadcast like this (updateUIReciver is defined as a class instance) :
```
IntentFilter filter = new IntentFilter();
filter.addAction("com.hello.action");
updateUIReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//UI update here
}
};
registerReceiver(updateUIReciver,filter);
```
And from the service you send the intent like this:
```
Intent local = new Intent();
local.setAction("com.hello.action");
this.sendBroadcast(local);
```
don't forget to unregister the recover in the activity on destroy :
```
unregisterReceiver(updateUIReciver);
``` |
14,695,580 | I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.
The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.
The file I'm trying to access looks like this inside my visual studio solution explorer
AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)
**Here is the routing for the portable area:**
```
using System.Web.Mvc;
using MvcContrib.PortableAreas;
namespace AdHocReporting.Areas.AdHocReportBuilder
{
public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
{
public override string AreaName
{
get { return "AdHocReportBuilder"; }
}
public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
{
RegisterRoutes(context);
RegisterAreaEmbeddedResources();
}
private void RegisterRoutes(AreaRegistrationContext context)
{
context.MapRoute(
AreaName + "_content",
base.AreaRoutePrefix + "/Content/{resourceName}",
new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
new[] { "MvcContrib.PortableAreas" }
);
context.MapRoute(
AreaName + "_default",
base.AreaRoutePrefix + "/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
**Here is the Web sites Global.aspx that has the reference to the portable area**
```
namespace AdHocReportingSite
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
PortableAreaRegistration.RegisterEmbeddedViewEngine();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
```
**here is an image of what my solution explore looks like:**
![Solution Explorer](https://i.stack.imgur.com/6P0TK.png) | 2013/02/04 | ['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/'] | for me the simplest solution was to send a broadcast, in the activity oncreate i registered and defined the broadcast like this (updateUIReciver is defined as a class instance) :
```
IntentFilter filter = new IntentFilter();
filter.addAction("com.hello.action");
updateUIReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//UI update here
}
};
registerReceiver(updateUIReciver,filter);
```
And from the service you send the intent like this:
```
Intent local = new Intent();
local.setAction("com.hello.action");
this.sendBroadcast(local);
```
don't forget to unregister the recover in the activity on destroy :
```
unregisterReceiver(updateUIReciver);
``` | I would use a [bound service](http://developer.android.com/guide/components/bound-services.html) to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there! |
57,344,515 | I am trying to get serialized data for the below model with foreign keys but in the output i am only getting the ids instead of the fields of the model associated with hyperlink.
I have tried getting all the fields of the Skills model using the commented lines in the profile serializer but no luck
models.py
```
class Profile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
first_name = models.CharField(max_length=20, null=True)
last_name = models.CharField(max_length=20, null=True)
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
class Skill(models.Model):
skill = models.CharField(max_length=20, null=True)
level = models.CharField(max_length=20, null=True)
user = models.ForeignKey(Profile, null=True,
on_delete=models.PROTECT, related_name='skills')
def __str__(self):
return '%s: %s: %s' % (self.user, self.skill, self.level)
```
serializer.py
```
class SkillSerializer(serializers.ModelSerializer):
class Meta:
model = Skill
fields = ('user', 'skill', 'level')
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
# skills = SkillSerializer(many=True, read_only=True) # serializes child model's data inside this model's data
# skills = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='skill-detail')
# skills = serializers.StringRelatedField(many=True)
# skills = serializers.HyperlinkedIdentityField( view_name = "skill-list", lookup_field = "user")
url = HyperlinkedIdentityField( view_name="profile-detail", lookup_field = "id")
# user = serializers.ReadOnlyField(source='user.username')
# pdb.set_trace()
model = Profile
fields = ['id', 'user', 'url', 'skills']
```
views.py
```
class ProfileList(generics.ListCreateAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
class ProfileDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
class SkillList(generics.ListCreateAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
class SkillDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
```
urls.py
```
path('profiles/', views.ProfileList.as_view(), name='profile-list'),
path('profiles/<int:pk>/', views.ProfileDetail.as_view(), name='profile-detail'),
path('skills/', views.SkillList.as_view(), name='profile-list'),
path('skills/<int:pk>/', views.SkillDetail.as_view(), name='skill-list'),
```
Output: <http://127.0.0.1:8000/authenticator/profiles/>
```
[ "id": 6,
"user": 4,
"url": "http://127.0.0.1:8000/authenticator/profiles/6/",
"skills": [
57,
55
],
]
```
Expected output:
```
[ "id": 6,
"user": 4,
"url": "http://127.0.0.1:8000/authenticator/profiles/6/",
"skills": [
{
"user": 6,
"skill": "ABC",
"level": "Beginner"
},
{
"user": 6,
"skill": "DEF",
"level": "Intermediate"
},
]
]
``` | 2019/08/04 | ['https://Stackoverflow.com/questions/57344515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11879807/'] | This should normally work with the following in serializer.py:
```
class ProfileSerializer(serializers.ModelSerializer):
skills = SkillSerializer(many=True, read_only=True) # serializes child model's data inside this model's data
url = HyperlinkedIdentityField( view_name="profile-detail", lookup_field = "id")
class Meta:
model = Profile
fields = ['id', 'user', 'url', 'skills']
```
So basically uncomment the line in which the ProfileSerializer is told to serialize the skills with your SkillsSerializers, such that the entire skill objects are included in the result instead of its IDs. | You can use the concept of nested serializer for the solution.
Create two serializer `ProfileReadSerializer` and `ProfileWriteSerializer`
serializers.py
```py
class SkillSerializer(serializers.ModelSerializer):
class Meta:
model = Skill
fields = ('user', 'skill', 'level')
class ProfileReadSerializer(serializers.ModelSerializer):
skills = SkillSerializer(many=True, read_only=True)
url = HyperlinkedIdentityField( view_name="profile-detail", lookup_field = "id")
class Meta:
model = Profile
fields = ('id', 'user', 'url', 'skills')
class ProfileWriteSerializer(serializers.ModelSerializer):
skills = SkillSerializer(many=True)
class Meta:
model = Profile
fields = ('id', 'user', 'url', 'skills')
```
In views you simply can use `ModelViewSet` to make things easy and use `get_serializer_class`
views.py
```py
from rest_framework.viewsets import ModelViewSet
class ProfileVewSet(ModelViewSet):
queryset = Profile.objects.all()
def get_serializer_class(self):
if self.request.method == 'POST' or self.request.method == 'PUT' or self.request.method == 'PATCH':
return ProfileWriteSerializer
else:
return ProfileReadSerializer
```
And at last if you are using `ModelViewSet` you need to change the `urls.py`
urls.py
```py
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('profile', views.ProfileViewSet, base_name='profile')
urlpatterns = [
path('', include(router.urls))
]
```
I think this will solve your problem. Please have a look. |
53,660,611 | I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly.
My primary list is named data\_to\_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list.
How do I accomplish this?
This is my current code, which doesn't work as needed.
```
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
n = 100
x = list(divide_chunks(data_to_insert, 100))
```
Nestled list example:
```
data_to_insert = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[thousands of others lists go here]]
```
Desired output is another list (sliced\_data), which contains 100 lists from the nestled list (data\_to\_insert).
```
sliced_data = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[98 more lists go here]]
```
I need to loop through the nestled list, data\_to\_insert until it's empty. | 2018/12/06 | ['https://Stackoverflow.com/questions/53660611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083423/'] | You can use `random` to select `100` random nested lists from your given list.
This will output `3` random nested list from original list,
```
import random
l = [[1,2], [3,4], [1,1], [2,3], [3,5], [0,0]]
print(random.sample(l, 3))
# output,
[[3, 4], [1, 2], [2, 3]]
```
If you do not want a list output then replace `print(random.sample(l, 3))` with `print(*random.sample(l, 3))`,
```
# output,
[1, 2] [2, 3] [1, 1]
```
If you just want first `100` nested lists then do,
```
print(l[:100])
``` | If i did understand your question correctly, you need first to flatten your list of list then create a chunks of it. Here is an example using `chain.from_iterable` from `itertools module` along with the code you've used to create chunks:
```
from itertools import chain
def chunks(elm, length):
for k in range(0, len(elm), length):
yield elm[k: k + length]
my_list = [['item{}'.format(j) for j in range(7)]] * 1000
flattened = list(chain.from_iterable(my_list))
chunks = list(chunks(flattened, 100))
print(len(chunks[10]))
```
Output:
```
100
``` |
53,660,611 | I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly.
My primary list is named data\_to\_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list.
How do I accomplish this?
This is my current code, which doesn't work as needed.
```
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
n = 100
x = list(divide_chunks(data_to_insert, 100))
```
Nestled list example:
```
data_to_insert = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[thousands of others lists go here]]
```
Desired output is another list (sliced\_data), which contains 100 lists from the nestled list (data\_to\_insert).
```
sliced_data = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[98 more lists go here]]
```
I need to loop through the nestled list, data\_to\_insert until it's empty. | 2018/12/06 | ['https://Stackoverflow.com/questions/53660611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083423/'] | You can use `random` to select `100` random nested lists from your given list.
This will output `3` random nested list from original list,
```
import random
l = [[1,2], [3,4], [1,1], [2,3], [3,5], [0,0]]
print(random.sample(l, 3))
# output,
[[3, 4], [1, 2], [2, 3]]
```
If you do not want a list output then replace `print(random.sample(l, 3))` with `print(*random.sample(l, 3))`,
```
# output,
[1, 2] [2, 3] [1, 1]
```
If you just want first `100` nested lists then do,
```
print(l[:100])
``` | After some time-consuming research, I developed a solution that worked. The solution below loops through a list of lists and extract 100 lists.
```
# Verifies that the list data_to_insert isn't empty
if len(data_to_insert) > 0:
# Obtains the length of the data to insert.
# The length is the number of sublists
# contained in the main nestled list.
data_length = len(data_to_insert)
# A loop counter used in the
# data insert process.
i = 0
# The number of sublists to slice
# from the main nestled list in
# each loop.
n = 100
# This loop execute a set of statements
# as long as the condition below is true
while i < data_length:
# Increments the loop counter
if len(data_to_insert) < 100:
i += len(data_to_insert)
else:
i += 100
# Slices 100 sublists from the main nestled list.
sliced_data = data_to_insert[:n]
# Verifies that the list sliced_data isn't empty
if len(sliced_data) > 0:
# Removes 1000 sublists from the main nestled list.
data_to_insert = data_to_insert[n:]
##################################
do something with the sliced_data
##################################
# Clears the list used to store the
# sliced_data in the insertion loop.
sliced_data.clear()
gc.collect()
# Clears the list used to store the
# data elements inserted into the
# database.
data_to_insert.clear()
gc.collect()
``` |
53,660,611 | I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly.
My primary list is named data\_to\_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list.
How do I accomplish this?
This is my current code, which doesn't work as needed.
```
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
n = 100
x = list(divide_chunks(data_to_insert, 100))
```
Nestled list example:
```
data_to_insert = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[thousands of others lists go here]]
```
Desired output is another list (sliced\_data), which contains 100 lists from the nestled list (data\_to\_insert).
```
sliced_data = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[98 more lists go here]]
```
I need to loop through the nestled list, data\_to\_insert until it's empty. | 2018/12/06 | ['https://Stackoverflow.com/questions/53660611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083423/'] | You can use `random` to select `100` random nested lists from your given list.
This will output `3` random nested list from original list,
```
import random
l = [[1,2], [3,4], [1,1], [2,3], [3,5], [0,0]]
print(random.sample(l, 3))
# output,
[[3, 4], [1, 2], [2, 3]]
```
If you do not want a list output then replace `print(random.sample(l, 3))` with `print(*random.sample(l, 3))`,
```
# output,
[1, 2] [2, 3] [1, 1]
```
If you just want first `100` nested lists then do,
```
print(l[:100])
``` | I developed a second method to accomplish my objective, which is based on [Sufiyan Ghori](https://stackoverflow.com/users/1149423/sufiyan-ghori) suggestion of using `random.`
```
if len(my_nestled_list) > 0:
# Obtains the length of the data to insert.
# The length is the number of sublists
# contained in the main nestled list.
data_length = len(my_nestled_list))
# A loop counter used in the
# data insert process.
i = 0
# The number of sublists to slice
# from the main nestled list in
# each loop.
n = 100
# This loop execute a set of statements
# as long as the condition below is true
while i < data_length:
# Increments the loop counter
if len(my_nestled_list)) < 100:
i += len(my_nestled_list))
else:
i += 100
# Uses list comprehension to randomly select 100 lists
# from the nestled list.
random_sample_of_100 = [my_nestled_list)[i] for i in sorted(random.sample(range(len(my_nestled_list))), n))]
print (random_sample_of_100)
``` |
53,660,611 | I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly.
My primary list is named data\_to\_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list.
How do I accomplish this?
This is my current code, which doesn't work as needed.
```
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
n = 100
x = list(divide_chunks(data_to_insert, 100))
```
Nestled list example:
```
data_to_insert = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[thousands of others lists go here]]
```
Desired output is another list (sliced\_data), which contains 100 lists from the nestled list (data\_to\_insert).
```
sliced_data = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[98 more lists go here]]
```
I need to loop through the nestled list, data\_to\_insert until it's empty. | 2018/12/06 | ['https://Stackoverflow.com/questions/53660611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083423/'] | If i did understand your question correctly, you need first to flatten your list of list then create a chunks of it. Here is an example using `chain.from_iterable` from `itertools module` along with the code you've used to create chunks:
```
from itertools import chain
def chunks(elm, length):
for k in range(0, len(elm), length):
yield elm[k: k + length]
my_list = [['item{}'.format(j) for j in range(7)]] * 1000
flattened = list(chain.from_iterable(my_list))
chunks = list(chunks(flattened, 100))
print(len(chunks[10]))
```
Output:
```
100
``` | After some time-consuming research, I developed a solution that worked. The solution below loops through a list of lists and extract 100 lists.
```
# Verifies that the list data_to_insert isn't empty
if len(data_to_insert) > 0:
# Obtains the length of the data to insert.
# The length is the number of sublists
# contained in the main nestled list.
data_length = len(data_to_insert)
# A loop counter used in the
# data insert process.
i = 0
# The number of sublists to slice
# from the main nestled list in
# each loop.
n = 100
# This loop execute a set of statements
# as long as the condition below is true
while i < data_length:
# Increments the loop counter
if len(data_to_insert) < 100:
i += len(data_to_insert)
else:
i += 100
# Slices 100 sublists from the main nestled list.
sliced_data = data_to_insert[:n]
# Verifies that the list sliced_data isn't empty
if len(sliced_data) > 0:
# Removes 1000 sublists from the main nestled list.
data_to_insert = data_to_insert[n:]
##################################
do something with the sliced_data
##################################
# Clears the list used to store the
# sliced_data in the insertion loop.
sliced_data.clear()
gc.collect()
# Clears the list used to store the
# data elements inserted into the
# database.
data_to_insert.clear()
gc.collect()
``` |
53,660,611 | I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly.
My primary list is named data\_to\_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list.
How do I accomplish this?
This is my current code, which doesn't work as needed.
```
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
n = 100
x = list(divide_chunks(data_to_insert, 100))
```
Nestled list example:
```
data_to_insert = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[thousands of others lists go here]]
```
Desired output is another list (sliced\_data), which contains 100 lists from the nestled list (data\_to\_insert).
```
sliced_data = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[98 more lists go here]]
```
I need to loop through the nestled list, data\_to\_insert until it's empty. | 2018/12/06 | ['https://Stackoverflow.com/questions/53660611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083423/'] | If i did understand your question correctly, you need first to flatten your list of list then create a chunks of it. Here is an example using `chain.from_iterable` from `itertools module` along with the code you've used to create chunks:
```
from itertools import chain
def chunks(elm, length):
for k in range(0, len(elm), length):
yield elm[k: k + length]
my_list = [['item{}'.format(j) for j in range(7)]] * 1000
flattened = list(chain.from_iterable(my_list))
chunks = list(chunks(flattened, 100))
print(len(chunks[10]))
```
Output:
```
100
``` | I developed a second method to accomplish my objective, which is based on [Sufiyan Ghori](https://stackoverflow.com/users/1149423/sufiyan-ghori) suggestion of using `random.`
```
if len(my_nestled_list) > 0:
# Obtains the length of the data to insert.
# The length is the number of sublists
# contained in the main nestled list.
data_length = len(my_nestled_list))
# A loop counter used in the
# data insert process.
i = 0
# The number of sublists to slice
# from the main nestled list in
# each loop.
n = 100
# This loop execute a set of statements
# as long as the condition below is true
while i < data_length:
# Increments the loop counter
if len(my_nestled_list)) < 100:
i += len(my_nestled_list))
else:
i += 100
# Uses list comprehension to randomly select 100 lists
# from the nestled list.
random_sample_of_100 = [my_nestled_list)[i] for i in sorted(random.sample(range(len(my_nestled_list))), n))]
print (random_sample_of_100)
``` |
39,947 | I noticed the phrase “What gives?” in the following lines of the article of Washington Post (August 29) article, titled “Is Ron Paul being ignored?”
>
> “And yet talk to almost anyone in politics — Republicans or Democrats — and the idea of Ron Paul as a top-tier candidate for president is greeted with either a laugh or an eye roll (or both.)
>
>
> *What gives?*
>
>
> Paul appears to be suffering from the “once bitten, twice shy” tendency of the media.”
>
>
>
It appears to me “What gives?” is a common and frequently-used phrase, but I don’t think I’ve seen this phrase so often in written English format like newspaper articles, much less in English textbooks we use.
Does it mean “for what (reason)?” or "What is its implication?" What is the spelt-out format of “What gives?” | 2011/08/30 | ['https://english.stackexchange.com/questions/39947', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/3119/'] | *What gives?* [means](http://idioms.thefreedictionary.com/What+Gives%3f):
>
> Inf. What happened?; What went wrong?; What's the problem?
>
>
> Bill: Hi, you guys. What gives? Bob: Nothing, just a little misunderstanding. Tom's a little angry.
>
>
> Bob: Where's my wallet? What gives?
>
>
> Tom: I think one of those roughnecks who just walked by us has borrowed it for a little while.
>
>
>
According to this page on the [linguistics of the phrase](http://ling.ucsc.edu/Jorge/joseph.html), it is not short for anything. There are a few theories about how it arose:
>
> Regarding the issue of why *what gives* is anomalous, the best that I can offer (speaking now as an historical linguist) is to suggest that we turn to the history of the construction, but even there, full enlightenment is not forthcoming (see Joseph 2000 for more detailed discussion). The construction seems clearly to have originated in American English; the first attestation for what gives comes in 1940, in John O'Hara's Pal Joey, according to Wentworth and Flexner (1960: 574, s.v. what gives) and the Oxford English Dictionary (1989 on-line second edition).
>
>
> Even with this late attestation, what gives makes for an interesting comparison with the German existential use of *geben* 'to give', in the impersonal form with an expletive subject, *es gibt*, as in *Es gibt keinen Gott* 'There is no god', itself anomalous from the point of view of the usual syntax and meaning of *geben*...
>
>
> Some scholars however see what gives as having arisen via language contact, as a calque from German, an origin for it which would eliminate a basis for a Proto-West-Germanic prototype, but might allow for a different explanation for the anomalies this expression shows; that is, under such a view, it would show an anomaly because it is a borrowing in the same way that an expression like It goes without saying, calqued from French *Ça va sans dire*, does, with its unusual passive-like voice semantics for an active form of say. In particular, it has been suggested (Chapman (1986: 463, s.v.); see also Wentworth and Flexner ibid.) that what gives is a loan translation from German or Yiddish was *gibt* 'What's going on?'.
>
>
>
The site itself has an even more thorough explanation of the phrase. However, it is a phrase on its own, rather than an abbreviation of another phrase. It means "What's happening?" or "What's up?" It is usually informal, though, so you would not see this in formal writing. You can use it in conversation with others, and they will understand you. However, the tone is slightly negative, so be careful when you choose to use it. | I've been living in Germany for 17 years, and this morning the similarity of the phrase "What gives?" to the German "Was gibt's?" occurred to me, so I checked the net ...
The article ["What Gives with What Gives?"](http://babel.ucsc.edu/Jorge/joseph.html) by Brian Joseph of Ohio State University - also cited above - seems to provide a well founded discussion of the syntax and origin of the phrase in American English. Joseph argues, however, that the German may not be suitable as the origin of the phrase:
>
> … there is no German expression that is simply *was gibt!* Rather, colloquial German has *was gibt es?* 'What is the matter? What's up?', but this is not a suitable source for *what gives* since the putative calquing did not lead to a direct counterpart to the German subject pronoun es (thus, *what gives*, not \**what gives it* or \**what does it give*).
>
>
>
---
For all us non-linguists out there, Wikipedia says:
>
> In linguistics, a calque (/ˈkælk/) or loan translation is a word or
> phrase borrowed from another language by literal, word-for-word
> (Latin: verbum pro verbo) or root-for-root translation.
>
>
>
---
I believe, however, that his dismissal of the German as a source is flawed, because Joseph is principally arguing from a syntax-of-language standpoint and thus comparing the (written) WORDS instead of the SPOKEN language.
Clearly in a comparison of the SYNTAX of "Was - gibt - es ?" with the English "What - gives ?" the word "it" (="es") is missing in the English. However, back then even more so than today, language is primarily a SPOKEN organism! - and a comparison of the SPOKEN phrases provides a very solid argument for its origin from the German:
In the spoken German phrase "Was gibt es?" the second and third word are slurred together (at least, based on modern-day speech), so that only the "s" of "es" is pronounced (sorry, phonetics here are my best guess):
/vasɡiːpts/ and /vasɡɪpts/ (normally written out with an apostrophe: "Was gibt's")
In comparison to the English "What gives?", we can see (or rather hear) that the transition from the German to English comprises the translation of "Was" to "what" and the minimal change in the consonant sounds /pts/ to /vz/.
The final /s/ in the German becomes the third person inflection "(it) give*s*" in the English. In other words the word "it" IS implicitly present in the English, but as an inflection of the verb instead of as an extra word.
---
Wikipedia to the rescue again! Wikipedia explains that:
>
> Calquing is distinct from phono-semantic matching.[3] While calquing
> includes semantic translation, it does not consist of phonetic
> matching (i.e. retaining the approximate sound of the borrowed word
> through matching it with a similar-sounding pre-existent word or
> morpheme in the target language).
>
>
>
and
>
> Phono-semantic matching (PSM) is a linguistic term referring to camouflaged borrowing in which a foreign word is matched with a phonetically and semantically similar pre-existent native word/root.
>
>
>
---
So, to summarize:
I argue that the phrase "what gives?" likely originates from the German "Was gibt's?", and transitioned to English primarily due to the phono-semantic match of the two phrases, and that the transition can be described as a calque in so far as the "it" is implied in the presence of the third person singular inflection /s/.
I would be gratified if a linguist would take my argument further, and reiterate it using the correct phonetics.
--- |
39,947 | I noticed the phrase “What gives?” in the following lines of the article of Washington Post (August 29) article, titled “Is Ron Paul being ignored?”
>
> “And yet talk to almost anyone in politics — Republicans or Democrats — and the idea of Ron Paul as a top-tier candidate for president is greeted with either a laugh or an eye roll (or both.)
>
>
> *What gives?*
>
>
> Paul appears to be suffering from the “once bitten, twice shy” tendency of the media.”
>
>
>
It appears to me “What gives?” is a common and frequently-used phrase, but I don’t think I’ve seen this phrase so often in written English format like newspaper articles, much less in English textbooks we use.
Does it mean “for what (reason)?” or "What is its implication?" What is the spelt-out format of “What gives?” | 2011/08/30 | ['https://english.stackexchange.com/questions/39947', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/3119/'] | *What gives?* [means](http://idioms.thefreedictionary.com/What+Gives%3f):
>
> Inf. What happened?; What went wrong?; What's the problem?
>
>
> Bill: Hi, you guys. What gives? Bob: Nothing, just a little misunderstanding. Tom's a little angry.
>
>
> Bob: Where's my wallet? What gives?
>
>
> Tom: I think one of those roughnecks who just walked by us has borrowed it for a little while.
>
>
>
According to this page on the [linguistics of the phrase](http://ling.ucsc.edu/Jorge/joseph.html), it is not short for anything. There are a few theories about how it arose:
>
> Regarding the issue of why *what gives* is anomalous, the best that I can offer (speaking now as an historical linguist) is to suggest that we turn to the history of the construction, but even there, full enlightenment is not forthcoming (see Joseph 2000 for more detailed discussion). The construction seems clearly to have originated in American English; the first attestation for what gives comes in 1940, in John O'Hara's Pal Joey, according to Wentworth and Flexner (1960: 574, s.v. what gives) and the Oxford English Dictionary (1989 on-line second edition).
>
>
> Even with this late attestation, what gives makes for an interesting comparison with the German existential use of *geben* 'to give', in the impersonal form with an expletive subject, *es gibt*, as in *Es gibt keinen Gott* 'There is no god', itself anomalous from the point of view of the usual syntax and meaning of *geben*...
>
>
> Some scholars however see what gives as having arisen via language contact, as a calque from German, an origin for it which would eliminate a basis for a Proto-West-Germanic prototype, but might allow for a different explanation for the anomalies this expression shows; that is, under such a view, it would show an anomaly because it is a borrowing in the same way that an expression like It goes without saying, calqued from French *Ça va sans dire*, does, with its unusual passive-like voice semantics for an active form of say. In particular, it has been suggested (Chapman (1986: 463, s.v.); see also Wentworth and Flexner ibid.) that what gives is a loan translation from German or Yiddish was *gibt* 'What's going on?'.
>
>
>
The site itself has an even more thorough explanation of the phrase. However, it is a phrase on its own, rather than an abbreviation of another phrase. It means "What's happening?" or "What's up?" It is usually informal, though, so you would not see this in formal writing. You can use it in conversation with others, and they will understand you. However, the tone is slightly negative, so be careful when you choose to use it. | [As already observed](https://english.stackexchange.com/a/178303/16833), *What gives?* may well be derived from German *Was gibt es* via the more common contracted form *Was gibt's?*. As a native speaker of German who has spent some years in English-speaking countries I consider this particularly convincing because contrary to first impressions the uses of *What gives?* and *Was gibt's?* do actually overlap, and the overlap is in a kind of situation in which German speakers would be particularly likely to take such shortcuts as leaving out the *it* in an English sentence because the verb already ends in *s*.
In German, *Was gibt es? / Was gibt's* is a neutral way of asking: *What's going on? / What's up?* But it is *also* something a drunk person is likely to say when feeling slighted by someone and trying to start a fight without really knowing why. (Of course there are also alternatives, such as *Was ist los?*) In this situation the question may well be repeated several times, and invariably in the contracted form *Was gibt's* rather than the long form *Was gibt es?*.
(By the way, in northern Germany people are less likely to use the contraction, but instead they are likely to say *wat* instead of *was*: *Wat gibt es?* This is intriguing, though I doubt that it played an important role.)
So I imagine a drunk, agitated German speaker in the US. Under the circumstances he may be mixing up and simplifying German and English phonetics:
"Was hast du gesagt? Whas did you say? ... Was gib's? Was gib's? Was gib's?"
I think it would be natural for a native English speaker addressed in this way to remember the mysterious question as *What gives?* Or indeed the German speaker may say *What gives?* himself in his attempt to speak English.
(I think it would have been more proper to upvote [the other answer](https://english.stackexchange.com/a/178303/16833) and add a short comment to it than make this a separate answer, but apparently both actions require 'reputation'.) |
39,947 | I noticed the phrase “What gives?” in the following lines of the article of Washington Post (August 29) article, titled “Is Ron Paul being ignored?”
>
> “And yet talk to almost anyone in politics — Republicans or Democrats — and the idea of Ron Paul as a top-tier candidate for president is greeted with either a laugh or an eye roll (or both.)
>
>
> *What gives?*
>
>
> Paul appears to be suffering from the “once bitten, twice shy” tendency of the media.”
>
>
>
It appears to me “What gives?” is a common and frequently-used phrase, but I don’t think I’ve seen this phrase so often in written English format like newspaper articles, much less in English textbooks we use.
Does it mean “for what (reason)?” or "What is its implication?" What is the spelt-out format of “What gives?” | 2011/08/30 | ['https://english.stackexchange.com/questions/39947', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/3119/'] | *What gives?* [means](http://idioms.thefreedictionary.com/What+Gives%3f):
>
> Inf. What happened?; What went wrong?; What's the problem?
>
>
> Bill: Hi, you guys. What gives? Bob: Nothing, just a little misunderstanding. Tom's a little angry.
>
>
> Bob: Where's my wallet? What gives?
>
>
> Tom: I think one of those roughnecks who just walked by us has borrowed it for a little while.
>
>
>
According to this page on the [linguistics of the phrase](http://ling.ucsc.edu/Jorge/joseph.html), it is not short for anything. There are a few theories about how it arose:
>
> Regarding the issue of why *what gives* is anomalous, the best that I can offer (speaking now as an historical linguist) is to suggest that we turn to the history of the construction, but even there, full enlightenment is not forthcoming (see Joseph 2000 for more detailed discussion). The construction seems clearly to have originated in American English; the first attestation for what gives comes in 1940, in John O'Hara's Pal Joey, according to Wentworth and Flexner (1960: 574, s.v. what gives) and the Oxford English Dictionary (1989 on-line second edition).
>
>
> Even with this late attestation, what gives makes for an interesting comparison with the German existential use of *geben* 'to give', in the impersonal form with an expletive subject, *es gibt*, as in *Es gibt keinen Gott* 'There is no god', itself anomalous from the point of view of the usual syntax and meaning of *geben*...
>
>
> Some scholars however see what gives as having arisen via language contact, as a calque from German, an origin for it which would eliminate a basis for a Proto-West-Germanic prototype, but might allow for a different explanation for the anomalies this expression shows; that is, under such a view, it would show an anomaly because it is a borrowing in the same way that an expression like It goes without saying, calqued from French *Ça va sans dire*, does, with its unusual passive-like voice semantics for an active form of say. In particular, it has been suggested (Chapman (1986: 463, s.v.); see also Wentworth and Flexner ibid.) that what gives is a loan translation from German or Yiddish was *gibt* 'What's going on?'.
>
>
>
The site itself has an even more thorough explanation of the phrase. However, it is a phrase on its own, rather than an abbreviation of another phrase. It means "What's happening?" or "What's up?" It is usually informal, though, so you would not see this in formal writing. You can use it in conversation with others, and they will understand you. However, the tone is slightly negative, so be careful when you choose to use it. | Leo Rosten, *The Joys of Yinglish* (1989) claims "What gives" as a characteristic element of what he calls "Yinglish" (hybridized English/Yiddish or Yiddish-inflected English):
>
> **What gives?**
>
>
> This is a stellar addition to the colloquial phrases of conversational Yinglish. From Yiddish: *Vi geyt's*?" "How goes it?" Via German: *Was gibt*?
>
>
> 1. What's going on there?
> 2. What's new?
> 3. What's the matter? What's wrong?
> 4. Tell me the whole story.
>
>
>
As the multiple definitions in Rosten's account indicate, people use "What gives?" can be used in a number of distinct senses. But the most common ones in my experience are "What's going on?" (asked curiously or querulously) and "What's wrong?" (asked sympathetically).
According to Christine Ammer, *The American Heritage Dictionary of Idioms* (1997), "what gives" can also mean "how are you":
>
> The last variant [of "what's cooking"], **what gives**, may derive from the German equivalent, *Was gibt's?* Slang from about 1940, it is also used to mean, "how are you," as in *Hello, Jack—what gives?*
>
>
>
As simchona's answer indicates, Harold Wentworth & Stuart Flexner have a detailed entry for "What gives?" in *Dictionary of American Slang*, first edition (1960):
>
> **What gives?** **1** A common greeting. **2** "What's happening?" "What did I do to make you say or do that?" [Cross reference omitted.] 3 = **What's new?** *Perhaps a lit. translation of the Ger. "was ist los?"* **1939:** "What gives, I asked her...." O'Hara, *Pal Joey*, 43. **1949:** "What gives?' he croaked in an annoyed tone." Chandler, *Little Sister*, 21.
>
>
>
The instance from John O'Hara's *Pal Joey* appeared under the title "[Joey and the Calcutta Club](https://books.google.com/books?id=BzYdAQAAMAAJ&q=%22what+gives,+I+asked+her%22&dq=%22what+gives,+I+asked+her%22&hl=en&sa=X&ved=0ahUKEwjPlPHy2tDOAhVI9WMKHRMAC4gQ6AEIUjAJ)" in *The New Yorker* (March 30, 1940) [combined snippets]:
>
> So Quinn asked me to join them and I did and this mouse with them named Jean Benedict looks like 10000 other dames on the line of some Bway show except when she opens her trap she has an accent that is so British even Sir Nevile Chamberlin would not be able to understand her. I knew she was strictly U.S.A. by appearance but the accent is so good I think what is the angle. **What gives**, I asked her, altho not in so many words. I inquired how she happen to have the accent and she said a lot of people inquire of her the same thing and it is easily explained. She is half American and her father is British.
>
>
>
And from Raymond Chandler's [*The Little Sister*](https://books.google.com/books?id=YaaU052RltUC&pg=PA244&dq=%22what+gives?+he+croaked%22&hl=en&sa=X&ved=0ahUKEwi0woKr3dDOAhVW92MKHaPADcQQ6AEIHjAA#v=onepage&q=%22what%20gives%3F%20he%20croaked%22&f=false) (1949):
>
> He made a grab for the glass [of gin, freshly poured by Marlowe]. I put it on the table in front of him. He grasped it carefully in both hands and poured the gin into his face. Then he laughed heartily and threw the glass at me. I managed to catch it and up-end it on the table again. The man looked me over with a studied but unsuccessful attempt at sternness.
>
>
> "**What gives**?" he croaked in an annoyed tone.
>
>
> "Manager?"
>
>
> He nodded and almost fell off the couch. "Must be I'm drunky," he said. "Kind of a bit of a little bit drunky."
>
>
> "You're not bad," I said. "You're still breathing."
>
>
>
Somewhat surprisingly, the earliest match that a separate Google Books search finds for the expression is from Elizabeth Kata, [*Be Ready with Bells & Drums*](https://books.google.com/books?id=lAAfAAAAMAAJ&q=%22what+gives%22&dq=%22what+gives%22&hl=en&sa=X&ved=0ahUKEwj7i6uA4NDOAhUU22MKHRTQDmo4ChDoAQgiMAI) (1961):
>
> "Is that you. Paul?" Gordon asked.
>
>
> 'But of course. Excuse me for asking, Dad, but **what gives**? **What gives** out there with Orphan Annie, with little Eva. With your—friend—so I'm told. You care to tell me **what gives**, Dad? Honoured older brother, you mind telling me about this friend of yours?'
>
>
> ...
>
>
> 'It's nice to know you care. I'm glad you love me, Dad.' I heard them laughing together. It was fine to hear brothers laughing together. Paul went on speaking.
>
>
> 'You're evading the issue—I don't like any issue being evaded. **What gives** with li'l Eva? Who, what, when, where, and for Pete's sake, why? Why?'
>
>
>
In this dialogue, "Dad" appears to be beatnik talk for "friend" or "pal." Kata was an Australian novelist, not an American; but the usage of "what gives" in this excerpt mirrors U.S. usage. |
39,947 | I noticed the phrase “What gives?” in the following lines of the article of Washington Post (August 29) article, titled “Is Ron Paul being ignored?”
>
> “And yet talk to almost anyone in politics — Republicans or Democrats — and the idea of Ron Paul as a top-tier candidate for president is greeted with either a laugh or an eye roll (or both.)
>
>
> *What gives?*
>
>
> Paul appears to be suffering from the “once bitten, twice shy” tendency of the media.”
>
>
>
It appears to me “What gives?” is a common and frequently-used phrase, but I don’t think I’ve seen this phrase so often in written English format like newspaper articles, much less in English textbooks we use.
Does it mean “for what (reason)?” or "What is its implication?" What is the spelt-out format of “What gives?” | 2011/08/30 | ['https://english.stackexchange.com/questions/39947', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/3119/'] | I've been living in Germany for 17 years, and this morning the similarity of the phrase "What gives?" to the German "Was gibt's?" occurred to me, so I checked the net ...
The article ["What Gives with What Gives?"](http://babel.ucsc.edu/Jorge/joseph.html) by Brian Joseph of Ohio State University - also cited above - seems to provide a well founded discussion of the syntax and origin of the phrase in American English. Joseph argues, however, that the German may not be suitable as the origin of the phrase:
>
> … there is no German expression that is simply *was gibt!* Rather, colloquial German has *was gibt es?* 'What is the matter? What's up?', but this is not a suitable source for *what gives* since the putative calquing did not lead to a direct counterpart to the German subject pronoun es (thus, *what gives*, not \**what gives it* or \**what does it give*).
>
>
>
---
For all us non-linguists out there, Wikipedia says:
>
> In linguistics, a calque (/ˈkælk/) or loan translation is a word or
> phrase borrowed from another language by literal, word-for-word
> (Latin: verbum pro verbo) or root-for-root translation.
>
>
>
---
I believe, however, that his dismissal of the German as a source is flawed, because Joseph is principally arguing from a syntax-of-language standpoint and thus comparing the (written) WORDS instead of the SPOKEN language.
Clearly in a comparison of the SYNTAX of "Was - gibt - es ?" with the English "What - gives ?" the word "it" (="es") is missing in the English. However, back then even more so than today, language is primarily a SPOKEN organism! - and a comparison of the SPOKEN phrases provides a very solid argument for its origin from the German:
In the spoken German phrase "Was gibt es?" the second and third word are slurred together (at least, based on modern-day speech), so that only the "s" of "es" is pronounced (sorry, phonetics here are my best guess):
/vasɡiːpts/ and /vasɡɪpts/ (normally written out with an apostrophe: "Was gibt's")
In comparison to the English "What gives?", we can see (or rather hear) that the transition from the German to English comprises the translation of "Was" to "what" and the minimal change in the consonant sounds /pts/ to /vz/.
The final /s/ in the German becomes the third person inflection "(it) give*s*" in the English. In other words the word "it" IS implicitly present in the English, but as an inflection of the verb instead of as an extra word.
---
Wikipedia to the rescue again! Wikipedia explains that:
>
> Calquing is distinct from phono-semantic matching.[3] While calquing
> includes semantic translation, it does not consist of phonetic
> matching (i.e. retaining the approximate sound of the borrowed word
> through matching it with a similar-sounding pre-existent word or
> morpheme in the target language).
>
>
>
and
>
> Phono-semantic matching (PSM) is a linguistic term referring to camouflaged borrowing in which a foreign word is matched with a phonetically and semantically similar pre-existent native word/root.
>
>
>
---
So, to summarize:
I argue that the phrase "what gives?" likely originates from the German "Was gibt's?", and transitioned to English primarily due to the phono-semantic match of the two phrases, and that the transition can be described as a calque in so far as the "it" is implied in the presence of the third person singular inflection /s/.
I would be gratified if a linguist would take my argument further, and reiterate it using the correct phonetics.
--- | Leo Rosten, *The Joys of Yinglish* (1989) claims "What gives" as a characteristic element of what he calls "Yinglish" (hybridized English/Yiddish or Yiddish-inflected English):
>
> **What gives?**
>
>
> This is a stellar addition to the colloquial phrases of conversational Yinglish. From Yiddish: *Vi geyt's*?" "How goes it?" Via German: *Was gibt*?
>
>
> 1. What's going on there?
> 2. What's new?
> 3. What's the matter? What's wrong?
> 4. Tell me the whole story.
>
>
>
As the multiple definitions in Rosten's account indicate, people use "What gives?" can be used in a number of distinct senses. But the most common ones in my experience are "What's going on?" (asked curiously or querulously) and "What's wrong?" (asked sympathetically).
According to Christine Ammer, *The American Heritage Dictionary of Idioms* (1997), "what gives" can also mean "how are you":
>
> The last variant [of "what's cooking"], **what gives**, may derive from the German equivalent, *Was gibt's?* Slang from about 1940, it is also used to mean, "how are you," as in *Hello, Jack—what gives?*
>
>
>
As simchona's answer indicates, Harold Wentworth & Stuart Flexner have a detailed entry for "What gives?" in *Dictionary of American Slang*, first edition (1960):
>
> **What gives?** **1** A common greeting. **2** "What's happening?" "What did I do to make you say or do that?" [Cross reference omitted.] 3 = **What's new?** *Perhaps a lit. translation of the Ger. "was ist los?"* **1939:** "What gives, I asked her...." O'Hara, *Pal Joey*, 43. **1949:** "What gives?' he croaked in an annoyed tone." Chandler, *Little Sister*, 21.
>
>
>
The instance from John O'Hara's *Pal Joey* appeared under the title "[Joey and the Calcutta Club](https://books.google.com/books?id=BzYdAQAAMAAJ&q=%22what+gives,+I+asked+her%22&dq=%22what+gives,+I+asked+her%22&hl=en&sa=X&ved=0ahUKEwjPlPHy2tDOAhVI9WMKHRMAC4gQ6AEIUjAJ)" in *The New Yorker* (March 30, 1940) [combined snippets]:
>
> So Quinn asked me to join them and I did and this mouse with them named Jean Benedict looks like 10000 other dames on the line of some Bway show except when she opens her trap she has an accent that is so British even Sir Nevile Chamberlin would not be able to understand her. I knew she was strictly U.S.A. by appearance but the accent is so good I think what is the angle. **What gives**, I asked her, altho not in so many words. I inquired how she happen to have the accent and she said a lot of people inquire of her the same thing and it is easily explained. She is half American and her father is British.
>
>
>
And from Raymond Chandler's [*The Little Sister*](https://books.google.com/books?id=YaaU052RltUC&pg=PA244&dq=%22what+gives?+he+croaked%22&hl=en&sa=X&ved=0ahUKEwi0woKr3dDOAhVW92MKHaPADcQQ6AEIHjAA#v=onepage&q=%22what%20gives%3F%20he%20croaked%22&f=false) (1949):
>
> He made a grab for the glass [of gin, freshly poured by Marlowe]. I put it on the table in front of him. He grasped it carefully in both hands and poured the gin into his face. Then he laughed heartily and threw the glass at me. I managed to catch it and up-end it on the table again. The man looked me over with a studied but unsuccessful attempt at sternness.
>
>
> "**What gives**?" he croaked in an annoyed tone.
>
>
> "Manager?"
>
>
> He nodded and almost fell off the couch. "Must be I'm drunky," he said. "Kind of a bit of a little bit drunky."
>
>
> "You're not bad," I said. "You're still breathing."
>
>
>
Somewhat surprisingly, the earliest match that a separate Google Books search finds for the expression is from Elizabeth Kata, [*Be Ready with Bells & Drums*](https://books.google.com/books?id=lAAfAAAAMAAJ&q=%22what+gives%22&dq=%22what+gives%22&hl=en&sa=X&ved=0ahUKEwj7i6uA4NDOAhUU22MKHRTQDmo4ChDoAQgiMAI) (1961):
>
> "Is that you. Paul?" Gordon asked.
>
>
> 'But of course. Excuse me for asking, Dad, but **what gives**? **What gives** out there with Orphan Annie, with little Eva. With your—friend—so I'm told. You care to tell me **what gives**, Dad? Honoured older brother, you mind telling me about this friend of yours?'
>
>
> ...
>
>
> 'It's nice to know you care. I'm glad you love me, Dad.' I heard them laughing together. It was fine to hear brothers laughing together. Paul went on speaking.
>
>
> 'You're evading the issue—I don't like any issue being evaded. **What gives** with li'l Eva? Who, what, when, where, and for Pete's sake, why? Why?'
>
>
>
In this dialogue, "Dad" appears to be beatnik talk for "friend" or "pal." Kata was an Australian novelist, not an American; but the usage of "what gives" in this excerpt mirrors U.S. usage. |
39,947 | I noticed the phrase “What gives?” in the following lines of the article of Washington Post (August 29) article, titled “Is Ron Paul being ignored?”
>
> “And yet talk to almost anyone in politics — Republicans or Democrats — and the idea of Ron Paul as a top-tier candidate for president is greeted with either a laugh or an eye roll (or both.)
>
>
> *What gives?*
>
>
> Paul appears to be suffering from the “once bitten, twice shy” tendency of the media.”
>
>
>
It appears to me “What gives?” is a common and frequently-used phrase, but I don’t think I’ve seen this phrase so often in written English format like newspaper articles, much less in English textbooks we use.
Does it mean “for what (reason)?” or "What is its implication?" What is the spelt-out format of “What gives?” | 2011/08/30 | ['https://english.stackexchange.com/questions/39947', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/3119/'] | [As already observed](https://english.stackexchange.com/a/178303/16833), *What gives?* may well be derived from German *Was gibt es* via the more common contracted form *Was gibt's?*. As a native speaker of German who has spent some years in English-speaking countries I consider this particularly convincing because contrary to first impressions the uses of *What gives?* and *Was gibt's?* do actually overlap, and the overlap is in a kind of situation in which German speakers would be particularly likely to take such shortcuts as leaving out the *it* in an English sentence because the verb already ends in *s*.
In German, *Was gibt es? / Was gibt's* is a neutral way of asking: *What's going on? / What's up?* But it is *also* something a drunk person is likely to say when feeling slighted by someone and trying to start a fight without really knowing why. (Of course there are also alternatives, such as *Was ist los?*) In this situation the question may well be repeated several times, and invariably in the contracted form *Was gibt's* rather than the long form *Was gibt es?*.
(By the way, in northern Germany people are less likely to use the contraction, but instead they are likely to say *wat* instead of *was*: *Wat gibt es?* This is intriguing, though I doubt that it played an important role.)
So I imagine a drunk, agitated German speaker in the US. Under the circumstances he may be mixing up and simplifying German and English phonetics:
"Was hast du gesagt? Whas did you say? ... Was gib's? Was gib's? Was gib's?"
I think it would be natural for a native English speaker addressed in this way to remember the mysterious question as *What gives?* Or indeed the German speaker may say *What gives?* himself in his attempt to speak English.
(I think it would have been more proper to upvote [the other answer](https://english.stackexchange.com/a/178303/16833) and add a short comment to it than make this a separate answer, but apparently both actions require 'reputation'.) | Leo Rosten, *The Joys of Yinglish* (1989) claims "What gives" as a characteristic element of what he calls "Yinglish" (hybridized English/Yiddish or Yiddish-inflected English):
>
> **What gives?**
>
>
> This is a stellar addition to the colloquial phrases of conversational Yinglish. From Yiddish: *Vi geyt's*?" "How goes it?" Via German: *Was gibt*?
>
>
> 1. What's going on there?
> 2. What's new?
> 3. What's the matter? What's wrong?
> 4. Tell me the whole story.
>
>
>
As the multiple definitions in Rosten's account indicate, people use "What gives?" can be used in a number of distinct senses. But the most common ones in my experience are "What's going on?" (asked curiously or querulously) and "What's wrong?" (asked sympathetically).
According to Christine Ammer, *The American Heritage Dictionary of Idioms* (1997), "what gives" can also mean "how are you":
>
> The last variant [of "what's cooking"], **what gives**, may derive from the German equivalent, *Was gibt's?* Slang from about 1940, it is also used to mean, "how are you," as in *Hello, Jack—what gives?*
>
>
>
As simchona's answer indicates, Harold Wentworth & Stuart Flexner have a detailed entry for "What gives?" in *Dictionary of American Slang*, first edition (1960):
>
> **What gives?** **1** A common greeting. **2** "What's happening?" "What did I do to make you say or do that?" [Cross reference omitted.] 3 = **What's new?** *Perhaps a lit. translation of the Ger. "was ist los?"* **1939:** "What gives, I asked her...." O'Hara, *Pal Joey*, 43. **1949:** "What gives?' he croaked in an annoyed tone." Chandler, *Little Sister*, 21.
>
>
>
The instance from John O'Hara's *Pal Joey* appeared under the title "[Joey and the Calcutta Club](https://books.google.com/books?id=BzYdAQAAMAAJ&q=%22what+gives,+I+asked+her%22&dq=%22what+gives,+I+asked+her%22&hl=en&sa=X&ved=0ahUKEwjPlPHy2tDOAhVI9WMKHRMAC4gQ6AEIUjAJ)" in *The New Yorker* (March 30, 1940) [combined snippets]:
>
> So Quinn asked me to join them and I did and this mouse with them named Jean Benedict looks like 10000 other dames on the line of some Bway show except when she opens her trap she has an accent that is so British even Sir Nevile Chamberlin would not be able to understand her. I knew she was strictly U.S.A. by appearance but the accent is so good I think what is the angle. **What gives**, I asked her, altho not in so many words. I inquired how she happen to have the accent and she said a lot of people inquire of her the same thing and it is easily explained. She is half American and her father is British.
>
>
>
And from Raymond Chandler's [*The Little Sister*](https://books.google.com/books?id=YaaU052RltUC&pg=PA244&dq=%22what+gives?+he+croaked%22&hl=en&sa=X&ved=0ahUKEwi0woKr3dDOAhVW92MKHaPADcQQ6AEIHjAA#v=onepage&q=%22what%20gives%3F%20he%20croaked%22&f=false) (1949):
>
> He made a grab for the glass [of gin, freshly poured by Marlowe]. I put it on the table in front of him. He grasped it carefully in both hands and poured the gin into his face. Then he laughed heartily and threw the glass at me. I managed to catch it and up-end it on the table again. The man looked me over with a studied but unsuccessful attempt at sternness.
>
>
> "**What gives**?" he croaked in an annoyed tone.
>
>
> "Manager?"
>
>
> He nodded and almost fell off the couch. "Must be I'm drunky," he said. "Kind of a bit of a little bit drunky."
>
>
> "You're not bad," I said. "You're still breathing."
>
>
>
Somewhat surprisingly, the earliest match that a separate Google Books search finds for the expression is from Elizabeth Kata, [*Be Ready with Bells & Drums*](https://books.google.com/books?id=lAAfAAAAMAAJ&q=%22what+gives%22&dq=%22what+gives%22&hl=en&sa=X&ved=0ahUKEwj7i6uA4NDOAhUU22MKHRTQDmo4ChDoAQgiMAI) (1961):
>
> "Is that you. Paul?" Gordon asked.
>
>
> 'But of course. Excuse me for asking, Dad, but **what gives**? **What gives** out there with Orphan Annie, with little Eva. With your—friend—so I'm told. You care to tell me **what gives**, Dad? Honoured older brother, you mind telling me about this friend of yours?'
>
>
> ...
>
>
> 'It's nice to know you care. I'm glad you love me, Dad.' I heard them laughing together. It was fine to hear brothers laughing together. Paul went on speaking.
>
>
> 'You're evading the issue—I don't like any issue being evaded. **What gives** with li'l Eva? Who, what, when, where, and for Pete's sake, why? Why?'
>
>
>
In this dialogue, "Dad" appears to be beatnik talk for "friend" or "pal." Kata was an Australian novelist, not an American; but the usage of "what gives" in this excerpt mirrors U.S. usage. |
35,937,244 | I have an application where I want to filter a long list of products based on value from "select" containing product types. The filter works, but only after I select something. It initially sets the "Show All" option, but filters out everything. If I select something else, it works, and if I re-select "Show All" it works. But why doesn't the filter work initially?
The model (looks something like this):
```
$scope.products = {[
{name: 'productA',Type: 1},
{name: 'productB',Type: 1},
{name: 'productC',Type: 2},
{name: 'productD',Type: 2},
]};
$scope.productTypes = {[
{Name: 'typeAlpha',Type: 1},
{Name: 'typeBravo',Type: 2},
]};
```
The HTML:
```
<select id="productFilter" data-ng-model="productFilter">
<option value="" selected="selected">Show all</option>
<option data-ng-repeat="type in productTypes" value="{{type.Type}}">{{type.Name}}</option>
</select>
<p data-ng-repeat="product in products | filter:{Type:productFilter} ">{{product.Name}}</p>
``` | 2016/03/11 | ['https://Stackoverflow.com/questions/35937244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4233688/'] | I recommend using ng-options instead of ng-repeat over the options:
```
<select id="productFilter" ng-model="productFilter"
data-ng-options="type.type as type.name for type in productTypes">
<option value selected="selected">Show all</option>
</select>
<p data-ng-repeat="product in products | filter:(!!productFilter || undefined) && {type: productFilter}">
{{product.name}}
</p>
```
For "show all", the filter must return undefined ([ng-repeat filter "show all" items if no filter selected](https://stackoverflow.com/questions/28164580/ng-repeat-filter-show-all-items-if-no-filter-selected))
Also removed the {..} around the array and better use lower case for properties:
```
$scope.products = [
{name: 'productA', type: 1},
{name: 'productB', type: 1},
{name: 'productC', type: 2},
{name: 'productD', type: 2}
];
$scope.productTypes = [
{name: 'typeAlpha', type: 1},
{name: 'typeBravo', type: 2}
];
```
Here is a jsbin (based on Hiskinds)
<http://jsbin.com/yepaqikodo/1/edit?html,js,output> | This is a working example based on code above: <http://jsbin.com/buzafisuko/edit?html,js,output>
The Slava.N's comment is correct and you should not wrap productTypes and product in {}
Also, JavaScript is a case-sensitive language, `product.Name` is always undefined, you should use `product.name` in your HTML instead. |
35,937,244 | I have an application where I want to filter a long list of products based on value from "select" containing product types. The filter works, but only after I select something. It initially sets the "Show All" option, but filters out everything. If I select something else, it works, and if I re-select "Show All" it works. But why doesn't the filter work initially?
The model (looks something like this):
```
$scope.products = {[
{name: 'productA',Type: 1},
{name: 'productB',Type: 1},
{name: 'productC',Type: 2},
{name: 'productD',Type: 2},
]};
$scope.productTypes = {[
{Name: 'typeAlpha',Type: 1},
{Name: 'typeBravo',Type: 2},
]};
```
The HTML:
```
<select id="productFilter" data-ng-model="productFilter">
<option value="" selected="selected">Show all</option>
<option data-ng-repeat="type in productTypes" value="{{type.Type}}">{{type.Name}}</option>
</select>
<p data-ng-repeat="product in products | filter:{Type:productFilter} ">{{product.Name}}</p>
``` | 2016/03/11 | ['https://Stackoverflow.com/questions/35937244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4233688/'] | I recommend using ng-options instead of ng-repeat over the options:
```
<select id="productFilter" ng-model="productFilter"
data-ng-options="type.type as type.name for type in productTypes">
<option value selected="selected">Show all</option>
</select>
<p data-ng-repeat="product in products | filter:(!!productFilter || undefined) && {type: productFilter}">
{{product.name}}
</p>
```
For "show all", the filter must return undefined ([ng-repeat filter "show all" items if no filter selected](https://stackoverflow.com/questions/28164580/ng-repeat-filter-show-all-items-if-no-filter-selected))
Also removed the {..} around the array and better use lower case for properties:
```
$scope.products = [
{name: 'productA', type: 1},
{name: 'productB', type: 1},
{name: 'productC', type: 2},
{name: 'productD', type: 2}
];
$scope.productTypes = [
{name: 'typeAlpha', type: 1},
{name: 'typeBravo', type: 2}
];
```
Here is a jsbin (based on Hiskinds)
<http://jsbin.com/yepaqikodo/1/edit?html,js,output> | Use product.Type instead ofType inside 2nd ng-repeat filter |
35,937,244 | I have an application where I want to filter a long list of products based on value from "select" containing product types. The filter works, but only after I select something. It initially sets the "Show All" option, but filters out everything. If I select something else, it works, and if I re-select "Show All" it works. But why doesn't the filter work initially?
The model (looks something like this):
```
$scope.products = {[
{name: 'productA',Type: 1},
{name: 'productB',Type: 1},
{name: 'productC',Type: 2},
{name: 'productD',Type: 2},
]};
$scope.productTypes = {[
{Name: 'typeAlpha',Type: 1},
{Name: 'typeBravo',Type: 2},
]};
```
The HTML:
```
<select id="productFilter" data-ng-model="productFilter">
<option value="" selected="selected">Show all</option>
<option data-ng-repeat="type in productTypes" value="{{type.Type}}">{{type.Name}}</option>
</select>
<p data-ng-repeat="product in products | filter:{Type:productFilter} ">{{product.Name}}</p>
``` | 2016/03/11 | ['https://Stackoverflow.com/questions/35937244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4233688/'] | I recommend using ng-options instead of ng-repeat over the options:
```
<select id="productFilter" ng-model="productFilter"
data-ng-options="type.type as type.name for type in productTypes">
<option value selected="selected">Show all</option>
</select>
<p data-ng-repeat="product in products | filter:(!!productFilter || undefined) && {type: productFilter}">
{{product.name}}
</p>
```
For "show all", the filter must return undefined ([ng-repeat filter "show all" items if no filter selected](https://stackoverflow.com/questions/28164580/ng-repeat-filter-show-all-items-if-no-filter-selected))
Also removed the {..} around the array and better use lower case for properties:
```
$scope.products = [
{name: 'productA', type: 1},
{name: 'productB', type: 1},
{name: 'productC', type: 2},
{name: 'productD', type: 2}
];
$scope.productTypes = [
{name: 'typeAlpha', type: 1},
{name: 'typeBravo', type: 2}
];
```
Here is a jsbin (based on Hiskinds)
<http://jsbin.com/yepaqikodo/1/edit?html,js,output> | you set $scope.productFilter = ''.
so its return by default value blank at filter. |