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
|
---|---|---|---|---|---|
3,926,936 |
I have a directory of 9 images:
```
image_0001, image_0002, image_0003
image_0010, image_0011
image_0011-1, image_0011-2, image_0011-3
image_9999
```
I would like to be able to list them in an efficient way, like this (4 entries for 9 images):
```
(image_000[1-3], image_00[10-11], image_0011-[1-3], image_9999)
```
Is there a way in python, to return a directory of images, in a short/clear way (without listing every file)?
So, possibly something like this:
list all images, sort numerically, create a list (counting each image in sequence from start).
When an image is missing (create a new list), continue until original file list is finished.
Now I should just have some lists that contain non broken sequences.
I'm trying to make it easy to read/describe a list of numbers. If I had a sequence of 1000 consecutive files It could be clearly listed as file[0001-1000] rather than file['0001','0002','0003' etc...]
**Edit1**(based on suggestion): Given a flattened list, how would you derive the glob patterns?
**Edit2** I'm trying to break the problem down into smaller pieces. Here is an example of part of the solution:
data1 works, data2 returns 0010 as 64, data3 (the realworld data) doesn't work:
```
# Find runs of consecutive numbers using groupby. The key to the solution
# is differencing with a range so that consecutive numbers all appear in
# same group.
from operator import itemgetter
from itertools import *
data1=[01,02,03,10,11,100,9999]
data2=[0001,0002,0003,0010,0011,0100,9999]
data3=['image_0001','image_0002','image_0003','image_0010','image_0011','image_0011-2','image_0011-3','image_0100','image_9999']
list1 = []
for k, g in groupby(enumerate(data1), lambda (i,x):i-x):
list1.append(map(itemgetter(1), g))
print 'data1'
print list1
list2 = []
for k, g in groupby(enumerate(data2), lambda (i,x):i-x):
list2.append(map(itemgetter(1), g))
print '\ndata2'
print list2
```
returns:
```
data1
[[1, 2, 3], [10, 11], [100], [9999]]
data2
[[1, 2, 3], [8, 9], [64], [9999]]
```
|
2010/10/13
|
['https://Stackoverflow.com/questions/3926936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178686/']
|
Here is a working implementation of what you want to achieve, using the code you added as a starting point:
```
#!/usr/bin/env python
import itertools
import re
# This algorithm only works if DATA is sorted.
DATA = ["image_0001", "image_0002", "image_0003",
"image_0010", "image_0011",
"image_0011-1", "image_0011-2", "image_0011-3",
"image_0100", "image_9999"]
def extract_number(name):
# Match the last number in the name and return it as a string,
# including leading zeroes (that's important for formatting below).
return re.findall(r"\d+$", name)[0]
def collapse_group(group):
if len(group) == 1:
return group[0][1] # Unique names collapse to themselves.
first = extract_number(group[0][1]) # Fetch range
last = extract_number(group[-1][1]) # of this group.
# Cheap way to compute the string length of the upper bound,
# discarding leading zeroes.
length = len(str(int(last)))
# Now we have the length of the variable part of the names,
# the rest is only formatting.
return "%s[%s-%s]" % (group[0][1][:-length],
first[-length:], last[-length:])
groups = [collapse_group(tuple(group)) \
for key, group in itertools.groupby(enumerate(DATA),
lambda(index, name): index - int(extract_number(name)))]
print groups
```
This prints `['image_000[1-3]', 'image_00[10-11]', 'image_0011-[1-3]', 'image_0100', 'image_9999']`, which is what you want.
**HISTORY:** I initially answered the question backwards, as @Mark Ransom pointed out below. For the sake of history, my original answer was:
You're looking for [glob](http://docs.python.org/library/glob.html). Try:
```
import glob
images = glob.glob("image_[0-9]*")
```
Or, using your example:
```
images = [glob.glob(pattern) for pattern in ("image_000[1-3]*",
"image_00[10-11]*", "image_0011-[1-3]*", "image_9999*")]
images = [image for seq in images for image in seq] # flatten the list
```
|
Okay, so I found your question to be a fascinating puzzle. I've left how to
"compress" the numeric ranges up to you (marked as a TODO), as there are
different ways to accomplish that depending on how you like it formatted and if
you want the minimum number of elements or the minimum string description
length.
This solution uses a simple regular expression (digit strings) to classify each string into two groups: static and variable. After the data is classified, I use groupby to collect the
static data into longest matching groups to achieve the summary effect. I mix integer index sentinals into the result (in matchGrouper) so I can re-select the varying parts from all elements (in unpack).
```
import re
import glob
from itertools import groupby
from operator import itemgetter
def classifyGroups(iterable, reObj=re.compile('\d+')):
"""Yields successive match lists, where each item in the list is either
static text content, or a list of matching values.
* `iterable` is a list of strings, such as glob('images/*')
* `reObj` is a compiled regular expression that describes the
variable section of the iterable you want to match and classify
"""
def classify(text, pos=0):
"""Use a regular expression object to split the text into match and non-match sections"""
r = []
for m in reObj.finditer(text, pos):
m0 = m.start()
r.append((False, text[pos:m0]))
pos = m.end()
r.append((True, text[m0:pos]))
r.append((False, text[pos:]))
return r
def matchGrouper(each):
"""Returns index of matches or origional text for non-matches"""
return [(i if t else v) for i,(t,v) in enumerate(each)]
def unpack(k,matches):
"""If the key is an integer, unpack the value array from matches"""
if isinstance(k, int):
k = [m[k][1] for m in matches]
return k
# classify each item into matches
matchLists = (classify(t) for t in iterable)
# group the matches by their static content
for key, matches in groupby(matchLists, matchGrouper):
matches = list(matches)
# Yield a list of content matches. Each entry is either text
# from static content, or a list of matches
yield [unpack(k, matches) for k in key]
```
Finally, we add enough logic to perform pretty printing of the output, and run an example.
```
def makeResultPretty(res):
"""Formats data somewhat like the question"""
r = []
for e in res:
if isinstance(e, list):
# TODO: collapse and simplify ranges as desired here
if len(set(e))<=1:
# it's a list of the same element
e = e[0]
else:
# prettify the list
e = '['+' '.join(e)+']'
r.append(e)
return ''.join(r)
fnList = sorted(glob.glob('images/*'))
re_digits = re.compile(r'\d+')
for res in classifyGroups(fnList, re_digits):
print makeResultPretty(res)
```
My directory of images was created from your example. You can replace fnList with the following list for testing:
```
fnList = [
'images/image_0001.jpg',
'images/image_0002.jpg',
'images/image_0003.jpg',
'images/image_0010.jpg',
'images/image_0011-1.jpg',
'images/image_0011-2.jpg',
'images/image_0011-3.jpg',
'images/image_0011.jpg',
'images/image_9999.jpg']
```
And when I run against this directory, my output looks like:
```
StackOverflow/3926936% python classify.py
images/image_[0001 0002 0003 0010].jpg
images/image_0011-[1 2 3].jpg
images/image_[0011 9999].jpg
```
|
373,831 |
I need to center the title of the parts in the toc. I'm trying these two approaches:
```
\documentclass{article}
\usepackage{hyperref}
\usepackage{tocloft}
\cftpagenumbersoff{part}
\begin{document}
\tableofcontents
\addcontentsline{toc}{part}{\centerline{Part A}}
\addcontentsline{toc}{section}{Section A}
\addcontentsline{toc}{part}{\hfill{Part B}\hfill}
\addcontentsline{toc}{section}{Section B}
\end{document}
```
When the PDF is generated, the bookmarks have some of problems:
1. Part A appears in the bookmarks as "toPart A".
2. Part B appears hierarchically under Section A.
3. Part B appears correctly in the bookmarks, but it's not correctly centered in the page.
What can I do to solve this problem? Thank you!
|
2017/06/07
|
['https://tex.stackexchange.com/questions/373831', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/134459/']
|
You need to expand the number when you define \parttitle:
```
\documentclass[11pt, oneside, a4paper]{memoir}
\usepackage{lipsum}
\newcounter{DocPart}
\setcounter{DocPart}{0}
\newcommand{\pageNumber}{}
\newcommand{\parttitle}{}
\renewcommand{\part}[1]{%
\ifnum\theDocPart = 0
\renewcommand{\parttitle}{A. #1}
\renewcommand{\pageNumber}{A.\thepage}
\cftaddtitleline{toc}{part}{A. #1}{}
\else
\edef\parttitle{A\theDocPart. #1}%<----
\edef\pageNumber{A\theDocPart.\noexpand\thepage}%<-----
\cftaddtitleline{toc}{part}{A\theDocPart. #1}{}
\fi
\stepcounter{DocPart}
}
\makepagestyle{test}
\makeoddhead{test}{\pageNumber}{}{\parttitle}
\pagestyle{test}
\begin{document}
\part{PART NUMBER ZERO} % I want this to say A. PART NUMBER ZERO in the header, which it does
\chapter{FAKE CHAPTER ONE}
\theDocPart \thispagestyle{test}
\lipsum[88]
\chapter{FAKE CHAPTER TWO}
\thispagestyle{test}
\lipsum[120]
\newpage
\tableofcontents*
\part{PART NUMBER ONE} % I want this to say A1. PART NUMBER ONE in the header
\chapter{FAKE CHAPTER TWO}
\thispagestyle{test}
\lipsum
\part{PART NUMBER TWO} % I want this to say A2. PART NUMBER TWO in the header
\chapter{FAKE CHAPTER THREE}
\thispagestyle{test}
\lipsum
\end{document}
```
|
The setting of the header is as far as I know asynchronous. However, expanding the `\theDocPart` in `\pageNumber` and `\parttitle` does work:
```
\documentclass[11pt, oneside, a4paper]{memoir}
\usepackage{lipsum}
\newcounter{DocPart}
\setcounter{DocPart}{0}
\newcommand{\pageNumber}{}
\newcommand{\parttitle}{}
\renewcommand{\part}[1]{
\ifnum\theDocPart = 0
\renewcommand{\parttitle}{A. #1}
\renewcommand{\pageNumber}{A.\thepage}
\cftaddtitleline{toc}{part}{A. #1}{}
\else
\xdef\parttitle{A\theDocPart. #1}
\xdef\pageNumber{A\theDocPart.\noexpand\thepage}
\cftaddtitleline{toc}{part}{A\theDocPart. #1}{}
\fi
\stepcounter{DocPart}
}
\makepagestyle{test}
\makeoddhead{test}{\pageNumber}{}{\parttitle}
\pagestyle{test}
\begin{document}
\part{PART NUMBER ZERO} % I want this to say A. PART NUMBER ZERO in the header, which it does
\chapter{FAKE CHAPTER ONE}
\thispagestyle{test}
\lipsum[88]
\chapter{FAKE CHAPTER TWO}
\thispagestyle{test}
\lipsum[120]
\newpage
\tableofcontents*
\part{PART NUMBER ONE} % I want this to say A1. PART NUMBER ONE in the header
\chapter{FAKE CHAPTER TWO}
\thispagestyle{test}
\lipsum
\part{PART NUMBER TWO} % I want this to say A2. PART NUMBER TWO in the header
\chapter{FAKE CHAPTER THREE}
\thispagestyle{test}
\lipsum
\end{document}
```
|
66,189,992 |
If this doesnt make sense, let me show you an example.
Right now, I am trying to evaluate a postfix expression. I have done everything needed, but there is one problem.
When I have single digits in the expression, everything works fine. This is because during my code, I had to get rid of all spaces.
For example, the postfix expression `2 1 + 3 *` evaluates to `9`. But when I have the postfix expression `4 13 5 / +` , the evaluated expression is incorrect.
This is because when I got rid of all the spaces in that expression, the number 13 becomes seperated into two numbers. (1 and 3) I do not want that to happen, but I cannot figure out how to fix this error!
`Input = 4 13 5 / +`
`Output = 2`
The output should be `6`.
I am using the `.replace(" ", "")` method.
How do I fix this?
Here is an example of my code.
```
from __future__ import division
import random
formula = input()
formula = formula.replace(" ", "")
OPERATORS = set(['+', '-', '*', '/', '(', ')'])
PRIORITY = {'+':1, '-':1, '*':2, '/':2}
stack = []
prev_op = None
for ch in formula:
if not ch in OPERATORS:
stack.append(ch)
else:
b = stack.pop()
a = stack.pop()
if ch == "+":
output = int(b)+int(a)
if ch == "-":
output = int(b)-int(a)
if ch == "*":
output = int(b)*int(a)
if ch == "/":
output = int(b)/int(a)
stack.append(output)
print(output)
```
|
2021/02/13
|
['https://Stackoverflow.com/questions/66189992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14923907/']
|
There are a few issues with your code.
1. Instead of the replace, you can simply use `formula.split()`
2. You are popping the items in the wrong order, you need to pop a before b to get the right answers. You were lucky to have the first case give you the same, but second fails because instead of 13/5 it does 5/13.
I have marked the changes below. Do try it out.
```
from __future__ import division
import random
formula = input().split() #<------
OPERATORS = set(['+', '-', '*', '/', '(', ')'])
PRIORITY = {'+':1, '-':1, '*':2, '/':2}
stack = []
prev_op = None
for ch in formula:
if not ch in OPERATORS:
stack.append(ch)
else:
a = stack.pop() #<---------
b = stack.pop() #<---------
if ch == "+":
output = int(b)+int(a)
if ch == "-":
output = int(b)-int(a)
if ch == "*":
output = int(b)*int(a)
if ch == "/":
output = int(b)/int(a)
stack.append(output)
print(output)
```
```
4 13 5 / +
6
```
|
Instead of removing spaces, you should keep them: this will make it easy to extract the *words* from the input, using `split`:
```
for ch in formula.split():
```
|
69,445,978 |
Lets say I have two franchise of dance schools.
I have two tables. First table tells about students roll no. every
Table 1 =
```
Roll No. Center ID Name Date
1 A Anna 10/10/2020
1 A Anna 11/10/2020
1 B Anna 12/10/2020
2 A Bella 12/10/2020
2 B Bella 13/10/2020
3 A Catty 10/10/2020
```
Table 2 =
```
Roll no. Center ID Report
1 A Did well
1 A Sick
1 B Needs more twist
2 A Practice required
2 B Did well
3 A Needs more practice
```
Result table expected: I want in the result it should pick Center id as A only but Report should be from both the centers
```
Roll no. Center ID Report Name
1 A Did well ,Sick ,Needs more twist Anna
2 A Practice required,Did well Bella
3 A Needs more practice Catty
```
Could someone pls help.
|
2021/10/05
|
['https://Stackoverflow.com/questions/69445978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11496279/']
|
By `dplyr`,
```
t1 %>%
mutate(Report = t2$Report) %>%
group_by(Roll_No.) %>%
summarise(Center_ID = "A",
Report = paste0(Report, collapse = ', '),
Name = unique(Name)
)
Roll_No. Center_ID Report Name
<int> <chr> <chr> <chr>
1 1 A Did well, Sick, Needs more twist Anna
2 2 A Practice required, Did well Bella
3 3 A Needs more practice Catty
```
|
```r
library(tidyverse)
a <- tribble(
~Roll, ~Center, ~Name, ~Date,
1, "A", "Anna", "10/10/2020",
1, "B", "Anna", "12/10/2020",
3, "A", "Catty", "10/10/2020"
)
b <- tribble(
~Roll, ~Center, ~Report,
1, "A", "Dis well",
1, "A", "Sick",
1, "B", "Needs more twist",
3, "A", "Needs more practice"
)
a %>%
left_join(b) %>%
group_by(Roll, Center) %>%
summarise(
Report = c(Report, Name %>% unique()) %>% paste0(collapse = ",")
)
#> Joining, by = c("Roll", "Center")
#> `summarise()` has grouped output by 'Roll'. You can override using the `.groups` argument.
#> # A tibble: 3 x 3
#> # Groups: Roll [2]
#> Roll Center Report
#> <dbl> <chr> <chr>
#> 1 1 A Dis well,Sick,Anna
#> 2 1 B Needs more twist,Anna
#> 3 3 A Needs more practice,Catty
```
Created on 2021-10-05 by the [reprex package](https://reprex.tidyverse.org) (v2.0.0)
|
69,445,978 |
Lets say I have two franchise of dance schools.
I have two tables. First table tells about students roll no. every
Table 1 =
```
Roll No. Center ID Name Date
1 A Anna 10/10/2020
1 A Anna 11/10/2020
1 B Anna 12/10/2020
2 A Bella 12/10/2020
2 B Bella 13/10/2020
3 A Catty 10/10/2020
```
Table 2 =
```
Roll no. Center ID Report
1 A Did well
1 A Sick
1 B Needs more twist
2 A Practice required
2 B Did well
3 A Needs more practice
```
Result table expected: I want in the result it should pick Center id as A only but Report should be from both the centers
```
Roll no. Center ID Report Name
1 A Did well ,Sick ,Needs more twist Anna
2 A Practice required,Did well Bella
3 A Needs more practice Catty
```
Could someone pls help.
|
2021/10/05
|
['https://Stackoverflow.com/questions/69445978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11496279/']
|
By `dplyr`,
```
t1 %>%
mutate(Report = t2$Report) %>%
group_by(Roll_No.) %>%
summarise(Center_ID = "A",
Report = paste0(Report, collapse = ', '),
Name = unique(Name)
)
Roll_No. Center_ID Report Name
<int> <chr> <chr> <chr>
1 1 A Did well, Sick, Needs more twist Anna
2 2 A Practice required, Did well Bella
3 3 A Needs more practice Catty
```
|
With **`dplyr`** package:
```
library(dplyr)
cbind(df1, Report=df2$Report) %>% group_by(Name) %>%
summarize(RollNo=first(RollNo), CenterID=first(CenterID), Report=paste(toString(Report), first(Name), collapse=' '))
```
Output:
```
Name RollNo CenterID Report
<chr> <dbl> <chr> <chr>
1 Anna 1 A Did well, Sick, Needs more twist Anna
2 Bella 2 A Practice Required, Did well Bella
3 Cathy 3 A Needs more practice Cathy
```
|
69,445,978 |
Lets say I have two franchise of dance schools.
I have two tables. First table tells about students roll no. every
Table 1 =
```
Roll No. Center ID Name Date
1 A Anna 10/10/2020
1 A Anna 11/10/2020
1 B Anna 12/10/2020
2 A Bella 12/10/2020
2 B Bella 13/10/2020
3 A Catty 10/10/2020
```
Table 2 =
```
Roll no. Center ID Report
1 A Did well
1 A Sick
1 B Needs more twist
2 A Practice required
2 B Did well
3 A Needs more practice
```
Result table expected: I want in the result it should pick Center id as A only but Report should be from both the centers
```
Roll no. Center ID Report Name
1 A Did well ,Sick ,Needs more twist Anna
2 A Practice required,Did well Bella
3 A Needs more practice Catty
```
Could someone pls help.
|
2021/10/05
|
['https://Stackoverflow.com/questions/69445978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11496279/']
|
By `dplyr`,
```
t1 %>%
mutate(Report = t2$Report) %>%
group_by(Roll_No.) %>%
summarise(Center_ID = "A",
Report = paste0(Report, collapse = ', '),
Name = unique(Name)
)
Roll_No. Center_ID Report Name
<int> <chr> <chr> <chr>
1 1 A Did well, Sick, Needs more twist Anna
2 2 A Practice required, Did well Bella
3 3 A Needs more practice Catty
```
|
**update:**
With the hint of @Park many thanks!:
Logic:
1. `left_join` by `RollNo.`
2. `filter`, `group_by` and `summarise`
```
library(dplyr)
table1 %>%
left_join(table2, by=c("RollNo."="Rollno.")) %>%
filter(CenterID.x== "A") %>%
group_by(RollNo., CenterID=CenterID.x, Name) %>%
summarise(Report = paste(unique(Report), collapse = ", "))
```
output:
```
RollNo. CenterID Name Report
<dbl> <chr> <chr> <chr>
1 1 A Anna Did well, Sick, Needs more twist
2 2 A Bella Practice required, Did well
3 3 A Catty Needs more practice
```
**First answer:**
We could try this: It is depending on whether `Date` should be considered or not, so you may modify the code:
```
table1 %>%
left_join(table2, by=c("CenterID", "RollNo."="Rollno.")) %>%
filter(CenterID == "A") %>%
group_by(RollNo., CenterID, Name) %>%
summarise(Report = paste(unique(Report), collapse = ", "))
```
```
RollNo. CenterID Name Report
<dbl> <chr> <chr> <chr>
1 1 A Anna Did well, Sick
2 2 A Bella Practice required
3 3 A Catty Needs more practice
```
|
30,107,988 |
I have a sparse banded matrix A and I'd like to (direct) solve Ax=b. I have about 500 vectors b, so I'd like to solve for the corresponding 500 x's.
I'm brand new to CUDA, so I'm a little confused as to what options I have available.
cuSOLVER has a batch direct solver cuSolverSP for sparse A\_i x\_i = b\_i using QR [here](http://devblogs.nvidia.com/parallelforall/parallel-direct-solvers-with-cusolver-batched-qr/). (I'd be fine with LU too since A is decently conditioned.) However, as far as I can tell, I can't exploit the fact that all my A\_i's are the same.
Would an alternative option be to first determine a sparse LU (QR) factorization on the CPU or GPU then perform in parallel the backsubstitution (respectively, backsub and matrix mult) on the GPU? If [cusolverSp< t >csrlsvlu()](http://docs.nvidia.com/cuda/cusolver/index.html#cusolver-lt-t-gt-csrlsvlu) is for one b\_i, is there a standard way to batch perform this operation for multiple b\_i's?
Finally, since I don't have intuition for this, should I expect a speedup on a GPU for either of these options, given the necessary overhead? x has length ~10000-100000. Thanks.
|
2015/05/07
|
['https://Stackoverflow.com/questions/30107988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672126/']
|
I'm currently working on something similar myself. I decided to basically wrap the conjugate gradient and level-0 incomplete cholesky preconditioned conjugate gradient solvers utility samples that came with the CUDA SDK into a small class.
You can find them in your CUDA\_HOME directory under the path:
`samples/7_CUDALibraries/conjugateGradient` and `/Developer/NVIDIA/CUDA-samples/7_CUDALibraries/conjugateGradientPrecond`
Basically, you would load the matrix into the device memory once (and for ICCG, compute the corresponding conditioner / matrix analysis) then call the solve kernel with different b vectors.
I don't know what you anticipate your matrix band structure to look like, but if it is symmetric and either diagonally dominant (off diagonal bands along each row and column are opposite sign of diagonal and their sum is less than the diagonal entry) or positive definite (no eigenvectors with an eigenvalue of 0.) then CG and ICCG should be useful. Alternately, the various multigrid algorithms are another option if you are willing to go through coding them up.
If your matrix is only positive semi-definite (e.g. has at least one eigenvector with an eigenvalue of zero) you can still ofteb get away with using CG or ICCG as long as you ensure that:
1) The right hand side (b vectors) are orthogonal to the null space (null space meaning eigenvectors with an eigenvalue of zero).
2) The solution you obtain is orthogonal to the null space.
It is interesting to note that if you do have a non-trivial null space, then different numeric solvers can give you different answers for the same exact system. The solutions will end up differing by a linear combination of the null space... That problem has caused me many many man hours of debugging and frustration before I finally caught on, so its good to be aware of it.
Lastly, if your matrix has a [Circulant Band structure](https://en.wikipedia.org/?title=Circulant_matrix) you might consider using a fast fourier transform (FFT) based solver. FFT based numerical solvers can often yield superior performance in cases where they are applicable.
|
If you don't mind going with an open-source library, you could also check out CUSP:
[CUSP Quick Start Page](https://code.google.com/p/cusp-library/wiki/QuickStartGuide)
It has a fairly decent suite of solvers, including a few preconditioned methods:
[CUSP Preconditioner Examples](http://code.google.com/p/cusp-library/source/browse/#hg%2Fexamples%2FPreconditioners)
The smoothed aggregation preconditioner (a variant of algebraic multigrid) seems to work very well as long as your GPU has enough onboard memory for it.
|
30,107,988 |
I have a sparse banded matrix A and I'd like to (direct) solve Ax=b. I have about 500 vectors b, so I'd like to solve for the corresponding 500 x's.
I'm brand new to CUDA, so I'm a little confused as to what options I have available.
cuSOLVER has a batch direct solver cuSolverSP for sparse A\_i x\_i = b\_i using QR [here](http://devblogs.nvidia.com/parallelforall/parallel-direct-solvers-with-cusolver-batched-qr/). (I'd be fine with LU too since A is decently conditioned.) However, as far as I can tell, I can't exploit the fact that all my A\_i's are the same.
Would an alternative option be to first determine a sparse LU (QR) factorization on the CPU or GPU then perform in parallel the backsubstitution (respectively, backsub and matrix mult) on the GPU? If [cusolverSp< t >csrlsvlu()](http://docs.nvidia.com/cuda/cusolver/index.html#cusolver-lt-t-gt-csrlsvlu) is for one b\_i, is there a standard way to batch perform this operation for multiple b\_i's?
Finally, since I don't have intuition for this, should I expect a speedup on a GPU for either of these options, given the necessary overhead? x has length ~10000-100000. Thanks.
|
2015/05/07
|
['https://Stackoverflow.com/questions/30107988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672126/']
|
I'm currently working on something similar myself. I decided to basically wrap the conjugate gradient and level-0 incomplete cholesky preconditioned conjugate gradient solvers utility samples that came with the CUDA SDK into a small class.
You can find them in your CUDA\_HOME directory under the path:
`samples/7_CUDALibraries/conjugateGradient` and `/Developer/NVIDIA/CUDA-samples/7_CUDALibraries/conjugateGradientPrecond`
Basically, you would load the matrix into the device memory once (and for ICCG, compute the corresponding conditioner / matrix analysis) then call the solve kernel with different b vectors.
I don't know what you anticipate your matrix band structure to look like, but if it is symmetric and either diagonally dominant (off diagonal bands along each row and column are opposite sign of diagonal and their sum is less than the diagonal entry) or positive definite (no eigenvectors with an eigenvalue of 0.) then CG and ICCG should be useful. Alternately, the various multigrid algorithms are another option if you are willing to go through coding them up.
If your matrix is only positive semi-definite (e.g. has at least one eigenvector with an eigenvalue of zero) you can still ofteb get away with using CG or ICCG as long as you ensure that:
1) The right hand side (b vectors) are orthogonal to the null space (null space meaning eigenvectors with an eigenvalue of zero).
2) The solution you obtain is orthogonal to the null space.
It is interesting to note that if you do have a non-trivial null space, then different numeric solvers can give you different answers for the same exact system. The solutions will end up differing by a linear combination of the null space... That problem has caused me many many man hours of debugging and frustration before I finally caught on, so its good to be aware of it.
Lastly, if your matrix has a [Circulant Band structure](https://en.wikipedia.org/?title=Circulant_matrix) you might consider using a fast fourier transform (FFT) based solver. FFT based numerical solvers can often yield superior performance in cases where they are applicable.
|
>
> is there a standard way to batch perform this operation for multiple b\_i's?
>
>
>
One option is to use the batched refactorization module in CUDA's cuSOLVER, but I am not sure if it is *standard*.
Batched refactorization module in cuSOLVER provides an efficient method to solve batches of linear systems with fixed left-hand side sparse matrix (or matrices with fixed sparsity pattern but varying coefficients) and varying right-hand sides, based on LU decomposition. Only some partially completed code snippets can be found in the official documentation (as of CUDA 10.1) that are related to it. A complete example can be found [here](https://github.com/zishun/cuSolverRf-batch).
|
30,107,988 |
I have a sparse banded matrix A and I'd like to (direct) solve Ax=b. I have about 500 vectors b, so I'd like to solve for the corresponding 500 x's.
I'm brand new to CUDA, so I'm a little confused as to what options I have available.
cuSOLVER has a batch direct solver cuSolverSP for sparse A\_i x\_i = b\_i using QR [here](http://devblogs.nvidia.com/parallelforall/parallel-direct-solvers-with-cusolver-batched-qr/). (I'd be fine with LU too since A is decently conditioned.) However, as far as I can tell, I can't exploit the fact that all my A\_i's are the same.
Would an alternative option be to first determine a sparse LU (QR) factorization on the CPU or GPU then perform in parallel the backsubstitution (respectively, backsub and matrix mult) on the GPU? If [cusolverSp< t >csrlsvlu()](http://docs.nvidia.com/cuda/cusolver/index.html#cusolver-lt-t-gt-csrlsvlu) is for one b\_i, is there a standard way to batch perform this operation for multiple b\_i's?
Finally, since I don't have intuition for this, should I expect a speedup on a GPU for either of these options, given the necessary overhead? x has length ~10000-100000. Thanks.
|
2015/05/07
|
['https://Stackoverflow.com/questions/30107988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672126/']
|
>
> is there a standard way to batch perform this operation for multiple b\_i's?
>
>
>
One option is to use the batched refactorization module in CUDA's cuSOLVER, but I am not sure if it is *standard*.
Batched refactorization module in cuSOLVER provides an efficient method to solve batches of linear systems with fixed left-hand side sparse matrix (or matrices with fixed sparsity pattern but varying coefficients) and varying right-hand sides, based on LU decomposition. Only some partially completed code snippets can be found in the official documentation (as of CUDA 10.1) that are related to it. A complete example can be found [here](https://github.com/zishun/cuSolverRf-batch).
|
If you don't mind going with an open-source library, you could also check out CUSP:
[CUSP Quick Start Page](https://code.google.com/p/cusp-library/wiki/QuickStartGuide)
It has a fairly decent suite of solvers, including a few preconditioned methods:
[CUSP Preconditioner Examples](http://code.google.com/p/cusp-library/source/browse/#hg%2Fexamples%2FPreconditioners)
The smoothed aggregation preconditioner (a variant of algebraic multigrid) seems to work very well as long as your GPU has enough onboard memory for it.
|
155,403 |
In the ancient times when things were easy, you just had to code a form in html and then your php would typically have a if($\_REQUEST['some\_value']) to handle the request. But now with Drupal, nothing is easy... Here is once more my latest battle to understand how Drupal thinks.
Context: I have a list of news (content type "news") shown on a page with paging system. Each news title links to the news details page. This works fine. There is a new requirement that each news must have one or more "tags". The goal is to show a list of checkboxes on top of the news list to allow the user to filter in/out news with the selected tags.
EDIT: After being defeated by Drupal's form I decided to completely bypass the Form API and generate my own fully flexible form.
There is only one thing remaining, Drupal is forcing some div wrappers around each of my input fields. I want to get rid of them (and stop Drupal to think at my place).
In my\_news\_list.tpl.php I coded:
```
<form action="" method="post"> <!-- recall same page on submit -->
<?php
foreach($tags as $tag){
?><input type="checkbox" name="tags[]"
value="<?php echo $tag['id'] ?>"
onchange="form.submit();"
<?php if(isset($tag['checked'])){?>checked="checked"<?php }?>
/><?php echo $tag['value'] ?><?php
}
?>
</form>
```
Result(!):
```
<form action="" method="post">
<div class=" ui-checkbox"> <!-- Why those div wrappers?! -->
<input type="checkbox" name="tags[]" value="15" onchange="form.submit();">
</div>
Acquisitions
<div class=" ui-checkbox">
<input type="checkbox" name="tags[]" value="14" onchange="form.submit();">
</div>
Corporate
<div class=" ui-checkbox">
<input type="checkbox" name="tags[]" value="18" onchange="form.submit();">
</div>
Investor News
<div class=" ui-checkbox">
<input type="checkbox" name="tags[]" value="16" onchange="form.submit();">
</div>
Products and Services
</form>
```
|
2015/04/16
|
['https://drupal.stackexchange.com/questions/155403', 'https://drupal.stackexchange.com', 'https://drupal.stackexchange.com/users/39325/']
|
Drupal's Form API is complex but gives you lot of things: is secure, is extensible, is themeable. Indeed is more difficult than coding a simple HTML form, but with a simpel HTML form you have a simple functionality: just that simple HTML form.
Form API generates the form HTML element and handles the POST requests, and validate and submithandlers, you don't and you shouldn't code your own HTML form.
I recommend you to read the [Drupal 6 Form API Quickstart Guide](https://www.drupal.org/node/751826). Drupal 7 form handling is pretty the same, but check the [Drupal 7 Form API Reference](http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7) and [Form API Internal Workflow Illustration](https://www.drupal.org/node/165104).
In the other hand you may prefer to use a module that address what you need without coding, that's a faceted search: [Facet API](https://www.drupal.org/project/facetapi). From its [documentation page](http://www.trellon.com/content/blog/apachesolr-and-facetapi):
>
> Faceted search allows our search results to be filtered by defined
> criteria like category, date, author, location, or anything else that
> can come out of a field. We call these criteria facets. With facets,
> you can narrow down your search more and more until you get to the
> desired results.
>
>
>
|
The issue here is theme\_wrappers around your form elements.
// @see: <https://drupal.stackexchange.com/a/193587/58635>
|
18,292 |
Приложение с союзом как обычно имеет дополнительное значение причинности (можно заменить придаточным причины с союзами так как, потому что, поскольку или оборотом со словом будучи) и обособляется:
Как старый артиллерист, я презираю этот вид холодного оружия (Шолохов). – Будучи старым артиллеристом, я презираю этот вид холодного оружия; Я презираю этот вид холодного оружия, потому что я старый артиллерист.
Мой друг, как лучший математик класса, будет участником олимпиады.
Мой друг как лучший математик класса будет участником олимпиады.
Здесь постановка запятых зависит от интонации?
Я, как лучший математик класса, буду участником олимпиады.
Я как лучший математик класса буду участником олимпиады.
оба эти варианта возможны в зависимости от интонации?
Или если определяемое слово - местоимение, то обязательно выделять запятыми приложение?
|
2013/04/09
|
['https://rus.stackexchange.com/questions/18292', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/1197/']
|
Обособление - это выделение в устной речи интонационно, а в письменной речи - с помощью знаков препинания. И то, и другое в данном случае зависит от смысла, который вы вкладываете во фразу. Правильные знаки помогают читающему понять суть.
|
Любое приложение при личном местоимении обособляется, и прочитать вы его сможете только с интонацией выделения. Так что вариантов нет:Я, как лучший математик класса, буду участником олимпиады. А значение у приложения явно причинное.
Мой друг, как лучший математик класса, будет участником олимпиады. - тоже без вариантов, потому что другого значения, кроме причинного, здесь нет. Так как он лучший математик, поэтому и будет участником олимпиады.
|
21,438,650 |
I am sorry if this question has been asked before, but could not find a solution to my problem. Which `apply`-like function fits the below case?
I have an `R` function which has 3 arguments `(x, y, z)`. What it does is basically to call an `PostgreSQL` function which quires `x, y, z` and retrieve a dataframe consisting of corresponding values `a, b, c`, something like this;
```
myfunc <- function(x, y, z){
get.df <- fn$sqldf("SELECT * FROM retrieve_meta_data('$x', '$y', '$z')")
# get.df is a dataframe consisting of x number of rows and columns a, b, c
# some dataframe manipulation...
return(get.df)
}
```
What I am looking for is to call this function by using a dataframe `(call.df)` with x number of rows and columns `x, y, z`. So `apply` the function for each ith row and using the columns as arguments.
I have looked through a range of `apply`-like functions but I have failed so far. It's probably way easy.
I imagine something like `apply(call.df, c(1,2), myfunc)` but this gives the error;
```
Error in eval(expr, envir, enclos) :
argument "y" is missing, with no default
```
I hope am clear enough without supplying any dummy data. Any pointers would be very much appreciated, thanks!
|
2014/01/29
|
['https://Stackoverflow.com/questions/21438650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1734415/']
|
If x, y, and z are the first three columns of df, then this should work:
```
apply(df,1,function(params)myfunc(params[1],params[2], params[3]))
```
`apply(df,1,FUN)` takes the first argument, `df`, and passes it to FUN row-wise (because the second argument is 1). So in `function(params)`, params is a row of `df`. Hence, `params[1]` is the first column of that row, etc.
|
This version will work if your arguments are of different types, though in this case it looks like they are all character or can be treated as such so `apply` works fine.
```
sapply(
split(df, 1:nrow(df)),
function(x) do.call(myfunc, x)
)
```
|
21,438,650 |
I am sorry if this question has been asked before, but could not find a solution to my problem. Which `apply`-like function fits the below case?
I have an `R` function which has 3 arguments `(x, y, z)`. What it does is basically to call an `PostgreSQL` function which quires `x, y, z` and retrieve a dataframe consisting of corresponding values `a, b, c`, something like this;
```
myfunc <- function(x, y, z){
get.df <- fn$sqldf("SELECT * FROM retrieve_meta_data('$x', '$y', '$z')")
# get.df is a dataframe consisting of x number of rows and columns a, b, c
# some dataframe manipulation...
return(get.df)
}
```
What I am looking for is to call this function by using a dataframe `(call.df)` with x number of rows and columns `x, y, z`. So `apply` the function for each ith row and using the columns as arguments.
I have looked through a range of `apply`-like functions but I have failed so far. It's probably way easy.
I imagine something like `apply(call.df, c(1,2), myfunc)` but this gives the error;
```
Error in eval(expr, envir, enclos) :
argument "y" is missing, with no default
```
I hope am clear enough without supplying any dummy data. Any pointers would be very much appreciated, thanks!
|
2014/01/29
|
['https://Stackoverflow.com/questions/21438650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1734415/']
|
If x, y, and z are the first three columns of df, then this should work:
```
apply(df,1,function(params)myfunc(params[1],params[2], params[3]))
```
`apply(df,1,FUN)` takes the first argument, `df`, and passes it to FUN row-wise (because the second argument is 1). So in `function(params)`, params is a row of `df`. Hence, `params[1]` is the first column of that row, etc.
|
Just apply over `1` for your margin; then the row is passed to your function as a vector and you should be able to deal with it. For example:
```
> apply(iris, 1, function(v) paste(v["Species"], v["Sepal.Width"]))
[1] "setosa 3.5" "setosa 3.0" "setosa 3.2" "setosa 3.1"
...
```
|
21,438,650 |
I am sorry if this question has been asked before, but could not find a solution to my problem. Which `apply`-like function fits the below case?
I have an `R` function which has 3 arguments `(x, y, z)`. What it does is basically to call an `PostgreSQL` function which quires `x, y, z` and retrieve a dataframe consisting of corresponding values `a, b, c`, something like this;
```
myfunc <- function(x, y, z){
get.df <- fn$sqldf("SELECT * FROM retrieve_meta_data('$x', '$y', '$z')")
# get.df is a dataframe consisting of x number of rows and columns a, b, c
# some dataframe manipulation...
return(get.df)
}
```
What I am looking for is to call this function by using a dataframe `(call.df)` with x number of rows and columns `x, y, z`. So `apply` the function for each ith row and using the columns as arguments.
I have looked through a range of `apply`-like functions but I have failed so far. It's probably way easy.
I imagine something like `apply(call.df, c(1,2), myfunc)` but this gives the error;
```
Error in eval(expr, envir, enclos) :
argument "y" is missing, with no default
```
I hope am clear enough without supplying any dummy data. Any pointers would be very much appreciated, thanks!
|
2014/01/29
|
['https://Stackoverflow.com/questions/21438650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1734415/']
|
If x, y, and z are the first three columns of df, then this should work:
```
apply(df,1,function(params)myfunc(params[1],params[2], params[3]))
```
`apply(df,1,FUN)` takes the first argument, `df`, and passes it to FUN row-wise (because the second argument is 1). So in `function(params)`, params is a row of `df`. Hence, `params[1]` is the first column of that row, etc.
|
It's helpful if you supply sample data so you get an answer that matches your situation, but it sounds like you're looking for `mapply`, e.g.,
```
do.call(mapply, c(myfunc, call.df[c(x.col, y.col, z.col)]))
```
|
21,438,650 |
I am sorry if this question has been asked before, but could not find a solution to my problem. Which `apply`-like function fits the below case?
I have an `R` function which has 3 arguments `(x, y, z)`. What it does is basically to call an `PostgreSQL` function which quires `x, y, z` and retrieve a dataframe consisting of corresponding values `a, b, c`, something like this;
```
myfunc <- function(x, y, z){
get.df <- fn$sqldf("SELECT * FROM retrieve_meta_data('$x', '$y', '$z')")
# get.df is a dataframe consisting of x number of rows and columns a, b, c
# some dataframe manipulation...
return(get.df)
}
```
What I am looking for is to call this function by using a dataframe `(call.df)` with x number of rows and columns `x, y, z`. So `apply` the function for each ith row and using the columns as arguments.
I have looked through a range of `apply`-like functions but I have failed so far. It's probably way easy.
I imagine something like `apply(call.df, c(1,2), myfunc)` but this gives the error;
```
Error in eval(expr, envir, enclos) :
argument "y" is missing, with no default
```
I hope am clear enough without supplying any dummy data. Any pointers would be very much appreciated, thanks!
|
2014/01/29
|
['https://Stackoverflow.com/questions/21438650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1734415/']
|
This version will work if your arguments are of different types, though in this case it looks like they are all character or can be treated as such so `apply` works fine.
```
sapply(
split(df, 1:nrow(df)),
function(x) do.call(myfunc, x)
)
```
|
Just apply over `1` for your margin; then the row is passed to your function as a vector and you should be able to deal with it. For example:
```
> apply(iris, 1, function(v) paste(v["Species"], v["Sepal.Width"]))
[1] "setosa 3.5" "setosa 3.0" "setosa 3.2" "setosa 3.1"
...
```
|
21,438,650 |
I am sorry if this question has been asked before, but could not find a solution to my problem. Which `apply`-like function fits the below case?
I have an `R` function which has 3 arguments `(x, y, z)`. What it does is basically to call an `PostgreSQL` function which quires `x, y, z` and retrieve a dataframe consisting of corresponding values `a, b, c`, something like this;
```
myfunc <- function(x, y, z){
get.df <- fn$sqldf("SELECT * FROM retrieve_meta_data('$x', '$y', '$z')")
# get.df is a dataframe consisting of x number of rows and columns a, b, c
# some dataframe manipulation...
return(get.df)
}
```
What I am looking for is to call this function by using a dataframe `(call.df)` with x number of rows and columns `x, y, z`. So `apply` the function for each ith row and using the columns as arguments.
I have looked through a range of `apply`-like functions but I have failed so far. It's probably way easy.
I imagine something like `apply(call.df, c(1,2), myfunc)` but this gives the error;
```
Error in eval(expr, envir, enclos) :
argument "y" is missing, with no default
```
I hope am clear enough without supplying any dummy data. Any pointers would be very much appreciated, thanks!
|
2014/01/29
|
['https://Stackoverflow.com/questions/21438650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1734415/']
|
It's helpful if you supply sample data so you get an answer that matches your situation, but it sounds like you're looking for `mapply`, e.g.,
```
do.call(mapply, c(myfunc, call.df[c(x.col, y.col, z.col)]))
```
|
Just apply over `1` for your margin; then the row is passed to your function as a vector and you should be able to deal with it. For example:
```
> apply(iris, 1, function(v) paste(v["Species"], v["Sepal.Width"]))
[1] "setosa 3.5" "setosa 3.0" "setosa 3.2" "setosa 3.1"
...
```
|
15,588,510 |
This is a two-part question from a newbie.
First, I need an encoding for simple text (without the lowercase/caps distinction), and I need it to be more space-efficient than ASCII. So I have thought of creating my own 5-bit code, holding a range of 32 characters (the alphabet plus some punctuation marks).
As far as I understand, all modern computing 'thinks' in bytes, so I cannot actually define my own 5-bit encoding without actually resorting to a 8-bit encoding.
What I am thinking of doing is:
I define my own 5-bit code and I save the text in 3-character blocks, each block saved as 2 bytes. Every block will occupy total of 15 bits, which will be stored within two bytes (holding 16 bits). I might use the extra bit for parity check, even if I don't actually need it.
Does this approach make sense? Or is there any better approach?
Alternatively, I might define a 6-bit encoding, and save the text into blocks of 4 characters each, with each block being saved in 3 bytes.
The second part of the question is: assuming that the text will then be compressed (via a standard lossless algorithm for texts, such as zip for example), is it worth the trouble of creating my own encoding (as explained above)? Or will the compression algorithm take care of the space inefficiency of the 8-bit encoding, making the compressed as efficient as a compressed file which originally was encoded using a 5-bit or 6-bit encoding? If so, I would have no advantage of using a 5/6 bit encoding for pre-compression text, so I would simply skip altogether this step.
I need to know from experienced programmers, what is the case?
Thanks everyone
|
2013/03/23
|
['https://Stackoverflow.com/questions/15588510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2134205/']
|
This is precisely what they're doing. It's called recursion, and it's, well, hard to wrap your head around at first. Imagine you have strings:
A B C D
Effectively, what you do, is choose each string in turn and then find all permutations of the remaining strings, and prepend your chosen string.
```
Choose A, get all permutations of {B,C,D} and append A.
Choose B, get all permutations of {A,C,D} and append B.
Choose C, get all permutations of {A,B,D} and append C.
Choose D, get all permutations of {A,B,C} and append D.
```
Now, we have subproblems that look very similar, but are smaller. That's the heart of recursion. Take a problem, and find a way to turn it into a smaller version of the problem. Now, keep turning it into a smaller problem until it's trivial. Now we have to figure out how to generate permutations of 3 strings.
```
Permute(A B C)
Choose A, get all permutations of {B,C} and append A.
Choose B, get all permutations of {A,C} and append B.
Choose C, get all permutations of {A,B} and append C.
```
Same structure, but smaller problems. So take it a step further. How do we do permute(A B)
```
Permute(A B)
Choose A, get all permutations of {B} and append A.
Choose B, get all permutations of {A} and append B.
```
So now we just have to permute one string. That's trivial.
```
Permute(A)
A
```
So now we have a way to Permute a list of strings of size 1, and we've defined how to permute a list of size N by Permuting a list of size N-1. So, we can permute any list of size >= 1, by calling ourselves with a slightly smaller version of the problem. That's the beauty of recursion. You just define how to solve the smallest problem, and how to use that solution to build a bigger solution, and it builds upon itself.
|
This is a recursive algorithm, it essentially takes each element in the array as the first one then adds to to it the output of calling itself without that element.
Take 3 elements A, B and C and walk through the logic, lets call our function `perm`.
so, we want
```
perm({A, B, C})
```
this equals
```
A + perm({B, C})
B + perm({A, C})
C + perm({A, B})
```
expand again
```
A + B + perm({C})
A + C + perm({B})
B + A + perm({C})
B + C + perm({A})
C + A + perm({B})
C + B + perm({A})
```
as `perm({X}) = X` we end up with
```
A + B + C
A + C + B
B + A + C
B + C + A
C + A + B
C + B + A
```
|
15,588,510 |
This is a two-part question from a newbie.
First, I need an encoding for simple text (without the lowercase/caps distinction), and I need it to be more space-efficient than ASCII. So I have thought of creating my own 5-bit code, holding a range of 32 characters (the alphabet plus some punctuation marks).
As far as I understand, all modern computing 'thinks' in bytes, so I cannot actually define my own 5-bit encoding without actually resorting to a 8-bit encoding.
What I am thinking of doing is:
I define my own 5-bit code and I save the text in 3-character blocks, each block saved as 2 bytes. Every block will occupy total of 15 bits, which will be stored within two bytes (holding 16 bits). I might use the extra bit for parity check, even if I don't actually need it.
Does this approach make sense? Or is there any better approach?
Alternatively, I might define a 6-bit encoding, and save the text into blocks of 4 characters each, with each block being saved in 3 bytes.
The second part of the question is: assuming that the text will then be compressed (via a standard lossless algorithm for texts, such as zip for example), is it worth the trouble of creating my own encoding (as explained above)? Or will the compression algorithm take care of the space inefficiency of the 8-bit encoding, making the compressed as efficient as a compressed file which originally was encoded using a 5-bit or 6-bit encoding? If so, I would have no advantage of using a 5/6 bit encoding for pre-compression text, so I would simply skip altogether this step.
I need to know from experienced programmers, what is the case?
Thanks everyone
|
2013/03/23
|
['https://Stackoverflow.com/questions/15588510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2134205/']
|
This is precisely what they're doing. It's called recursion, and it's, well, hard to wrap your head around at first. Imagine you have strings:
A B C D
Effectively, what you do, is choose each string in turn and then find all permutations of the remaining strings, and prepend your chosen string.
```
Choose A, get all permutations of {B,C,D} and append A.
Choose B, get all permutations of {A,C,D} and append B.
Choose C, get all permutations of {A,B,D} and append C.
Choose D, get all permutations of {A,B,C} and append D.
```
Now, we have subproblems that look very similar, but are smaller. That's the heart of recursion. Take a problem, and find a way to turn it into a smaller version of the problem. Now, keep turning it into a smaller problem until it's trivial. Now we have to figure out how to generate permutations of 3 strings.
```
Permute(A B C)
Choose A, get all permutations of {B,C} and append A.
Choose B, get all permutations of {A,C} and append B.
Choose C, get all permutations of {A,B} and append C.
```
Same structure, but smaller problems. So take it a step further. How do we do permute(A B)
```
Permute(A B)
Choose A, get all permutations of {B} and append A.
Choose B, get all permutations of {A} and append B.
```
So now we just have to permute one string. That's trivial.
```
Permute(A)
A
```
So now we have a way to Permute a list of strings of size 1, and we've defined how to permute a list of size N by Permuting a list of size N-1. So, we can permute any list of size >= 1, by calling ourselves with a slightly smaller version of the problem. That's the beauty of recursion. You just define how to solve the smallest problem, and how to use that solution to build a bigger solution, and it builds upon itself.
|
The scheme used is "divide and conquer". It's basic idea is to break up a big problem into a set of smaller problems to which the same mechanism is applied until an "atomic" level of the problem is reached. In other words: A problem of size n is broken up into n problems of size n-1 continuously. At the bottom there is a simple way of dealing with the problem of size 1 (or any other constant). This is usually done using recursion (as Calgar99) pointed out already.
A very nice example of that scheme that will also twist you head a bit are the "Towers of Hanoi". Check it out and the ingenuity of such an approach will hit you.
As for the presented code: The permutation of n words is the concatenation of the permutation of n-1 words with each of the n original words. This recursive definition represents a quite elegant solution for the problem.
|
33,397,094 |
**This part works.**
In my C#.NET WPF XAML, I have a **static** ComboBox and a **static** TextBox. The TextBox displays another column from the same DataTable (in the ComboBox's ItemSource). The column "rr\_code" is the column for company name and the column "rr\_addr" is the column for the address.
```
<ComboBox x:Name="CompanyComboBox1" IsEditable="True" IsTextSearchEnabled="True" IsSynchronizedWithCurrentItem="False"/>
<TextBox x:Name="StreetTextBox1" DataContext="{Binding SelectedItem, ElementName=CompanyComboBox1}" Text="{Binding rr_addr}" IsManipulationEnabled="True"\>
```
The ComboBox reads programmatically from a column in a DataTable:
```
CompanyComboBox1.ItemsSource = Rails.DefaultView; // Rails is a DataTable
CompanyComboBox1.DisplayMemberPath = "rr_code"; // column name for company name
```
**This part doesn't work**
The question is, I now have a "Add Company" button that creates a new form in a StackPanel, **dynamically** and with this exact functionality. The ComboBox works exactly as expected. Here's what I have so far:
```
ComboBox companyComboBox = new ComboBox();
companyComboBox.ItemsSource = Rails.DefaultView;
companyComboBox.IsEditable = true;
companyComboBox.IsTextSearchEnabled = true;
companyComboBox.DisplayMemberPath = "rr_code";
```
The problem is in the TextBox, which is not updating when I change the dynamic companyComboBox, so I'm sure it has to do with the binding.
```
TextBox streetTextBox = new TextBox();
streetTextBox.DataContext = companyComboBox;
Binding b = new Binding("rr_addr");
b.Mode = BindingMode.Default;
b.Source = companyComboBox.SelectedItem;
streetTextBox.SetBinding(ComboBox.SelectedItemProperty, b);
```
What is the correct way to set the binding for the TextBox streetTextBox?
|
2015/10/28
|
['https://Stackoverflow.com/questions/33397094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3847534/']
|
The code-behind equivalent of this particular XAML + C# data binding in pure C# is:
```
ComboBox companyComboBox = new ComboBox();
companyComboBox.ItemsSource = Rails.DefaultView; // Rails being DataTable
companyComboBox.IsEditable = true;
companyComboBox.IsTextSearchEnabled = true;
companyComboBox.DisplayMemberPath = "rr_code";
Binding b = new Binding("SelectedItem.rr_addr"); // The selected item's 'rr_addr' column ...
b.Source = companyComboBox; // ... of the companyComboBox ...
TextBox streetTextBox = new TextBox();
streetTextBox.SetBinding(TextBox.TextProperty,b); // ... is bound to streetTextBox's Text property.
```
The error was in the last line. SetBinding needed to have a property of the target, not the source. In addition, the Binding declaration needed "SelectedItem." for some reason.
|
Why are you setting the TextBox DataContext ?
You can simply bind TextBox.Text property to ComboBox SelectedItem in your XAML
```
<TextBox Text="{Binding ElementName=CompanyComboBox1, Path=SelectedItem.rr_addr}"></TextBox>
```
|
70,421,369 |
I have
```cpp
class ClassA {};
class ClassB {};
auto func_a() -> ClassA {
return ClassA(); // example implementation for illustration. in reality can be different. does not match the form of func_b
}
auto func_b() -> ClassB {
return ClassB(); // example implementation for illustration. in reality can be different. does not match the form of func_a
}
```
I want to be able to use the syntax
```cpp
func<ClassA>() // instead of func_a()
func<ClassB>() // instead of func_b()
```
(this is as part of a bigger template)
but I don't know how to implement this template specialization for the function alias.
Help? What is the syntax for this?
[Edit] The answers posted so far do not answer my question, so I'll edit my question to be more clear.
The actual definition of func\_a and func\_b is more complex than just "return Type();". Also they cannot be touched. So consider them to be
```
auto func_a() -> ClassA {
// unknown implementation. returns ClassA somehow
}
auto func_b() -> ClassB {
// unknown implementation. returns ClassB somehow
}
```
I cannot template the contents of func\_a or func\_b. I need the template for func<ClassA|ClassB> to be specialized for each one of the two and be able to select the correct one to call
|
2021/12/20
|
['https://Stackoverflow.com/questions/70421369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11249764/']
|
You might do something like (c++17):
```cpp
template <typename T>
auto func()
{
if constexpr (std::is_same_v<T, ClassA>) {
return func_a();
} else {
return func_b();
}
}
```
Alternative for pre-C++17 is tag dispatching (which allows customization point):
```cpp
// Utility class to allow to "pass" Type.
template <typename T> struct Tag{};
// Possibly in namespace details
auto func(Tag<ClassA>) { return func_a(); }
auto func(Tag<ClassB>) { return func_b(); }
template <typename T>
auto func() { return func(Tag<T>{}); }
```
|
You can do it like this :
```
#include <iostream>
#include <type_traits>
class A
{
public:
void hi()
{
std::cout << "hi\n";
}
};
class B
{
public:
void boo()
{
std::cout << "boo\n";
}
};
template<typename type_t>
auto create()
{
// optional : if you only want to be able to create instances of A or B
// static_assert(std::is_same_v<A, type_t> || std::is_same_v<B, type_t>);
type_t object{};
return object;
}
int main()
{
auto a = create<A>();
auto b = create<B>();
a.hi();
b.boo();
return 0;
}
```
|
1,429,246 |
I just compiled the latest preview of Qt4.6 on Snow Leopard in 64 bit without any major issues.
<http://qt.nokia.com/developer/qt-4.6-technology-preview#download-the-qt-4-1>
Now, I am trying to do the same for PyQt4.6 with the latest snapshot from the River Bank website. However, the compiler exits with the following issue:
```
g++ -c -pipe -fPIC -arch x86_64 -O2 -Wall -W -DNDEBUG -DQT_NO_DEBUG -DQT_CORE_LIB -I. -I/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -I/usr/local/Trolltech/Qt-4.6.0/mkspecs/default -I/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers -I/usr/local/Trolltech/Qt-4.6.0/include -F/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -F/usr/local/Trolltech/Qt-4.6.0/lib -o sipQtCoreQResource.o sipQtCoreQResource.cpp
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In copy constructor ‘QResource::QResource(const QResource&)’:
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:180: error: ‘QScopedPointer<T, Cleanup>::QScopedPointer(const QScopedPointer<T, Cleanup>&) [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter<QResourcePrivate>]’ is private
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: error: within this context
sipQtCoreQResource.cpp: In constructor ‘sipQResource::sipQResource(const QResource&)’:
sipQtCoreQResource.cpp:78: note: synthesized method ‘QResource::QResource(const QResource&)’ first required here
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In static member function ‘static void QScopedPointerDeleter<T>::cleanup(T*) [with T = QResourcePrivate]’:
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:100: instantiated from ‘QScopedPointer<T, Cleanup>::~QScopedPointer() [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter<QResourcePrivate>]’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: instantiated from here
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: creating array with negative size (‘-0x00000000000000001’)
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: creating array with negative size (‘-0x00000000000000001’)
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: warning: possible problem detected in invocation of delete operator:
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:54: warning: ‘pointer’ has incomplete type
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:56: warning: forward declaration of ‘struct QResourcePrivate’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.
```
Is this an error with PyQt4 trying to access a private member of a Qt4 class? Has anybody compiled PyQt4 on Snow Leopard successfully?
|
2009/09/15
|
['https://Stackoverflow.com/questions/1429246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134397/']
|
I just got PyQt 4.6.2 working with the 64bit Python 2.6.1. I posted the instructions here: <http://mpastell.com/2009/11/24/pyqt-4-6-2-with-snow-leopard/>
|
In the changelogs I see Phil (PyQt's maintainer) [has issued fixes](http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/ChangeLog-4.6-snapshot-20090914) yesterday in the development snapshots specifically for Snow Leopard:
>
> 2009/09/14 12:12:49 phil Further
> fixes for Snow Leopard on 64 bit
> systems. Added
> QObject.pyqtConfigure().
>
>
>
Are you using yesterday's build of PyQt?
[This thread on the mailinglist](http://www.riverbankcomputing.com/pipermail/pyqt/2009-September/thread.html#24247) is also particulary interesting.
The PyQt compile troubles seems to be caused by Snow Leopards default 64bit compiles and the 64/32 bit mixed version of Python it ships with.
If things continue to go wrong, i would submit your problems to this mailinglist (so they can get fixed - hopefully) and try to (temporarily) rebuild Qt and PyQt (and possibly python) in a 32-bit fashion (with the -m32 compiler flag) if you need it working now.
|
1,429,246 |
I just compiled the latest preview of Qt4.6 on Snow Leopard in 64 bit without any major issues.
<http://qt.nokia.com/developer/qt-4.6-technology-preview#download-the-qt-4-1>
Now, I am trying to do the same for PyQt4.6 with the latest snapshot from the River Bank website. However, the compiler exits with the following issue:
```
g++ -c -pipe -fPIC -arch x86_64 -O2 -Wall -W -DNDEBUG -DQT_NO_DEBUG -DQT_CORE_LIB -I. -I/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -I/usr/local/Trolltech/Qt-4.6.0/mkspecs/default -I/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers -I/usr/local/Trolltech/Qt-4.6.0/include -F/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -F/usr/local/Trolltech/Qt-4.6.0/lib -o sipQtCoreQResource.o sipQtCoreQResource.cpp
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In copy constructor ‘QResource::QResource(const QResource&)’:
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:180: error: ‘QScopedPointer<T, Cleanup>::QScopedPointer(const QScopedPointer<T, Cleanup>&) [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter<QResourcePrivate>]’ is private
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: error: within this context
sipQtCoreQResource.cpp: In constructor ‘sipQResource::sipQResource(const QResource&)’:
sipQtCoreQResource.cpp:78: note: synthesized method ‘QResource::QResource(const QResource&)’ first required here
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In static member function ‘static void QScopedPointerDeleter<T>::cleanup(T*) [with T = QResourcePrivate]’:
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:100: instantiated from ‘QScopedPointer<T, Cleanup>::~QScopedPointer() [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter<QResourcePrivate>]’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: instantiated from here
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: creating array with negative size (‘-0x00000000000000001’)
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: creating array with negative size (‘-0x00000000000000001’)
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: warning: possible problem detected in invocation of delete operator:
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:54: warning: ‘pointer’ has incomplete type
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:56: warning: forward declaration of ‘struct QResourcePrivate’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.
```
Is this an error with PyQt4 trying to access a private member of a Qt4 class? Has anybody compiled PyQt4 on Snow Leopard successfully?
|
2009/09/15
|
['https://Stackoverflow.com/questions/1429246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134397/']
|
In the changelogs I see Phil (PyQt's maintainer) [has issued fixes](http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/ChangeLog-4.6-snapshot-20090914) yesterday in the development snapshots specifically for Snow Leopard:
>
> 2009/09/14 12:12:49 phil Further
> fixes for Snow Leopard on 64 bit
> systems. Added
> QObject.pyqtConfigure().
>
>
>
Are you using yesterday's build of PyQt?
[This thread on the mailinglist](http://www.riverbankcomputing.com/pipermail/pyqt/2009-September/thread.html#24247) is also particulary interesting.
The PyQt compile troubles seems to be caused by Snow Leopards default 64bit compiles and the 64/32 bit mixed version of Python it ships with.
If things continue to go wrong, i would submit your problems to this mailinglist (so they can get fixed - hopefully) and try to (temporarily) rebuild Qt and PyQt (and possibly python) in a 32-bit fashion (with the -m32 compiler flag) if you need it working now.
|
You might want to use PyQt from the homebrew project: straightforward build, managed dependencies.
Run fine on my MBP Unibody, all 64-bit.
|
1,429,246 |
I just compiled the latest preview of Qt4.6 on Snow Leopard in 64 bit without any major issues.
<http://qt.nokia.com/developer/qt-4.6-technology-preview#download-the-qt-4-1>
Now, I am trying to do the same for PyQt4.6 with the latest snapshot from the River Bank website. However, the compiler exits with the following issue:
```
g++ -c -pipe -fPIC -arch x86_64 -O2 -Wall -W -DNDEBUG -DQT_NO_DEBUG -DQT_CORE_LIB -I. -I/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -I/usr/local/Trolltech/Qt-4.6.0/mkspecs/default -I/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers -I/usr/local/Trolltech/Qt-4.6.0/include -F/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -F/usr/local/Trolltech/Qt-4.6.0/lib -o sipQtCoreQResource.o sipQtCoreQResource.cpp
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In copy constructor ‘QResource::QResource(const QResource&)’:
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:180: error: ‘QScopedPointer<T, Cleanup>::QScopedPointer(const QScopedPointer<T, Cleanup>&) [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter<QResourcePrivate>]’ is private
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: error: within this context
sipQtCoreQResource.cpp: In constructor ‘sipQResource::sipQResource(const QResource&)’:
sipQtCoreQResource.cpp:78: note: synthesized method ‘QResource::QResource(const QResource&)’ first required here
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In static member function ‘static void QScopedPointerDeleter<T>::cleanup(T*) [with T = QResourcePrivate]’:
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:100: instantiated from ‘QScopedPointer<T, Cleanup>::~QScopedPointer() [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter<QResourcePrivate>]’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: instantiated from here
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: creating array with negative size (‘-0x00000000000000001’)
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: creating array with negative size (‘-0x00000000000000001’)
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: warning: possible problem detected in invocation of delete operator:
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:54: warning: ‘pointer’ has incomplete type
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:56: warning: forward declaration of ‘struct QResourcePrivate’
/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.
```
Is this an error with PyQt4 trying to access a private member of a Qt4 class? Has anybody compiled PyQt4 on Snow Leopard successfully?
|
2009/09/15
|
['https://Stackoverflow.com/questions/1429246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134397/']
|
I just got PyQt 4.6.2 working with the 64bit Python 2.6.1. I posted the instructions here: <http://mpastell.com/2009/11/24/pyqt-4-6-2-with-snow-leopard/>
|
You might want to use PyQt from the homebrew project: straightforward build, managed dependencies.
Run fine on my MBP Unibody, all 64-bit.
|
15,653,028 |
What is the best way to get the current location in android for the following scenario,
1. If GPS is not available, get location from Network provider
2. If GPS is available and can get current location, get location from GPS provider
3. If GPS is available but can't get current location(i.e continuously searching location), get location from the network provider.
now i can getting a location from network if gps not available, the best answer to satisfy the above scenario is highly appreciated. thanks in advance.
|
2013/03/27
|
['https://Stackoverflow.com/questions/15653028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1351297/']
|
Well, you can use [Timer](http://developer.android.com/reference/java/util/Timer.html) and [TimerTask](http://developer.android.com/reference/java/util/TimerTask.html) classes.
```
LocationManager manager;
TimerTask mTimertask;
GPSLocationListener mGPSLocationListener;
int i = 0; //Here i works as counter;
private static final int MAX_ATTEMPTS = 250;
public void getCurrentLocation() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mGPSLocationListener = new GPSLocationListener();
manager.addGpsStatusListener(mGPSStatusListener);
mTimerTask = new LocTimerTask(LocationManager.GPS_PROVIDER);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.v(TAG, "GPS ENABLED");
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
50.0f, mGPSLocationListener);
} else {
turnGPSOn();
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
50.0f, mGPSLocationListener);
}
if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L,
50.0f, mNetworkLocationListener);
}
if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v(TAG, "GPS ENABLED");
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000L, 50.0f, mGPSLocationListener);
}
myLocTimer = new Timer("LocationRunner", true);
myLocTimer.schedule(mTimerTask, 0, 500);
}
```
**GPSStatusListener**
```
private GpsStatus.Listener mGPSStatusListener = new GpsStatus.Listener() {
@Override
public synchronized void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.v(TAG, "GPS SAtellitestatus");
GpsStatus status = manager.getGpsStatus(null);
mSattelites = 0;
Iterable<GpsSatellite> list = status.getSatellites();
for (GpsSatellite satellite : list) {
if (satellite.usedInFix()) {
mSattelites++;
}
}
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
/*
* Toast.makeText(getApplicationContext(), "Got First Fix",
* Toast.LENGTH_LONG).show();
*/
break;
case GpsStatus.GPS_EVENT_STARTED:
/*
* Toast.makeText(getApplicationContext(), "GPS Event Started",
* Toast.LENGTH_LONG).show();
*/
break;
case GpsStatus.GPS_EVENT_STOPPED:
/*
* Toast.makeText(getApplicationContext(), "GPS Event Stopped",
* Toast.LENGTH_LONG).show();
*/
break;
default:
break;
}
}
};
```
**LocationListener**
```
public class GPSLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location argLocation) {
location = argLocation;
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
```
**TimerTask class**
```
class LocTimerTask extends TimerTask {
String provider;
public LocTimerTask(String provider) {
this.provider = provider;
}
final Handler mHandler = new Handler(Looper.getMainLooper());
Runnable r = new Runnable() {
@Override
public void run() {
i++;
Log.v(TAG, "Timer Task run" + i);
location = manager.getLastKnownLocation(provider);
if (location != null) {
Log.v(TAG, "in timer task run in if location not null");
isGPS = true;
onLocationReceived(location);
myLocTimer.cancel();
myLocTimer.purge();
mTimerTask.cancel();
return;
} else {
Log.v(TAG, "in timer task run in else location null");
isGPS = false;
if (location == null && i == MAX_ATTEMPTS) {
Log.v(TAG, "if 1 max attempts done");
turnGPSOff();
location = manager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.v(TAG,
"if 1 max attempts done Location from network not null");
Log.v(TAG,
"if 1 max attempts done Location from network not null coordinates not null");
onLocationReceived(location);
myLocTimer.cancel();
myLocTimer.purge();
mTimerTask.cancel();
return;
}
} else {
return;
}
}
i = 0;
}
};
public void run() {
mHandler.post(r);
}
}
```
Here the timer has been scheduled to run on every 500 milliseconds. Means, on every 500 milliseconds the timer task's `run method` will executed. In run method try get location from GPS provider for specific no. of attempts(**Here MAX\_ATTEMPTS**) say 5 or 10. If it gets location within specified no. of attempts then use that location else if counter(**Here i**) value has exceeded MAX\_ATTEMPTS, then get location from Network Provider. on getting location, I had passed that location to callback method `onLocationReceived(Location mLoc)` in which you can do your further work with location data. Here's how you will use callback method:
**Listener**
```
public interface OnLocationReceivedListener {
public void onLocationReceived(Location mLoc); //callback method which will be defined in your class.
```
}
Your class should implement the above defined listener. In your class:
```
@Override
public void onLocationReceived(Location mLoc) {
//Do your stuff
}
```
Hope it helps. If anybody have a better approach, then please let me know.
|
```
If GPS is available and can get current location,
```
For the above question you can try like this..
Using this you can get the latitude and longitude for the current location then pass the value to get the map.
```
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: “ +
“Latitud = “ + loc.getLatitude() +
“Longitud = “ + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Disabled”,
Toast.LENGTH_SHORT ).show();
}
@Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Enabled”,
Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
```
|
15,653,028 |
What is the best way to get the current location in android for the following scenario,
1. If GPS is not available, get location from Network provider
2. If GPS is available and can get current location, get location from GPS provider
3. If GPS is available but can't get current location(i.e continuously searching location), get location from the network provider.
now i can getting a location from network if gps not available, the best answer to satisfy the above scenario is highly appreciated. thanks in advance.
|
2013/03/27
|
['https://Stackoverflow.com/questions/15653028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1351297/']
|
Well, you can use [Timer](http://developer.android.com/reference/java/util/Timer.html) and [TimerTask](http://developer.android.com/reference/java/util/TimerTask.html) classes.
```
LocationManager manager;
TimerTask mTimertask;
GPSLocationListener mGPSLocationListener;
int i = 0; //Here i works as counter;
private static final int MAX_ATTEMPTS = 250;
public void getCurrentLocation() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mGPSLocationListener = new GPSLocationListener();
manager.addGpsStatusListener(mGPSStatusListener);
mTimerTask = new LocTimerTask(LocationManager.GPS_PROVIDER);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.v(TAG, "GPS ENABLED");
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
50.0f, mGPSLocationListener);
} else {
turnGPSOn();
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
50.0f, mGPSLocationListener);
}
if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L,
50.0f, mNetworkLocationListener);
}
if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v(TAG, "GPS ENABLED");
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000L, 50.0f, mGPSLocationListener);
}
myLocTimer = new Timer("LocationRunner", true);
myLocTimer.schedule(mTimerTask, 0, 500);
}
```
**GPSStatusListener**
```
private GpsStatus.Listener mGPSStatusListener = new GpsStatus.Listener() {
@Override
public synchronized void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.v(TAG, "GPS SAtellitestatus");
GpsStatus status = manager.getGpsStatus(null);
mSattelites = 0;
Iterable<GpsSatellite> list = status.getSatellites();
for (GpsSatellite satellite : list) {
if (satellite.usedInFix()) {
mSattelites++;
}
}
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
/*
* Toast.makeText(getApplicationContext(), "Got First Fix",
* Toast.LENGTH_LONG).show();
*/
break;
case GpsStatus.GPS_EVENT_STARTED:
/*
* Toast.makeText(getApplicationContext(), "GPS Event Started",
* Toast.LENGTH_LONG).show();
*/
break;
case GpsStatus.GPS_EVENT_STOPPED:
/*
* Toast.makeText(getApplicationContext(), "GPS Event Stopped",
* Toast.LENGTH_LONG).show();
*/
break;
default:
break;
}
}
};
```
**LocationListener**
```
public class GPSLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location argLocation) {
location = argLocation;
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
```
**TimerTask class**
```
class LocTimerTask extends TimerTask {
String provider;
public LocTimerTask(String provider) {
this.provider = provider;
}
final Handler mHandler = new Handler(Looper.getMainLooper());
Runnable r = new Runnable() {
@Override
public void run() {
i++;
Log.v(TAG, "Timer Task run" + i);
location = manager.getLastKnownLocation(provider);
if (location != null) {
Log.v(TAG, "in timer task run in if location not null");
isGPS = true;
onLocationReceived(location);
myLocTimer.cancel();
myLocTimer.purge();
mTimerTask.cancel();
return;
} else {
Log.v(TAG, "in timer task run in else location null");
isGPS = false;
if (location == null && i == MAX_ATTEMPTS) {
Log.v(TAG, "if 1 max attempts done");
turnGPSOff();
location = manager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.v(TAG,
"if 1 max attempts done Location from network not null");
Log.v(TAG,
"if 1 max attempts done Location from network not null coordinates not null");
onLocationReceived(location);
myLocTimer.cancel();
myLocTimer.purge();
mTimerTask.cancel();
return;
}
} else {
return;
}
}
i = 0;
}
};
public void run() {
mHandler.post(r);
}
}
```
Here the timer has been scheduled to run on every 500 milliseconds. Means, on every 500 milliseconds the timer task's `run method` will executed. In run method try get location from GPS provider for specific no. of attempts(**Here MAX\_ATTEMPTS**) say 5 or 10. If it gets location within specified no. of attempts then use that location else if counter(**Here i**) value has exceeded MAX\_ATTEMPTS, then get location from Network Provider. on getting location, I had passed that location to callback method `onLocationReceived(Location mLoc)` in which you can do your further work with location data. Here's how you will use callback method:
**Listener**
```
public interface OnLocationReceivedListener {
public void onLocationReceived(Location mLoc); //callback method which will be defined in your class.
```
}
Your class should implement the above defined listener. In your class:
```
@Override
public void onLocationReceived(Location mLoc) {
//Do your stuff
}
```
Hope it helps. If anybody have a better approach, then please let me know.
|
class member `boolean mIsGpsFix`;
Request Gps location update and set up a countdown timer
```
mCountDown.start();
private CountDownTimer mCountDown = new CountDownTimer(time to wait for Gps fix, same as right)
{
@Override
public void onTick(long millisUntilFinished)
{
}
@Override
public void onFinish()
{
// No fix after the desire amount of time collapse
if (!mIsGpsFix)
// Register for Network
}
};
```
|
58,362,757 |
I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error:
>
> 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from
> assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0
>
>
>
I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library.
Here is my library `.csproj`,
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
```
Here is my `ServiceExtensions` class from my library,
```cs
public static class ServiceExtensions
{
public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.ConfigureOptions<ConfigureLibraryOptions>();
return builder;
}
}
```
Here is my `ConfigureLibraryOptions` class,
```cs
public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
public void Configure(MvcOptions options)
{
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
}
}
```
Here is the `ConfigureServices` from `Startup`,
```cs
services.AddControllersWithViews().AddMyLibrary();
```
Please help on why I'm getting this error and assist on how to solve this?
|
2019/10/13
|
['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']
|
The reason why you're getting the error is because `MvcJsonOptions` was removed in .NET Core 3.0; you can read more about the breaking changes [here](https://github.com/aspnet/Announcements/issues/325).
|
In my case, the solution was to add `services.AddControllers()` as described under <https://github.com/RicoSuter/NSwag/issues/1961#issuecomment-515631411>.
|
58,362,757 |
I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error:
>
> 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from
> assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0
>
>
>
I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library.
Here is my library `.csproj`,
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
```
Here is my `ServiceExtensions` class from my library,
```cs
public static class ServiceExtensions
{
public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.ConfigureOptions<ConfigureLibraryOptions>();
return builder;
}
}
```
Here is my `ConfigureLibraryOptions` class,
```cs
public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
public void Configure(MvcOptions options)
{
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
}
}
```
Here is the `ConfigureServices` from `Startup`,
```cs
services.AddControllersWithViews().AddMyLibrary();
```
Please help on why I'm getting this error and assist on how to solve this?
|
2019/10/13
|
['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']
|
netstandard2.1 to netcoreapp3.0
MvcJsonOptions -> MvcNewtonsoftJsonOptions
```
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//MVC
services.AddControllersWithViews(options =>
{
}).AddNewtonsoftJson();
services.PostConfigure<MvcNewtonsoftJsonOptions>(options => {
options.SerializerSettings.ContractResolver = new MyCustomContractResolver()
{
NamingStrategy = new CamelCaseNamingStrategy()
};
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
}
```
|
When you config "Swashbuckle.AspNetCore", needed for configuring ApiKeyScheme become to OpenApiSecurityScheme it is changing the scheme from
```
c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description =
"Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
{ "Bearer", Enumerable.Empty<string>() }, });
```
To
```
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description =
"JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
```
|
58,362,757 |
I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error:
>
> 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from
> assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0
>
>
>
I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library.
Here is my library `.csproj`,
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
```
Here is my `ServiceExtensions` class from my library,
```cs
public static class ServiceExtensions
{
public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.ConfigureOptions<ConfigureLibraryOptions>();
return builder;
}
}
```
Here is my `ConfigureLibraryOptions` class,
```cs
public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
public void Configure(MvcOptions options)
{
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
}
}
```
Here is the `ConfigureServices` from `Startup`,
```cs
services.AddControllersWithViews().AddMyLibrary();
```
Please help on why I'm getting this error and assist on how to solve this?
|
2019/10/13
|
['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']
|
I'm not sure if this solves OP's problem, but this error also occurs when you use Swashbuckle 4 in .Net Core 3. The solution is to use Swashbuckle 5.
(use command `install-package Swashbuckle.AspNetCore`) to have in .csproj
```
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
```
Then you'll need to upgrade it in Startup.cs. Generally that involves prefixing classes that don't compile with `OpenApi` e.g.
`options.SwaggerDoc("v1" new Info ...`
becomes
`options.SwaggerDoc("v1", OpenApiInfo`
Also `OpenApiSecurityScheme` becomes `ApiKeyScheme`
See also docs at <https://github.com/domaindrivendev/Swashbuckle.AspNetCore>
|
The reason why you're getting the error is because `MvcJsonOptions` was removed in .NET Core 3.0; you can read more about the breaking changes [here](https://github.com/aspnet/Announcements/issues/325).
|
58,362,757 |
I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error:
>
> 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from
> assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0
>
>
>
I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library.
Here is my library `.csproj`,
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
```
Here is my `ServiceExtensions` class from my library,
```cs
public static class ServiceExtensions
{
public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.ConfigureOptions<ConfigureLibraryOptions>();
return builder;
}
}
```
Here is my `ConfigureLibraryOptions` class,
```cs
public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
public void Configure(MvcOptions options)
{
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
}
}
```
Here is the `ConfigureServices` from `Startup`,
```cs
services.AddControllersWithViews().AddMyLibrary();
```
Please help on why I'm getting this error and assist on how to solve this?
|
2019/10/13
|
['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']
|
I'm not sure if this solves OP's problem, but this error also occurs when you use Swashbuckle 4 in .Net Core 3. The solution is to use Swashbuckle 5.
(use command `install-package Swashbuckle.AspNetCore`) to have in .csproj
```
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
```
Then you'll need to upgrade it in Startup.cs. Generally that involves prefixing classes that don't compile with `OpenApi` e.g.
`options.SwaggerDoc("v1" new Info ...`
becomes
`options.SwaggerDoc("v1", OpenApiInfo`
Also `OpenApiSecurityScheme` becomes `ApiKeyScheme`
See also docs at <https://github.com/domaindrivendev/Swashbuckle.AspNetCore>
|
The problem is most likely with the incompatible nuget packages for .net core 3.1 above. Take a look at your packages and eventually upgrade to compatible version of core 3.1. That should really fix the issue I had one with Automapper and others had with Swagger.
If you are using AutoMapper you should upgrade to 7.0.0
See <https://medium.com/@nicky2983/how-to-using-automapper-on-asp-net-core-3-0-via-dependencyinjection-a5d25bd33e5b>
|
58,362,757 |
I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error:
>
> 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from
> assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0
>
>
>
I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library.
Here is my library `.csproj`,
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
```
Here is my `ServiceExtensions` class from my library,
```cs
public static class ServiceExtensions
{
public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.ConfigureOptions<ConfigureLibraryOptions>();
return builder;
}
}
```
Here is my `ConfigureLibraryOptions` class,
```cs
public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
public void Configure(MvcOptions options)
{
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
}
}
```
Here is the `ConfigureServices` from `Startup`,
```cs
services.AddControllersWithViews().AddMyLibrary();
```
Please help on why I'm getting this error and assist on how to solve this?
|
2019/10/13
|
['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']
|
The reason why you're getting the error is because `MvcJsonOptions` was removed in .NET Core 3.0; you can read more about the breaking changes [here](https://github.com/aspnet/Announcements/issues/325).
|
The problem is most likely with the incompatible nuget packages for .net core 3.1 above. Take a look at your packages and eventually upgrade to compatible version of core 3.1. That should really fix the issue I had one with Automapper and others had with Swagger.
If you are using AutoMapper you should upgrade to 7.0.0
See <https://medium.com/@nicky2983/how-to-using-automapper-on-asp-net-core-3-0-via-dependencyinjection-a5d25bd33e5b>
|
58,362,757 |
I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error:
>
> 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from
> assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0
>
>
>
I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library.
Here is my library `.csproj`,
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
```
Here is my `ServiceExtensions` class from my library,
```cs
public static class ServiceExtensions
{
public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.ConfigureOptions<ConfigureLibraryOptions>();
return builder;
}
}
```
Here is my `ConfigureLibraryOptions` class,
```cs
public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
public void Configure(MvcOptions options)
{
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
}
}
```
Here is the `ConfigureServices` from `Startup`,
```cs
services.AddControllersWithViews().AddMyLibrary();
```
Please help on why I'm getting this error and assist on how to solve this?
|
2019/10/13
|
['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']
|
I'm not sure if this solves OP's problem, but this error also occurs when you use Swashbuckle 4 in .Net Core 3. The solution is to use Swashbuckle 5.
(use command `install-package Swashbuckle.AspNetCore`) to have in .csproj
```
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
```
Then you'll need to upgrade it in Startup.cs. Generally that involves prefixing classes that don't compile with `OpenApi` e.g.
`options.SwaggerDoc("v1" new Info ...`
becomes
`options.SwaggerDoc("v1", OpenApiInfo`
Also `OpenApiSecurityScheme` becomes `ApiKeyScheme`
See also docs at <https://github.com/domaindrivendev/Swashbuckle.AspNetCore>
|
In my case, the solution was to add `services.AddControllers()` as described under <https://github.com/RicoSuter/NSwag/issues/1961#issuecomment-515631411>.
|
58,362,757 |
I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error:
>
> 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from
> assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0
>
>
>
I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library.
Here is my library `.csproj`,
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
```
Here is my `ServiceExtensions` class from my library,
```cs
public static class ServiceExtensions
{
public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.ConfigureOptions<ConfigureLibraryOptions>();
return builder;
}
}
```
Here is my `ConfigureLibraryOptions` class,
```cs
public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
public void Configure(MvcOptions options)
{
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
}
}
```
Here is the `ConfigureServices` from `Startup`,
```cs
services.AddControllersWithViews().AddMyLibrary();
```
Please help on why I'm getting this error and assist on how to solve this?
|
2019/10/13
|
['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']
|
The problem is most likely with the incompatible nuget packages for .net core 3.1 above. Take a look at your packages and eventually upgrade to compatible version of core 3.1. That should really fix the issue I had one with Automapper and others had with Swagger.
If you are using AutoMapper you should upgrade to 7.0.0
See <https://medium.com/@nicky2983/how-to-using-automapper-on-asp-net-core-3-0-via-dependencyinjection-a5d25bd33e5b>
|
In my case, the solution was to add `services.AddControllers()` as described under <https://github.com/RicoSuter/NSwag/issues/1961#issuecomment-515631411>.
|
58,362,757 |
I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error:
>
> 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from
> assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0
>
>
>
I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library.
Here is my library `.csproj`,
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
```
Here is my `ServiceExtensions` class from my library,
```cs
public static class ServiceExtensions
{
public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.ConfigureOptions<ConfigureLibraryOptions>();
return builder;
}
}
```
Here is my `ConfigureLibraryOptions` class,
```cs
public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
public void Configure(MvcOptions options)
{
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
}
}
```
Here is the `ConfigureServices` from `Startup`,
```cs
services.AddControllersWithViews().AddMyLibrary();
```
Please help on why I'm getting this error and assist on how to solve this?
|
2019/10/13
|
['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']
|
netstandard2.1 to netcoreapp3.0
MvcJsonOptions -> MvcNewtonsoftJsonOptions
```
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//MVC
services.AddControllersWithViews(options =>
{
}).AddNewtonsoftJson();
services.PostConfigure<MvcNewtonsoftJsonOptions>(options => {
options.SerializerSettings.ContractResolver = new MyCustomContractResolver()
{
NamingStrategy = new CamelCaseNamingStrategy()
};
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
}
```
|
The problem is most likely with the incompatible nuget packages for .net core 3.1 above. Take a look at your packages and eventually upgrade to compatible version of core 3.1. That should really fix the issue I had one with Automapper and others had with Swagger.
If you are using AutoMapper you should upgrade to 7.0.0
See <https://medium.com/@nicky2983/how-to-using-automapper-on-asp-net-core-3-0-via-dependencyinjection-a5d25bd33e5b>
|
58,362,757 |
I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error:
>
> 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from
> assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0
>
>
>
I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library.
Here is my library `.csproj`,
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
```
Here is my `ServiceExtensions` class from my library,
```cs
public static class ServiceExtensions
{
public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.ConfigureOptions<ConfigureLibraryOptions>();
return builder;
}
}
```
Here is my `ConfigureLibraryOptions` class,
```cs
public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
public void Configure(MvcOptions options)
{
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
}
}
```
Here is the `ConfigureServices` from `Startup`,
```cs
services.AddControllersWithViews().AddMyLibrary();
```
Please help on why I'm getting this error and assist on how to solve this?
|
2019/10/13
|
['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']
|
I'm not sure if this solves OP's problem, but this error also occurs when you use Swashbuckle 4 in .Net Core 3. The solution is to use Swashbuckle 5.
(use command `install-package Swashbuckle.AspNetCore`) to have in .csproj
```
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
```
Then you'll need to upgrade it in Startup.cs. Generally that involves prefixing classes that don't compile with `OpenApi` e.g.
`options.SwaggerDoc("v1" new Info ...`
becomes
`options.SwaggerDoc("v1", OpenApiInfo`
Also `OpenApiSecurityScheme` becomes `ApiKeyScheme`
See also docs at <https://github.com/domaindrivendev/Swashbuckle.AspNetCore>
|
netstandard2.1 to netcoreapp3.0
MvcJsonOptions -> MvcNewtonsoftJsonOptions
```
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//MVC
services.AddControllersWithViews(options =>
{
}).AddNewtonsoftJson();
services.PostConfigure<MvcNewtonsoftJsonOptions>(options => {
options.SerializerSettings.ContractResolver = new MyCustomContractResolver()
{
NamingStrategy = new CamelCaseNamingStrategy()
};
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
}
```
|
58,362,757 |
I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error:
>
> 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from
> assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0
>
>
>
I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library.
Here is my library `.csproj`,
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
```
Here is my `ServiceExtensions` class from my library,
```cs
public static class ServiceExtensions
{
public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.ConfigureOptions<ConfigureLibraryOptions>();
return builder;
}
}
```
Here is my `ConfigureLibraryOptions` class,
```cs
public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
public void Configure(MvcOptions options)
{
options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
}
}
```
Here is the `ConfigureServices` from `Startup`,
```cs
services.AddControllersWithViews().AddMyLibrary();
```
Please help on why I'm getting this error and assist on how to solve this?
|
2019/10/13
|
['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']
|
When you config "Swashbuckle.AspNetCore", needed for configuring ApiKeyScheme become to OpenApiSecurityScheme it is changing the scheme from
```
c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description =
"Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
{ "Bearer", Enumerable.Empty<string>() }, });
```
To
```
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description =
"JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
```
|
In my case, the solution was to add `services.AddControllers()` as described under <https://github.com/RicoSuter/NSwag/issues/1961#issuecomment-515631411>.
|
14,796,931 |
Google play reports an exception on some devices (all are "other" and one "LG-E400", so it might be some custom android build)
Exception is:
```
java.lang.IllegalArgumentException
at android.os.StatFs.native_setup(Native Method)
at android.os.StatFs.<init>(StatFs.java:32)
at android.webkit.CacheManager.init(CacheManager.java:199)
at android.webkit.BrowserFrame.<init>(BrowserFrame.java:210)
at android.webkit.WebViewCore.initialize(WebViewCore.java:201)
at android.webkit.WebViewCore.access$500(WebViewCore.java:54)
at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653)
at java.lang.Thread.run(Thread.java:1019)
```
The problem is I can't ignore this axception 'cause it is in separate thread.
Is there any solution for this problem?
Or what can I do with that?
|
2013/02/10
|
['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']
|
Much likely it's a device OS bug. I have much problems with AudioRecord library - it also fails in native init on number of devices like Yusu, Micromax, Alcatel and other low range devices. They are all shown as "other" in GooglePlay reports. Also I encoundered that some [Cyanogenmod](http://www.cyanogenmod.org/) ROMs have a bug in AudioRecord - on my HTC One V it worked okay until I flashed CM10.
One good way to know exact device model, logcats, mem and other info about what happens on these devices is to use some advanced crash report tool, as [ACRA](http://acra.ch/)
After I get report that something is definitely wrong on device with it's manufacturer's firmware, I blacklist it on GooglePlay.
|
Looks like some firmware had problem with StatFs
I had similar issue with Samsung Galaxy Stratosphere™ II (Verizon) SCH-I415, Android:4.1.2
When I call:
```
StatFs statFs = null;
statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
```
I got exception:
```
java.lang.IllegalArgumentException
at android.os.StatFs.native_setup(Native Method)
at android.os.StatFs.<init>(StatFs.java:32)
```
|
14,796,931 |
Google play reports an exception on some devices (all are "other" and one "LG-E400", so it might be some custom android build)
Exception is:
```
java.lang.IllegalArgumentException
at android.os.StatFs.native_setup(Native Method)
at android.os.StatFs.<init>(StatFs.java:32)
at android.webkit.CacheManager.init(CacheManager.java:199)
at android.webkit.BrowserFrame.<init>(BrowserFrame.java:210)
at android.webkit.WebViewCore.initialize(WebViewCore.java:201)
at android.webkit.WebViewCore.access$500(WebViewCore.java:54)
at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653)
at java.lang.Thread.run(Thread.java:1019)
```
The problem is I can't ignore this axception 'cause it is in separate thread.
Is there any solution for this problem?
Or what can I do with that?
|
2013/02/10
|
['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']
|
Much likely it's a device OS bug. I have much problems with AudioRecord library - it also fails in native init on number of devices like Yusu, Micromax, Alcatel and other low range devices. They are all shown as "other" in GooglePlay reports. Also I encoundered that some [Cyanogenmod](http://www.cyanogenmod.org/) ROMs have a bug in AudioRecord - on my HTC One V it worked okay until I flashed CM10.
One good way to know exact device model, logcats, mem and other info about what happens on these devices is to use some advanced crash report tool, as [ACRA](http://acra.ch/)
After I get report that something is definitely wrong on device with it's manufacturer's firmware, I blacklist it on GooglePlay.
|
I have got similar issue and my log was looking like
```
03-14 13:41:55.715: E/PayPalService(14037): Risk component failed to initialize, threw null
03-14 13:41:56.295: E/(14037): statfs /storage/sdcard0 failed, errno: 13
03-14 13:41:56.365: E/AndroidRuntime(14037): FATAL EXCEPTION: Thread-1219
03-14 13:41:56.365: E/AndroidRuntime(14037): java.lang.IllegalArgumentException
03-14 13:41:56.365: E/AndroidRuntime(14037): at android.os.StatFs.native_setup(Native Method)
03-14 13:41:56.365: E/AndroidRuntime(14037): at android.os.StatFs.<init>(StatFs.java:32)
```
I found this issue related to sd card by looking the first two lines .Then I checked device setting and found I had checked their a option **apps must have permission to read sd card** and the app I was installing was not having **READ SD CARD** permission in manifest. So possibly these things are related and possible solutions for me were either put permission in manifest or to unchecke that option .Hope it will help in further research.
|
14,796,931 |
Google play reports an exception on some devices (all are "other" and one "LG-E400", so it might be some custom android build)
Exception is:
```
java.lang.IllegalArgumentException
at android.os.StatFs.native_setup(Native Method)
at android.os.StatFs.<init>(StatFs.java:32)
at android.webkit.CacheManager.init(CacheManager.java:199)
at android.webkit.BrowserFrame.<init>(BrowserFrame.java:210)
at android.webkit.WebViewCore.initialize(WebViewCore.java:201)
at android.webkit.WebViewCore.access$500(WebViewCore.java:54)
at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653)
at java.lang.Thread.run(Thread.java:1019)
```
The problem is I can't ignore this axception 'cause it is in separate thread.
Is there any solution for this problem?
Or what can I do with that?
|
2013/02/10
|
['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']
|
Much likely it's a device OS bug. I have much problems with AudioRecord library - it also fails in native init on number of devices like Yusu, Micromax, Alcatel and other low range devices. They are all shown as "other" in GooglePlay reports. Also I encoundered that some [Cyanogenmod](http://www.cyanogenmod.org/) ROMs have a bug in AudioRecord - on my HTC One V it worked okay until I flashed CM10.
One good way to know exact device model, logcats, mem and other info about what happens on these devices is to use some advanced crash report tool, as [ACRA](http://acra.ch/)
After I get report that something is definitely wrong on device with it's manufacturer's firmware, I blacklist it on GooglePlay.
|
Path which you are providing in Statfs constructor does not exists
```
String path = "path to some directory";
StatFs statFs = null;
statFs = new StatFs(path);
```
and you must have external storage permission in manifest file
|
14,796,931 |
Google play reports an exception on some devices (all are "other" and one "LG-E400", so it might be some custom android build)
Exception is:
```
java.lang.IllegalArgumentException
at android.os.StatFs.native_setup(Native Method)
at android.os.StatFs.<init>(StatFs.java:32)
at android.webkit.CacheManager.init(CacheManager.java:199)
at android.webkit.BrowserFrame.<init>(BrowserFrame.java:210)
at android.webkit.WebViewCore.initialize(WebViewCore.java:201)
at android.webkit.WebViewCore.access$500(WebViewCore.java:54)
at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653)
at java.lang.Thread.run(Thread.java:1019)
```
The problem is I can't ignore this axception 'cause it is in separate thread.
Is there any solution for this problem?
Or what can I do with that?
|
2013/02/10
|
['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']
|
Much likely it's a device OS bug. I have much problems with AudioRecord library - it also fails in native init on number of devices like Yusu, Micromax, Alcatel and other low range devices. They are all shown as "other" in GooglePlay reports. Also I encoundered that some [Cyanogenmod](http://www.cyanogenmod.org/) ROMs have a bug in AudioRecord - on my HTC One V it worked okay until I flashed CM10.
One good way to know exact device model, logcats, mem and other info about what happens on these devices is to use some advanced crash report tool, as [ACRA](http://acra.ch/)
After I get report that something is definitely wrong on device with it's manufacturer's firmware, I blacklist it on GooglePlay.
|
Starting with Lollipop, Android placed rather extreme restrictions on accessing external SD cards. You can use:
```
StatFs stat;
try {
stat = new StatFs(path);
} catch (IllegalArgumentException e) {
// Handle the failure gracefully or just throw(e)
}
```
to work-around the error.
For my application, I just skip unavailable directories, essentially limiting the user to the internal storage. Not an ideal solution, but a limited application that doesn't crash is better than one which does.
|
14,796,931 |
Google play reports an exception on some devices (all are "other" and one "LG-E400", so it might be some custom android build)
Exception is:
```
java.lang.IllegalArgumentException
at android.os.StatFs.native_setup(Native Method)
at android.os.StatFs.<init>(StatFs.java:32)
at android.webkit.CacheManager.init(CacheManager.java:199)
at android.webkit.BrowserFrame.<init>(BrowserFrame.java:210)
at android.webkit.WebViewCore.initialize(WebViewCore.java:201)
at android.webkit.WebViewCore.access$500(WebViewCore.java:54)
at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653)
at java.lang.Thread.run(Thread.java:1019)
```
The problem is I can't ignore this axception 'cause it is in separate thread.
Is there any solution for this problem?
Or what can I do with that?
|
2013/02/10
|
['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']
|
Path which you are providing in Statfs constructor does not exists
```
String path = "path to some directory";
StatFs statFs = null;
statFs = new StatFs(path);
```
and you must have external storage permission in manifest file
|
Looks like some firmware had problem with StatFs
I had similar issue with Samsung Galaxy Stratosphere™ II (Verizon) SCH-I415, Android:4.1.2
When I call:
```
StatFs statFs = null;
statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
```
I got exception:
```
java.lang.IllegalArgumentException
at android.os.StatFs.native_setup(Native Method)
at android.os.StatFs.<init>(StatFs.java:32)
```
|
14,796,931 |
Google play reports an exception on some devices (all are "other" and one "LG-E400", so it might be some custom android build)
Exception is:
```
java.lang.IllegalArgumentException
at android.os.StatFs.native_setup(Native Method)
at android.os.StatFs.<init>(StatFs.java:32)
at android.webkit.CacheManager.init(CacheManager.java:199)
at android.webkit.BrowserFrame.<init>(BrowserFrame.java:210)
at android.webkit.WebViewCore.initialize(WebViewCore.java:201)
at android.webkit.WebViewCore.access$500(WebViewCore.java:54)
at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653)
at java.lang.Thread.run(Thread.java:1019)
```
The problem is I can't ignore this axception 'cause it is in separate thread.
Is there any solution for this problem?
Or what can I do with that?
|
2013/02/10
|
['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']
|
Path which you are providing in Statfs constructor does not exists
```
String path = "path to some directory";
StatFs statFs = null;
statFs = new StatFs(path);
```
and you must have external storage permission in manifest file
|
I have got similar issue and my log was looking like
```
03-14 13:41:55.715: E/PayPalService(14037): Risk component failed to initialize, threw null
03-14 13:41:56.295: E/(14037): statfs /storage/sdcard0 failed, errno: 13
03-14 13:41:56.365: E/AndroidRuntime(14037): FATAL EXCEPTION: Thread-1219
03-14 13:41:56.365: E/AndroidRuntime(14037): java.lang.IllegalArgumentException
03-14 13:41:56.365: E/AndroidRuntime(14037): at android.os.StatFs.native_setup(Native Method)
03-14 13:41:56.365: E/AndroidRuntime(14037): at android.os.StatFs.<init>(StatFs.java:32)
```
I found this issue related to sd card by looking the first two lines .Then I checked device setting and found I had checked their a option **apps must have permission to read sd card** and the app I was installing was not having **READ SD CARD** permission in manifest. So possibly these things are related and possible solutions for me were either put permission in manifest or to unchecke that option .Hope it will help in further research.
|
14,796,931 |
Google play reports an exception on some devices (all are "other" and one "LG-E400", so it might be some custom android build)
Exception is:
```
java.lang.IllegalArgumentException
at android.os.StatFs.native_setup(Native Method)
at android.os.StatFs.<init>(StatFs.java:32)
at android.webkit.CacheManager.init(CacheManager.java:199)
at android.webkit.BrowserFrame.<init>(BrowserFrame.java:210)
at android.webkit.WebViewCore.initialize(WebViewCore.java:201)
at android.webkit.WebViewCore.access$500(WebViewCore.java:54)
at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653)
at java.lang.Thread.run(Thread.java:1019)
```
The problem is I can't ignore this axception 'cause it is in separate thread.
Is there any solution for this problem?
Or what can I do with that?
|
2013/02/10
|
['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']
|
Path which you are providing in Statfs constructor does not exists
```
String path = "path to some directory";
StatFs statFs = null;
statFs = new StatFs(path);
```
and you must have external storage permission in manifest file
|
Starting with Lollipop, Android placed rather extreme restrictions on accessing external SD cards. You can use:
```
StatFs stat;
try {
stat = new StatFs(path);
} catch (IllegalArgumentException e) {
// Handle the failure gracefully or just throw(e)
}
```
to work-around the error.
For my application, I just skip unavailable directories, essentially limiting the user to the internal storage. Not an ideal solution, but a limited application that doesn't crash is better than one which does.
|
26,098,194 |
So, I export `PNotify` from bower to the `js` folder. I use `requirejs` to include my libraries
**HTML**
```
<script data-main="assets/js/app" type="text/javascript" src="assets/js/lib/require.js"></script>
```
My architecture is like this :
```
js
--- app.js
--- lib
------ pnotify.core.js
------ pnotify.desktop.js
------ pnotify.buttons.js
------ pnotify.callbacks.js
------ pnotify.confirm.js
------ pnotify.history.js
------ pnotify.nonblock.js
------ pnotify.reference.js
------ jquery.js
------ ...
```
I add the primary module which is pnotify.core
**APP.JS**
```
requirejs.config({
base: '/assets/js',
paths: {
'jQuery': 'lib/jquery.min',
'underscore': 'lib/underscore-min',
'Backbone': 'lib/backbone',
'Modernizr' : 'lib/modernizr',
'PNotify' : 'lib/pnotify.core',
'LoginView' : 'views/login'
},
shim: {
'jQuery': {
exports: '$'
},
'underscore': {
exports: '_'
},
'Backbone': {
exports: 'Backbone'
},
'Modernizr': {
exports: 'Modernizr'
},
'LoginView': {
exports: 'LoginView'
},
'PNotify': {
exports: 'PNotify'
}
}
});
```
PNotify is loaded in my page. Normally, PNotify works with requirejs : <https://github.com/sciactive/pnotify#using-pnotify-with-requirejs>
I don't know how can I import all modules, maybe concat these modules in one file pnotify.min.js?
Here, when I call the `PNotify` object under the `requirejs.config`
```
define(['jQuery', 'underscore', 'Backbone', 'Modernizr', 'LoginView', 'PNotify'], function ($, _, Backbone, Modernizr, LoginView, PNotify) {
$(document).ready(function(){
new PNotify({
title: 'Desktop Notice',
text: 'If you\'ve given me permission, I\'ll appear as a desktop notification. If you haven\'t, I\'ll still appear as a regular PNotify notice.'
});
});
});
```
I have this error : `Uncaught TypeError: undefined is not a function` on the line "new PNotify"...
Do you have some ideas?
|
2014/09/29
|
['https://Stackoverflow.com/questions/26098194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2798726/']
|
>
> When they detect AMD/RequireJS, PNotify core defines the named module
> "**pnotify**", and PNotify's modules each define names like
> "pnotify.module". The following example shows the use of the nonblock
> and desktop modules with RequireJS.
>
>
>
So my error is here
```
requirejs.config({
base: '/assets/js',
paths: {
'jQuery': 'lib/jquery.min',
'underscore': 'lib/underscore-min',
'Backbone': 'lib/backbone',
'Modernizr' : 'lib/modernizr',
'PNotify' : 'lib/pnotify.core',
^_____ 'replace by pnotify'
'LoginView' : 'views/login'
},
...
```
|
Compile All the modules into one minified file.
These Settings work for me in Require.js
```
paths: {
'pnotify': 'lib/pnotify.min',
'pnotify.nonblock': 'lib/pnotify.min',
'pnotify.desktop': 'lib/pnotify.min,
'jquery' : 'lib/jquery'
}
define(['jquery', 'pnotify','pnotify.nonblock', 'pnotify.desktop', function($, pnotify){
new PNotify({
title: 'Desktop Notice',
text: 'If you\'ve given me permission, I\'ll appear as a desktop notification. If you haven\'t, I\'ll still appear as a regular PNotify notice.',
desktop: {
desktop: true
},
nonblock: {
nonblock: true
}
});
});
```
|
2,159,414 |
There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball?
Solution: $\frac{397}{1000}$
How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot?
Solution: $\frac{35}{74}$
My idea:
I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example.
I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$
|
2017/02/24
|
['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']
|
$$\log\_2 x +\log\_4 x = 2$$
$$\frac{1}{\log\_ x2} +\frac{1}{\log\_ x4} = 2$$
$$\frac{1}{\log\_ x2} +\frac{1}{2\log\_ x2} = 2$$
$$\frac{3}{2\log\_ x2} = 2$$
$$\frac{1}{\log\_ x2} =\frac{4}{3}$$
$$\log\_ 2x =\frac{4}{3}$$
$$x=2^{4/3}$$
|
we write $$\frac{\ln(x)}{\ln(2)}+\frac{\ln(x)}{2\ln(2)}=2$$ multiplying by $$2\ln(2)$$ we obtain
$$2\ln(x)+\ln(x)=4\ln(2)$$thus we get
$$\ln(x)=\frac{4}{3}\ln(2)$$ can you finish this?
|
2,159,414 |
There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball?
Solution: $\frac{397}{1000}$
How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot?
Solution: $\frac{35}{74}$
My idea:
I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example.
I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$
|
2017/02/24
|
['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']
|
If we apply 4^ to both sides, we get
$$4^{\log\_2(x)+\log\_4(x)}=16$$
$$4^{\log\_2(x)}4^{\log\_4(x)}=16$$
Since $4=2^2$, this reduces to
$$2^{2\log\_2(x)}4^{\log\_4(x)}=16$$
$$x^2\cdot x=16$$
$$x^3=16$$
$$x=\sqrt[3]{16}\approx2.7$$
|
Use the definition of $\log\_a x=\ln(x)/\ln(a)$ and multiply $\log\_2 x + \log\_4 x = 2$ by $2 \ln 2$ to get $3\ln x=2$, hence $x=\exp(2/3)$.
|
2,159,414 |
There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball?
Solution: $\frac{397}{1000}$
How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot?
Solution: $\frac{35}{74}$
My idea:
I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example.
I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$
|
2017/02/24
|
['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']
|
If we apply 4^ to both sides, we get
$$4^{\log\_2(x)+\log\_4(x)}=16$$
$$4^{\log\_2(x)}4^{\log\_4(x)}=16$$
Since $4=2^2$, this reduces to
$$2^{2\log\_2(x)}4^{\log\_4(x)}=16$$
$$x^2\cdot x=16$$
$$x^3=16$$
$$x=\sqrt[3]{16}\approx2.7$$
|
You would need to change the base of one of the $log$.
For example $\log\_4 x = \frac{\log\_2 x}{log\_2 4} = \frac{\log\_2 x}{2}$
$$
2 = \log\_2 x + \log\_4 x = \frac{3}{2} \log\_2x \implies x = 2^{4/3} = \sqrt[3]{16}
$$
|
2,159,414 |
There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball?
Solution: $\frac{397}{1000}$
How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot?
Solution: $\frac{35}{74}$
My idea:
I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example.
I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$
|
2017/02/24
|
['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']
|
$$\log\_2 x +\log\_4 x = 2$$
$$\frac{1}{\log\_ x2} +\frac{1}{\log\_ x4} = 2$$
$$\frac{1}{\log\_ x2} +\frac{1}{2\log\_ x2} = 2$$
$$\frac{3}{2\log\_ x2} = 2$$
$$\frac{1}{\log\_ x2} =\frac{4}{3}$$
$$\log\_ 2x =\frac{4}{3}$$
$$x=2^{4/3}$$
|
You would need to change the base of one of the $log$.
For example $\log\_4 x = \frac{\log\_2 x}{log\_2 4} = \frac{\log\_2 x}{2}$
$$
2 = \log\_2 x + \log\_4 x = \frac{3}{2} \log\_2x \implies x = 2^{4/3} = \sqrt[3]{16}
$$
|
2,159,414 |
There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball?
Solution: $\frac{397}{1000}$
How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot?
Solution: $\frac{35}{74}$
My idea:
I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example.
I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$
|
2017/02/24
|
['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']
|
$$\log\_2 x +\log\_4 x = 2$$
$$\frac{1}{\log\_ x2} +\frac{1}{\log\_ x4} = 2$$
$$\frac{1}{\log\_ x2} +\frac{1}{2\log\_ x2} = 2$$
$$\frac{3}{2\log\_ x2} = 2$$
$$\frac{1}{\log\_ x2} =\frac{4}{3}$$
$$\log\_ 2x =\frac{4}{3}$$
$$x=2^{4/3}$$
|
If we apply 4^ to both sides, we get
$$4^{\log\_2(x)+\log\_4(x)}=16$$
$$4^{\log\_2(x)}4^{\log\_4(x)}=16$$
Since $4=2^2$, this reduces to
$$2^{2\log\_2(x)}4^{\log\_4(x)}=16$$
$$x^2\cdot x=16$$
$$x^3=16$$
$$x=\sqrt[3]{16}\approx2.7$$
|
2,159,414 |
There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball?
Solution: $\frac{397}{1000}$
How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot?
Solution: $\frac{35}{74}$
My idea:
I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example.
I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$
|
2017/02/24
|
['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']
|
we write $$\frac{\ln(x)}{\ln(2)}+\frac{\ln(x)}{2\ln(2)}=2$$ multiplying by $$2\ln(2)$$ we obtain
$$2\ln(x)+\ln(x)=4\ln(2)$$thus we get
$$\ln(x)=\frac{4}{3}\ln(2)$$ can you finish this?
|
Here is another way to think. First note that $4$ is a power of $2$
Let $\log\_4x=k\iff 4^k=x$
Now $4^k=x \implies (2^2)^k=x \implies 2^{2k}=x\iff\log\_2x=2k\implies \frac{1}{2}\log\_2{x}=\log\_4{x}$
We now have $$\log\_2x+\frac{1}{2}\log\_2x=2\\\frac{3}{2}\log\_2x=2\\\log\_2x^{3/2}=2\iff2^2=x^{3/2}\implies x=16^{1/3}$$
I added this because it reinforces the bonds between logs and powers.
|
2,159,414 |
There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball?
Solution: $\frac{397}{1000}$
How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot?
Solution: $\frac{35}{74}$
My idea:
I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example.
I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$
|
2017/02/24
|
['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']
|
$$\log\_2 x +\log\_4 x = 2$$
$$\frac{1}{\log\_ x2} +\frac{1}{\log\_ x4} = 2$$
$$\frac{1}{\log\_ x2} +\frac{1}{2\log\_ x2} = 2$$
$$\frac{3}{2\log\_ x2} = 2$$
$$\frac{1}{\log\_ x2} =\frac{4}{3}$$
$$\log\_ 2x =\frac{4}{3}$$
$$x=2^{4/3}$$
|
Here is another way to think. First note that $4$ is a power of $2$
Let $\log\_4x=k\iff 4^k=x$
Now $4^k=x \implies (2^2)^k=x \implies 2^{2k}=x\iff\log\_2x=2k\implies \frac{1}{2}\log\_2{x}=\log\_4{x}$
We now have $$\log\_2x+\frac{1}{2}\log\_2x=2\\\frac{3}{2}\log\_2x=2\\\log\_2x^{3/2}=2\iff2^2=x^{3/2}\implies x=16^{1/3}$$
I added this because it reinforces the bonds between logs and powers.
|
2,159,414 |
There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball?
Solution: $\frac{397}{1000}$
How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot?
Solution: $\frac{35}{74}$
My idea:
I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example.
I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$
|
2017/02/24
|
['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']
|
$$\log\_2 x +\log\_4 x = 2$$
$$\frac{1}{\log\_ x2} +\frac{1}{\log\_ x4} = 2$$
$$\frac{1}{\log\_ x2} +\frac{1}{2\log\_ x2} = 2$$
$$\frac{3}{2\log\_ x2} = 2$$
$$\frac{1}{\log\_ x2} =\frac{4}{3}$$
$$\log\_ 2x =\frac{4}{3}$$
$$x=2^{4/3}$$
|
Use the definition of $\log\_a x=\ln(x)/\ln(a)$ and multiply $\log\_2 x + \log\_4 x = 2$ by $2 \ln 2$ to get $3\ln x=2$, hence $x=\exp(2/3)$.
|
2,159,414 |
There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball?
Solution: $\frac{397}{1000}$
How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot?
Solution: $\frac{35}{74}$
My idea:
I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example.
I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$
|
2017/02/24
|
['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']
|
we write $$\frac{\ln(x)}{\ln(2)}+\frac{\ln(x)}{2\ln(2)}=2$$ multiplying by $$2\ln(2)$$ we obtain
$$2\ln(x)+\ln(x)=4\ln(2)$$thus we get
$$\ln(x)=\frac{4}{3}\ln(2)$$ can you finish this?
|
Use the definition of $\log\_a x=\ln(x)/\ln(a)$ and multiply $\log\_2 x + \log\_4 x = 2$ by $2 \ln 2$ to get $3\ln x=2$, hence $x=\exp(2/3)$.
|
2,159,414 |
There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball?
Solution: $\frac{397}{1000}$
How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot?
Solution: $\frac{35}{74}$
My idea:
I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example.
I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$
|
2017/02/24
|
['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']
|
we write $$\frac{\ln(x)}{\ln(2)}+\frac{\ln(x)}{2\ln(2)}=2$$ multiplying by $$2\ln(2)$$ we obtain
$$2\ln(x)+\ln(x)=4\ln(2)$$thus we get
$$\ln(x)=\frac{4}{3}\ln(2)$$ can you finish this?
|
You would need to change the base of one of the $log$.
For example $\log\_4 x = \frac{\log\_2 x}{log\_2 4} = \frac{\log\_2 x}{2}$
$$
2 = \log\_2 x + \log\_4 x = \frac{3}{2} \log\_2x \implies x = 2^{4/3} = \sqrt[3]{16}
$$
|
33,084,866 |
A bit stuck on getting hash equals to data attribute. so if url.com/#house-2 then it will trigger a click for test 2. How do you get it via jquery? <http://jsfiddle.net/ar1bd4bj/7/>
```
<ul class="list">
<li>
<a data-loc="house" href="#">test</a>
</li>
<li>
<a data-loc="house-2" href="#">test2</a>
</li>
<li>
<a data-loc="house-3" href="#">test3</a>
</li>
</ul>
<script>
$(window).load(function() {
if (window.location.hash === data('loc')) {
setTimeout(function() {
$('this').trigger('click');
},1);
}
});
</script>
```
|
2015/10/12
|
['https://Stackoverflow.com/questions/33084866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4939773/']
|
You can use [`attribute equals`](http://api.jquery.com/attribute-equals-selector/) to select your target `a` element and trigger `.click()` like this;
```
$('.list a[data-loc="' + window.location.hash.replace('#', '') + '"]').trigger('click');
```
If your HTML contains those `data-loc` attributes, this will work. But it won't work if data was added via jQuery `.data()` function.
|
You can use `filter()` to find the required element by the `data-loc` attribute. Try this:
```
var fragment = window.location.hash;
if (fragment) {
fragment = fragment.substr(1);
$('.list a').filter(function() {
return $(this).data('loc') == fragment;
}).click();
}
```
|
38,241,941 |
I'm exploring how jhipster manipulates data. I have found `$http.get()` in `getProfileInfo` method in `ProfileService` Service whitch interacting restful `api` :
```
function getProfileInfo() {
if (!angular.isDefined(dataPromise)) {
dataPromise = $http.get('api/profile-info').then(function(result) {
if (result.data.activeProfiles) {
var response = {};
response.activeProfiles = result.data.activeProfiles;
response.ribbonEnv = result.data.ribbonEnv;
response.inProduction = result.data.activeProfiles.indexOf("prod") !== -1;
response.swaggerDisabled = result.data.activeProfiles.indexOf("no-swagger") !== -1;
return response;
}
});
}
return dataPromise;
}
```
and some where i have found `$resouce()` manipulating `GET` method. for example in `BankAccount` factory :
```
var resourceUrl = 'api/bank-accounts/:id';
```
I searched for when to use `$http` and when to use `$resource` and i found this :
[AngularJS $http and $resource](https://stackoverflow.com/questions/13181406/angularjs-http-and-resource)
why `hipster` is not following `consistent` way of interacting API and manipulating data!!?
so `jhipster`, when to use `$http` and when to use `$resource` in services??
|
2016/07/07
|
['https://Stackoverflow.com/questions/38241941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1438055/']
|
We use `$resource` when requesting a RESTful endpoint, for example for an entity. `$resource` provides basic REST operations easily whereas `$http` is more specific.
For profile we only need to GET `/profile-infos` so it's useless to use `$resource` because we'll never need to call POST or DELETE on that URL.
|
$http will fetch you the entire page or complete set of data from a given URL whereas $resouce uses http but will help you to fetch a specific object or set of data.
$resource is fast and we use it when we need to increase the speed of our transaction.
$http is used when we are concerned with the time.
|
21,440,326 |
I am starting to work with classes in Python, and am learning how to create functions within classes. Does anyone have any tips on this sample class & function that I am testing out?
```
class test:
def __init__(self):
self.a = None
self.b = None
self.c = None
def prod(self):
return self.a * self.b
trial = test
trial.a = 4
trial.b = 5
print trial.prod
```
Ideally the result would be to see the number 20.
|
2014/01/29
|
['https://Stackoverflow.com/questions/21440326', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3250333/']
|
You need to:
1. Create an instance of `test`.
2. Invoke the `prod` method of that instance.
Both of these can be accomplished by adding `()` after their names:
```
trial = test()
trial.a = 4
trial.b = 5
print trial.prod()
```
Below is a demonstration:
```
>>> class test:
... def __init__(self):
... self.a = None
... self.b = None
... self.c = None
... def prod(self):
... return self.a * self.b
...
>>> trial = test()
>>> trial.a = 4
>>> trial.b = 5
>>> print trial.prod()
20
>>>
```
---
Without the parenthesis, this line:
```
trial = test
```
is simply assigning the variable `trial` to class `test` itself, not an instance of it. Moreover, this line:
```
print trial.prod
```
is just printing the string representation of `test.prod`, not the value returned by invoking it.
---
Here is a reference on [Python classes and OOP](http://docs.python.org/2/tutorial/classes.html).
|
Ideally you could also pass in the values to a, b, c as parameters to your object's constructor:
```
class test:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def prod(self):
return self.a * self.b
```
Then, constructing and calling the function would look like this:
```
trial = test(4, 5, None)
print trial.prod()
```
|
39,963,386 |
I have a database with multiple dates for the same unique ID. I am trying to find the first (min) and last (max) date for each unique ID. I want the result to be:
Unique ID, first Date, last date, field1, field2,field3
```
Select max(date_Executed) as Last_Date,
(select unique_ID, MIN(date_Executed)as First_Date
from Table_X
group by unique_ID, Field1, field2,field3
)
from Table_X
where unique_ID = unique_ID
group by unique_ID, Field1, field2,field3
order by unique_ID,First_Permit_Date
```
The error message I get is:
>
> Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
> Msg 207, Level 16, State 1, Line 19
> Invalid column name 'First\_Permit\_Date'.
>
>
>
I’m new to SQL…
Thanks for your help-
|
2016/10/10
|
['https://Stackoverflow.com/questions/39963386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6950328/']
|
why not a simple select with group by
```
Select max(date_Executed) as Last_Date, MIN(date_Executed) as First_Date
from Table_X
group by unique_ID, Field1, field2,field3
order by unique_ID,First_Permit_Date
```
You can use more then one aggregation function ina select .. (with the same group by clause)
|
Shouldn't it just be something like this?
I have no further insight in your tables, but the second 'select' statement seems to cause the error.
```
SELECT unique_ID, min(date_Executed) as First_Date, max(date_Executed) as Last_Date, field1, field2, field3
FROM Table_X
GROUP BY unique_ID, Field1, field2, field3
order by unique_ID, First_Permit_Date
```
|
39,764,678 |
I've been battling for days now to get data to save for my nested form. I basically want to be able to store a users reason for cancelling a project, along with the last stage of the project before it was cancelled. But I just can't seem to get the actions `cancel`, `cancel_save`, and `cancel_params` to play nicely!
**Controller**
```
before_action :correct_user, only: [:show, :edit, :update, :destroy, :cancel, :cancel_save]
...
def cancel
@project.build_project_close_reason
end
def cancel_save
@project.build_project_close_reason(cancel_params)
@project.update(project_status_id: 10)
redirect_to root_path, notice: 'Project has been successfully cancelled.'
end
private
def correct_user
@user = current_user
@project = current_user.projects.find_by(id: params[:id])
end
redirect_to user_projects_path, notice: "You are not authorised to view this project" if @project.nil?
end
def cancel_params
params.require(:project).permit(project_close_reason_attributes: [:comment]).merge(project_close_reason_attributes: [project_id: @project.id, last_status_id: @project.project_status_id ])
end
```
**Models**
```
class Project < ApplicationRecord
belongs_to :user
has_one :project_close_reason
accepts_nested_attributes_for :project_close_reason #adding this seemed to make no difference?
end
class ProjectCloseReason < ApplicationRecord
belongs_to :project
end
class User < ApplicationRecord
... # All standard devise stuff
has_many :projects
end
```
**Nested form in the view**
```
<%= form_for([@user, @project], url: {action: "cancel_save"}, method: :post) do |f| %>
<%= fields_for :project_close_reason do |pcr| %>
<div class="field entry_box">
<%= pcr.label "Why are you cancelling this project? (This helps us improve!)" %>
<%= pcr.text_area :comment, class: "form-control entry_field_text" %>
</div>
<% end %>
<div class="actions center space_big">
<%= f.submit "Cancel Project", class: "btn btn-lg btn-warning" %>
</div>
<% end %>
```
**Routes**
```
devise_for :users
devise_for :admins
resources :users do
resources :projects do
get "cancel", :on => :member
post "cancel" => 'projects#cancel_save', :on => :member
end
end
```
This is the error I get when I try and submit the form:
`ActionController::ParameterMissing in ProjectsController#cancel_save
param is missing or the value is empty: project`. It references the `cancel_params` action
Thanks for any help!
UPDATE
Here is the log when I call `cancel_save`
```
Started POST "/users/2/projects/10/cancel" for ::1 at 2016-09-29 10:03:44 +0200
Processing by ProjectsController#cancel_save as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"h6K+VFyjW/dV189YOePWZm+Pmjey50xAMQIJb+c3dzpEaMv8Ckh3jQGOWfVdlfVH/FxolbB45fXvTO0cdplhkg==", "project_close_reason"=>{"comment"=>"b"}, "commit"=>"Cancel Project", "user_id"=>"2", "id"=>"10"}
User Load (11.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 2], ["LIMIT", 1]]
Project Load (0.7ms) SELECT "projects".* FROM "projects" WHERE "projects"."user_id" = $1 AND "projects"."id" = $2 LIMIT $3 [["user_id", 2], ["id", 10], ["LIMIT", 1]]
ProjectCloseReason Load (0.2ms) SELECT "project_close_reasons".* FROM "project_close_reasons" WHERE "project_close_reasons"."project_id" = $1 LIMIT $2 [["project_id", 10], ["LIMIT", 1]]
Completed 400 Bad Request in 22ms (ActiveRecord: 12.1ms)
ActionController::ParameterMissing (param is missing or the value is empty: project):
```
|
2016/09/29
|
['https://Stackoverflow.com/questions/39764678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6748657/']
|
You need [`concat`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html):
```
print (pd.concat([df1[['Type','Breed','Behaviour']],
df2[['Type','Breed','Behaviour']]], ignore_index=True))
Type Breed Behaviour
0 Golden Big Fun
1 Corgi Small Crazy
2 Bulldog Medium Strong
3 Pug Small Sleepy
4 German Shepard Big Cool
5 Puddle Small Aggressive
```
More general is use [`intersection`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html) for columns of both `DataFrames`:
```
cols = df1.columns.intersection(df2.columns)
print (cols)
Index(['Type', 'Breed', 'Behaviour'], dtype='object')
print (pd.concat([df1[cols], df2[cols]], ignore_index=True))
Type Breed Behaviour
0 Golden Big Fun
1 Corgi Small Crazy
2 Bulldog Medium Strong
3 Pug Small Sleepy
4 German Shepard Big Cool
5 Puddle Small Aggressive
```
More general if `df1` and `df2` have no `NaN` values use [`dropna`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html) for removing columns with `NaN`:
```
print (pd.concat([df1 ,df2], ignore_index=True))
Bark Sound Behaviour Breed Common Color Other Color Type
0 NaN Fun Big Gold White Golden
1 NaN Crazy Small Brown White Corgi
2 NaN Strong Medium Black Grey Bulldog
3 Ak Sleepy Small NaN NaN Pug
4 Woof Cool Big NaN NaN German Shepard
5 Ek Aggressive Small NaN NaN Puddle
print (pd.concat([df1 ,df2], ignore_index=True).dropna(1))
Behaviour Breed Type
0 Fun Big Golden
1 Crazy Small Corgi
2 Strong Medium Bulldog
3 Sleepy Small Pug
4 Cool Big German Shepard
5 Aggressive Small Puddle
```
|
using `join` dropping columns that don't overlap
```
df1.T.join(df2.T, lsuffix='_').dropna().T.reset_index(drop=True)
```
[](https://i.stack.imgur.com/wb6AL.png)
|
29,260,425 |
I have a postgres database with a large number of time series metrics
Various operators are interested in different information and I want to provide an interface where they can chart the data, make comparisons and optionally export data as a csv.
The two solutions I have come across so far are, [graphite](https://github.com/graphite-project) and [grafana](http://grafana.org/), but both these solutions tie you down to storage engines and none support postgres.
What I am looking for is an interface similar to grafana, but which allows me to hook up any backend I want. Are there any tools out there, similar to grafana, which allow you to hook up any backend you want (or even just postgres).
Note that the data I am collecting is highly sensitive, and is required by other areas of the application and so is not suitable for storing in graphite.
The other alternative I see would be to setup a trigger on the postgres DB to feed data into graphite as it arrives, but again, not ideal.
|
2015/03/25
|
['https://Stackoverflow.com/questions/29260425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/527749/']
|
You may want to replace Graphite's storage backend with postgresql. [Here](http://obfuscurity.com/2013/12/Migrating-Graphite-from-SQLite-to-PostgreSQL) is a good primer.
|
**2018 update**: Grafana now supports PostgreSQL ([link](https://grafana.com/plugins/postgres)).
---
>
> What I am looking for is an interface similar to grafana, but which allows me to hook up any backend I want
>
>
>
Thats possible with grafana . Check this [guide](http://docs.grafana.org/plugins/developing/datasources/) which shows how to create a datasource plugin for a datasource thats currently not supported.
|
28,342,139 |
I have angularjs directive with template which consists of two tags - input and the empty list. What I want is to watch input value of the first input tag. The `$watch()` method is called once when directive is initialised but that's it. Any change of input value is silent. What do I miss?
here is my [plunk](http://plnkr.co/edit/kAeuOUxovP8AaAyepNlZ?p=preview)
and here is the code:
```
.directive('drpdwn', function(){
var ref = new Firebase("https://sagavera.firebaseio.com/countries");
function link(scope, element, attrs){
function watched(){
element[0].firstChild.value = 'bumba'; //this gets called once
return element[0].firstChild.value;
}
scope.$watch(watched, function(val){
console.log("watched", val)
}, true);
}
return {
scope:{
searchString: '='
},
link: link,
templateUrl:'drpdwn.html'
}
})
```
Edit:
if I call `$interval()` within link function it works as expected. is this intentional behaviour?
|
2015/02/05
|
['https://Stackoverflow.com/questions/28342139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2232045/']
|
It doesn't get called because there is never a digest triggered on the scope.
Try this instead, using ng-model:
<http://plnkr.co/edit/qMP5NDEMYjXfYsoJtneL?p=preview>
```
function link(scope, element, attrs){
scope.searchString = 'bumba';
scope.$watch('searchString', function(val){
console.log("watched", val)
val = val.toLowerCase();
val = val.replace(/ */g,'');
var regex = /^[a-z]*$/g;
if (regex.test(val)) {
scope.searchString = val;
// TODO something....
}
}, true);
```
Template:
```
<input class="form-control" ng-model="searchString" id="focusedInput" type="text" placeholder="something" />
<div></div>
```
|
You are setting the the value you want in the watcher function.
```
function watched(){
element[0].firstChild.value = 'bumba'; //this gets called once
return element[0].firstChild.value;
}
```
is essentially the same return value as
```
function watched() {
return 'bumba';
}
```
So the watcher will always return the same value.
If you want to initialize the value. Do it outside of the watcher:
```
element[0].firstChild.value = 'bumba'; //this gets called once
function watched(){
return element[0].firstChild.value;
}
```
|
57,995,932 |
I want to build a JSON object from an array returned from http request
my actual array look like:
```
[{
Description: "Product"
IsInstanciable: false
IsMasked: false
Name: "ProductBase"
Subclasses: [{
Description: "Product2"
IsInstanciable: false
IsMasked: false
Name: "ProductBase2",
Count: 5,
Subclasses:[]
},
{
Description: "Product3"
IsInstanciable: false
IsMasked: false
Name: "ProductBase3",
Count: 4,
Subclasses:[],
}]
},
{
Description: "Product4"
IsInstanciable: false
IsMasked: false
Name: "ProductBase4",
Count: '...',
Subclasses: [...]
}
```
I want to create a JSON object recursively from the array above. It will look like this:
```
[
{
name: 'Product',
Count: 9,
children: [
{name: 'Product2'},
{name: 'Product3'},
]
}, {
name: 'Product4',
children: [
{
name: '...',
Count: 'Sum of Count in all children by level'
children: [
{name: '...'},
{name: '...'},
]
}
]
},
];
```
Here is my recursively function in typescript but it doesn't work as expected. How can I fix this?
```js
recursive(data, stack: TreeNode[]) {
let elt: TreeNode = {name:'', children: []}
if(data.Subclasses.length > 0) {
elt.name = data.Description;
data.Subclasses.forEach(element => {
elt.children.push({name: element.Description});
this.recursive(element, stack);
});
}else {
elt.name = data.Description;
}
stack.push(elt);
}
```
|
2019/09/18
|
['https://Stackoverflow.com/questions/57995932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/874800/']
|
You can use the map function together with the recursive function like this:
```
function MapObject(object) {
if(!object || object.length < 0) return [];
return object.map(obj => { return {
name: obj.Description,
children: MapObject(obj.Subclasses)
}});
}
```
Follows a full work example:
```js
var example = [{
Description: "Product",
IsInstanciable: false,
IsMasked: false,
Name: "ProductBase",
Subclasses: [{
Description: "Product2",
IsInstanciable: false,
IsMasked: false,
Name: "ProductBase2",
Subclasses:[]
},
{
Description: "Product3",
IsInstanciable: false,
IsMasked: false,
Name: "ProductBase3",
Subclasses:[]
}]
},
{
Description: "Product4",
IsInstanciable: false,
IsMasked: false,
Name: "ProductBase4"
}]
function MapObject(object) {
if(!object || object.length < 0) return [];
return object.map(obj => { return {
name: obj.Description,
children: MapObject(obj.Subclasses)
}});
}
console.log(MapObject(example));
```
|
I would break this down into a few separate functions with clear responsibilities:
```js
const sum = (ns) =>
ns .reduce ((a, b) => a + Number (b), 0)
const getCount = (product) =>
(product .Count || 0) + sum ((product .Subclasses || []) .map (getCount))
const extract = (product) =>
({
name: product .Name,
count: getCount (product),
children: product .Subclasses .map (extract)
})
const extractAll = (products) =>
products .map (extract)
const products = [{"Description": "Product", "IsInstanciable": false, "IsMasked": false, "Name": "ProductBase", "Subclasses": [{"Count": 5, "Description": "Product2", "IsInstanciable": false, "IsMasked": false, "Name": "ProductBase2", "Subclasses": []}, {"Count": 4, "Description": "Product3", "IsInstanciable": false, "IsMasked": false, "Name": "ProductBase3", "Subclasses": []}]}, {"Count": 3, "Description": "Product4", "IsInstanciable": false, "IsMasked": false, "Name": "ProductBase4", "Subclasses": []}]
console .log (
extractAll (products)
)
```
(Note that I changed the case of the output `count` property. It just seemed more consistent with `name` and `children`.)
We recur through the object to get its `Count` property, and we recur separately to get the rest of the object. While there might be a way to combine these, I would expect that the code would be significantly more complex.
Note that I assumed that all `Count` properties are actually numeric, although your example above includes a string. If you do have values like `"3"`, then `getCount` will need to be a little more sophisticated.
|
1,115,762 |
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
|
2009/07/12
|
['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']
|
They are used mainly to obtain multiple return values from a method call. Personally, I tend to not use them. If I want multiple return values from a method then I'll create a small class to hold them.
ref and out are used when you want something back from the method in that parameter. As I recall, they both actually compile down to the same IL, but C# puts in place some extra stuff so you have to be specific.
Here are some examples:
```
static void Main(string[] args)
{
string myString;
MyMethod0(myString);
Console.WriteLine(myString);
Console.ReadLine();
}
public static void MyMethod0(string param1)
{
param1 = "Hello";
}
```
The above won't compile because myString is never initialised. If myString is initialised to string.Empty then the output of the program will be a empty line because all MyMethod0 does is assign a new string to a local reference to param1.
```
static void Main(string[] args)
{
string myString;
MyMethod1(out myString);
Console.WriteLine(myString);
Console.ReadLine();
}
public static void MyMethod1(out string param1)
{
param1 = "Hello";
}
```
myString is not initialised in the Main method, yet, the program outputs "Hello". This is because the myString reference in the Main method is being updated from MyMethod1. MyMethod1 does not expect param1 to already contain anything, so it can be left uninitialised. However, the method should be assigning something.
```
static void Main(string[] args)
{
string myString;
MyMethod2(ref myString);
Console.WriteLine(myString);
Console.ReadLine();
}
public static void MyMethod2(ref string param1)
{
param1 = "Hello";
}
```
This, again, will not compile. This is because ref demands that myString in the Main method is initialised to something first. But, if the Main method is changed so that myString is initialised to string.Empty then the code will compile and the output will be Hello.
So, the difference is out can be used with an uninitialised object, ref must be passed an initialised object. And if you pass an object without either the reference to it cannot be replaced.
Just to be clear: If the object being passed is a reference type already then the method can update the object and the updates are reflected in the calling code, however the reference to the object cannot be changed. So if I write code like this:
```
static void Main(string[] args)
{
string myString = "Hello";
MyMethod0(myString);
Console.WriteLine(myString);
Console.ReadLine();
}
public static void MyMethod0(string param1)
{
param1 = "World";
}
```
The output from the program will be Hello, and not World because the method only changed its local copy of the reference, not the reference that was passed in.
I hope this makes sense. My general rule of thumb is simply not to use them. I feel it is a throw back to pre-OO days. (But, that's just my opinion)
|
Very simple really. You use exactly the same keyword that the parameter was originally declared with in the method. If it was declared as `out`, you have to use `out`. If it was declared as `ref`, you have to use `ref`.
|
1,115,762 |
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
|
2009/07/12
|
['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']
|
(this is supplemental to the existing answers - a few extra considerations)
There is another scenario for using `ref` with C#, more commonly seen in things like XNA... Normally, when you pass a value-type (`struct`) around, it gets cloned. This uses stack-space and a few CPU cycles, and has the side-effect that any modifications to the `struct` in the invoked method are lost.
(aside: normally `struct`s should be immutable, but mutable structs isn't uncommon in XNA)
To get around this, it is quite common to see `ref` in such programs.
But in **most** programs (i.e. where you are using `class`es as the default), you can *normally* just pass the reference "by value" (i.e. no `ref`/`out`).
---
Another **very** common use-case of `out` is the `Try*` pattern, for example:
```
string s = Console.ReadLine();
int i;
if(int.TryParse(s, out i)) {
Console.WriteLine("You entered a valid int: " + i);
}
```
Or similarly, [`TryGetValue`](http://msdn.microsoft.com/en-us/library/zkw5c9ak(VS.85).aspx) on a dictionary.
This could use a tuple instead, but it is such a common pattern that it is reasonably understood, even by people who struggle with too much `ref`/`out`.
|
ref is to be avoided (I beleive there is an fx-cop rule for this also) however use ref when the object that is reference may itself changed. If you see the 'ref' keyword you know that the underlying object may no longer be referenced by the same variable after the method is called.
|
1,115,762 |
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
|
2009/07/12
|
['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']
|
In addition to Colin's detailed answer, you could also use out parameters to return multiple values from one method call. See for example the method below which returns 3 values.
```
static void AssignSomeValues(out int first, out bool second, out string third)
{
first = 12 + 12;
second = false;
third = "Output parameters are okay";
}
```
You could use it like so
```
static void Main(string[] args) {
int i;
string s;
bool b;
AssignSomeValues(out i, out b, out s);
Console.WriteLine("Int value: {0}", i);
Console.WriteLine("Bool value: {0}", b);
Console.WriteLine("String value: {0}", s);
//wait for enter key to terminate program
Console.ReadLine(); }
```
Just make sure that you assign a valid value to each out parameter to avoid getting an error.
|
Try to avoid using ref. Out is okay, because you know what will happen, the old value will be gone and a new value will be in your variable even if the function failed. However, just by looking at the function you have no idea what will happen to a ref parameter. It may be the same, modified, or an entirely new object.
Whenever I see ref, I get nervous.
|
1,115,762 |
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
|
2009/07/12
|
['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']
|
(this is supplemental to the existing answers - a few extra considerations)
There is another scenario for using `ref` with C#, more commonly seen in things like XNA... Normally, when you pass a value-type (`struct`) around, it gets cloned. This uses stack-space and a few CPU cycles, and has the side-effect that any modifications to the `struct` in the invoked method are lost.
(aside: normally `struct`s should be immutable, but mutable structs isn't uncommon in XNA)
To get around this, it is quite common to see `ref` in such programs.
But in **most** programs (i.e. where you are using `class`es as the default), you can *normally* just pass the reference "by value" (i.e. no `ref`/`out`).
---
Another **very** common use-case of `out` is the `Try*` pattern, for example:
```
string s = Console.ReadLine();
int i;
if(int.TryParse(s, out i)) {
Console.WriteLine("You entered a valid int: " + i);
}
```
Or similarly, [`TryGetValue`](http://msdn.microsoft.com/en-us/library/zkw5c9ak(VS.85).aspx) on a dictionary.
This could use a tuple instead, but it is such a common pattern that it is reasonably understood, even by people who struggle with too much `ref`/`out`.
|
Very simple really. You use exactly the same keyword that the parameter was originally declared with in the method. If it was declared as `out`, you have to use `out`. If it was declared as `ref`, you have to use `ref`.
|
1,115,762 |
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
|
2009/07/12
|
['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']
|
(this is supplemental to the existing answers - a few extra considerations)
There is another scenario for using `ref` with C#, more commonly seen in things like XNA... Normally, when you pass a value-type (`struct`) around, it gets cloned. This uses stack-space and a few CPU cycles, and has the side-effect that any modifications to the `struct` in the invoked method are lost.
(aside: normally `struct`s should be immutable, but mutable structs isn't uncommon in XNA)
To get around this, it is quite common to see `ref` in such programs.
But in **most** programs (i.e. where you are using `class`es as the default), you can *normally* just pass the reference "by value" (i.e. no `ref`/`out`).
---
Another **very** common use-case of `out` is the `Try*` pattern, for example:
```
string s = Console.ReadLine();
int i;
if(int.TryParse(s, out i)) {
Console.WriteLine("You entered a valid int: " + i);
}
```
Or similarly, [`TryGetValue`](http://msdn.microsoft.com/en-us/library/zkw5c9ak(VS.85).aspx) on a dictionary.
This could use a tuple instead, but it is such a common pattern that it is reasonably understood, even by people who struggle with too much `ref`/`out`.
|
Try to avoid using ref. Out is okay, because you know what will happen, the old value will be gone and a new value will be in your variable even if the function failed. However, just by looking at the function you have no idea what will happen to a ref parameter. It may be the same, modified, or an entirely new object.
Whenever I see ref, I get nervous.
|
1,115,762 |
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
|
2009/07/12
|
['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']
|
They are used mainly to obtain multiple return values from a method call. Personally, I tend to not use them. If I want multiple return values from a method then I'll create a small class to hold them.
ref and out are used when you want something back from the method in that parameter. As I recall, they both actually compile down to the same IL, but C# puts in place some extra stuff so you have to be specific.
Here are some examples:
```
static void Main(string[] args)
{
string myString;
MyMethod0(myString);
Console.WriteLine(myString);
Console.ReadLine();
}
public static void MyMethod0(string param1)
{
param1 = "Hello";
}
```
The above won't compile because myString is never initialised. If myString is initialised to string.Empty then the output of the program will be a empty line because all MyMethod0 does is assign a new string to a local reference to param1.
```
static void Main(string[] args)
{
string myString;
MyMethod1(out myString);
Console.WriteLine(myString);
Console.ReadLine();
}
public static void MyMethod1(out string param1)
{
param1 = "Hello";
}
```
myString is not initialised in the Main method, yet, the program outputs "Hello". This is because the myString reference in the Main method is being updated from MyMethod1. MyMethod1 does not expect param1 to already contain anything, so it can be left uninitialised. However, the method should be assigning something.
```
static void Main(string[] args)
{
string myString;
MyMethod2(ref myString);
Console.WriteLine(myString);
Console.ReadLine();
}
public static void MyMethod2(ref string param1)
{
param1 = "Hello";
}
```
This, again, will not compile. This is because ref demands that myString in the Main method is initialised to something first. But, if the Main method is changed so that myString is initialised to string.Empty then the code will compile and the output will be Hello.
So, the difference is out can be used with an uninitialised object, ref must be passed an initialised object. And if you pass an object without either the reference to it cannot be replaced.
Just to be clear: If the object being passed is a reference type already then the method can update the object and the updates are reflected in the calling code, however the reference to the object cannot be changed. So if I write code like this:
```
static void Main(string[] args)
{
string myString = "Hello";
MyMethod0(myString);
Console.WriteLine(myString);
Console.ReadLine();
}
public static void MyMethod0(string param1)
{
param1 = "World";
}
```
The output from the program will be Hello, and not World because the method only changed its local copy of the reference, not the reference that was passed in.
I hope this makes sense. My general rule of thumb is simply not to use them. I feel it is a throw back to pre-OO days. (But, that's just my opinion)
|
Try to avoid using ref. Out is okay, because you know what will happen, the old value will be gone and a new value will be in your variable even if the function failed. However, just by looking at the function you have no idea what will happen to a ref parameter. It may be the same, modified, or an entirely new object.
Whenever I see ref, I get nervous.
|
1,115,762 |
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
|
2009/07/12
|
['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']
|
(this is supplemental to the existing answers - a few extra considerations)
There is another scenario for using `ref` with C#, more commonly seen in things like XNA... Normally, when you pass a value-type (`struct`) around, it gets cloned. This uses stack-space and a few CPU cycles, and has the side-effect that any modifications to the `struct` in the invoked method are lost.
(aside: normally `struct`s should be immutable, but mutable structs isn't uncommon in XNA)
To get around this, it is quite common to see `ref` in such programs.
But in **most** programs (i.e. where you are using `class`es as the default), you can *normally* just pass the reference "by value" (i.e. no `ref`/`out`).
---
Another **very** common use-case of `out` is the `Try*` pattern, for example:
```
string s = Console.ReadLine();
int i;
if(int.TryParse(s, out i)) {
Console.WriteLine("You entered a valid int: " + i);
}
```
Or similarly, [`TryGetValue`](http://msdn.microsoft.com/en-us/library/zkw5c9ak(VS.85).aspx) on a dictionary.
This could use a tuple instead, but it is such a common pattern that it is reasonably understood, even by people who struggle with too much `ref`/`out`.
|
In addition to Colin's detailed answer, you could also use out parameters to return multiple values from one method call. See for example the method below which returns 3 values.
```
static void AssignSomeValues(out int first, out bool second, out string third)
{
first = 12 + 12;
second = false;
third = "Output parameters are okay";
}
```
You could use it like so
```
static void Main(string[] args) {
int i;
string s;
bool b;
AssignSomeValues(out i, out b, out s);
Console.WriteLine("Int value: {0}", i);
Console.WriteLine("Bool value: {0}", b);
Console.WriteLine("String value: {0}", s);
//wait for enter key to terminate program
Console.ReadLine(); }
```
Just make sure that you assign a valid value to each out parameter to avoid getting an error.
|
1,115,762 |
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
|
2009/07/12
|
['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']
|
In general, you should avoid using ref and out, if possible.
That being said, use ref when the method *might need* to modify the value. Use out when the method *always should* assign something to the value.
The difference between ref and out, is that when using out, the compiler enforces the rule, that you need to assign something to the out paramter before returning. When using ref, you must assign a value to the variable *before* using it as a ref parameter.
Obviously, the above applies, when you are writing your own methods. If you need to call methods that was declared with the ref or out modifiers on their parameters, you should use the same modifier before your parameter, when calling the method.
Also remember, that C# passes reference types (classes) by reference (as in, the reference is passed by value). So if you provide some method with a reference type as a parameter, the method can modify the data of the object; even without ref or out. But it cannot modify the reference itself (as in, it cannot modify which object is being referenced).
|
ref is to be avoided (I beleive there is an fx-cop rule for this also) however use ref when the object that is reference may itself changed. If you see the 'ref' keyword you know that the underlying object may no longer be referenced by the same variable after the method is called.
|
1,115,762 |
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
|
2009/07/12
|
['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']
|
In general, you should avoid using ref and out, if possible.
That being said, use ref when the method *might need* to modify the value. Use out when the method *always should* assign something to the value.
The difference between ref and out, is that when using out, the compiler enforces the rule, that you need to assign something to the out paramter before returning. When using ref, you must assign a value to the variable *before* using it as a ref parameter.
Obviously, the above applies, when you are writing your own methods. If you need to call methods that was declared with the ref or out modifiers on their parameters, you should use the same modifier before your parameter, when calling the method.
Also remember, that C# passes reference types (classes) by reference (as in, the reference is passed by value). So if you provide some method with a reference type as a parameter, the method can modify the data of the object; even without ref or out. But it cannot modify the reference itself (as in, it cannot modify which object is being referenced).
|
Try to avoid using ref. Out is okay, because you know what will happen, the old value will be gone and a new value will be in your variable even if the function failed. However, just by looking at the function you have no idea what will happen to a ref parameter. It may be the same, modified, or an entirely new object.
Whenever I see ref, I get nervous.
|
1,115,762 |
In c# , when sending a parameter to a method, when should we use "ref" and when "out" and when without any of them?
|
2009/07/12
|
['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']
|
In addition to Colin's detailed answer, you could also use out parameters to return multiple values from one method call. See for example the method below which returns 3 values.
```
static void AssignSomeValues(out int first, out bool second, out string third)
{
first = 12 + 12;
second = false;
third = "Output parameters are okay";
}
```
You could use it like so
```
static void Main(string[] args) {
int i;
string s;
bool b;
AssignSomeValues(out i, out b, out s);
Console.WriteLine("Int value: {0}", i);
Console.WriteLine("Bool value: {0}", b);
Console.WriteLine("String value: {0}", s);
//wait for enter key to terminate program
Console.ReadLine(); }
```
Just make sure that you assign a valid value to each out parameter to avoid getting an error.
|
ref is to be avoided (I beleive there is an fx-cop rule for this also) however use ref when the object that is reference may itself changed. If you see the 'ref' keyword you know that the underlying object may no longer be referenced by the same variable after the method is called.
|
32,283 |
I want to compute the total scene bounding box, so I can fit the scene in rendered image automatically. I have found `bound_box`. But why are there so many values
```
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
<bpy_float[3], Object.bound_box>
```
There should be 6 values (x\_min,y\_min,z\_min) and (x\_max,y\_max,z\_max)
|
2015/06/11
|
['https://blender.stackexchange.com/questions/32283', 'https://blender.stackexchange.com', 'https://blender.stackexchange.com/users/3258/']
|
You will get 8 values only,
```
>>> obj = bpy.context.active_object
>>> obj.bound_box
bpy.data.objects['Cube'].bound_box
>>> [v[:] for v in obj.bound_box]
[(-1.0, -1.0, -1.0),
(-1.0, -1.0, 1.0),
(-1.0, 1.0, 1.0),
(-1.0, 1.0, -1.0),
(1.0, -1.0, -1.0),
(1.0, -1.0, 1.0),
(1.0, 1.0, 1.0),
(1.0, 1.0, -1.0)]
```

for Suzanne it would be:

Here's some code [I wrote about 2 years ago](http://blenderscripting.blogspot.nl/2013/06/named-tuples-replacement.html) to get x.min, x.max, etc., and distance over the axis for *x, y and z*. With instructions how to use it. (I have this tucked away in a module so I just import the function when I need it)
```
import bpy
from mathutils import Vector
def bounds(obj, local=False):
local_coords = obj.bound_box[:]
om = obj.matrix_world
if not local:
# Use @ for multiplication instead of * in Blender2.8+. Source: https://blender.stackexchange.com/a/129474/138679
worldify = lambda p: om * Vector(p[:])
coords = [worldify(p).to_tuple() for p in local_coords]
else:
coords = [p[:] for p in local_coords]
rotated = zip(*coords[::-1])
push_axis = []
for (axis, _list) in zip('xyz', rotated):
info = lambda: None
info.max = max(_list)
info.min = min(_list)
info.distance = info.max - info.min
push_axis.append(info)
import collections
originals = dict(zip(['x', 'y', 'z'], push_axis))
o_details = collections.namedtuple('object_details', 'x y z')
return o_details(**originals)
"""
obj = bpy.context.object
object_details = bounds(obj)
a = object_details.z.max
b = object_details.z.min
c = object_details.z.distance
print(a, b, c)
"""
```
|
Each object that has a `bound_box` property will return *8* values that represent the bounding information. The 8 values describe the corners of the bounding box itself.
If you have 16 values I presume that is because you have 2 objects in the scene (though it isn't clear from your question what you might have typed in to return all 16 values).
|
8,459 |
It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple.
But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?
|
2013/10/23
|
['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']
|
It's not a *logical truth* that an apple is not an orange, but it's nevertheless *analytic* with respect to the meaning postulate: if predicate P holds uniformly of object a, then for all predicates Q contrary to P, ¬Q(a). For example, if something is uniformly black, then it's not of any color that is contrary to black (say red). Recall that predicates A, B are *contraries* iff they cannot simultaneously be true of an object:
>
> **Definition.** Predicates P and Q are *contraries* =def for all x, either ¬P(x) or ¬Q(x).
>
>
>
Here's how a proof could proceed. We have a meaning postulate, a convention that states that:
>
> **P1.** For all P, x: if P(x), then for all Q: if P and Q are contraries, then ¬Q(x).
>
>
>
Now we begin with the hypothesis that some object a is an A, and that A and O are contraries:
>
> **P2.** A(a)
>
> **P3.** Predicates A and O are contraries
>
>
>
Then we instantiate (P1) with a for x, obtaining:
>
> **P4.** For all P: if P(a), then for all Q: if P and Q are contraries, then ¬Q(a)
>
>
>
We then instantiate (P4) with A for P and O for Q, obtaining:
>
> **P5.** if A(a), then if A and O are contraries, then ¬O(a)
>
>
>
The rest is two applications of modus ponens starting with (P5) and using (P2) and then (P3):
>
> **P6.** if A and O are contraries, then ¬O(a)
>
> **P7.** ¬O(a)
>
>
>
|
As has been pointed out already, if you are using logic to talk about apples and oranges you have already provided some model (say, *a* is an apple and *o* is an orange - formally speaking you've set up a function from constants in your logical language to objects or types or fruit or whatever). So I'm reasonably comfortable that the following proof is no less rigorous than what you've got already: let *P* (a one-place predicate) be assigned the meaning 'needs to be peeled to be eaten'\*. Then *Po* is true and *Pa* is false, so then clearly ¬(*x* = *y*) holds.
\*obviously if you don't peel your oranges feel free to substitute some other predicate that fits
---
To generalise a little, in case the moral of the above isn't clear, we 'prove' that two objects are distinct by providing some property that holds of one but not the other. It's an open question in metaphysics whether distinct objects can share every property (contenders might be the object of 52 cards and the object of the deck, I guess). Within logic, though, if two elements of your domain are distinct but the same predicates hold of them there isn't a way to prove that they are distinct - you could show that rigorously in a quite straightforward way; proof systems for first-order logic use (roughly) the above method for proving inequality.
|
8,459 |
It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple.
But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?
|
2013/10/23
|
['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']
|
In mathematics, an equals sign connects subject and predicate.
The statement, apple=orange, is the same as the statement, an apple is an orange.
In order to determine an apple is an apple, you used the principle of identity. That which is the same is the same.
In order to determine an apple is not an orange, we use the principle of difference. That which is the same is not different, or two different things are not the same.
General reasoning from sense infers that apples are not oranges. However, if we use the power of abstraction, we can take the concept of an apple, its "appleness", and a concept of an orange, its "orangeness". These conceptions are known though general reasoning from sense and are often informed from the rest of society, e.g. academia.
An apple's "appleness" can only belong to apples. An orange's "orangeness" can only belong to oranges. "appleness" contains no "orangeness". Therefore, something containing "orangeness", namely an orange, is never something containing "appleness", namely an apple, i.e. apples are never oranges.
|
As has been pointed out already, if you are using logic to talk about apples and oranges you have already provided some model (say, *a* is an apple and *o* is an orange - formally speaking you've set up a function from constants in your logical language to objects or types or fruit or whatever). So I'm reasonably comfortable that the following proof is no less rigorous than what you've got already: let *P* (a one-place predicate) be assigned the meaning 'needs to be peeled to be eaten'\*. Then *Po* is true and *Pa* is false, so then clearly ¬(*x* = *y*) holds.
\*obviously if you don't peel your oranges feel free to substitute some other predicate that fits
---
To generalise a little, in case the moral of the above isn't clear, we 'prove' that two objects are distinct by providing some property that holds of one but not the other. It's an open question in metaphysics whether distinct objects can share every property (contenders might be the object of 52 cards and the object of the deck, I guess). Within logic, though, if two elements of your domain are distinct but the same predicates hold of them there isn't a way to prove that they are distinct - you could show that rigorously in a quite straightforward way; proof systems for first-order logic use (roughly) the above method for proving inequality.
|
8,459 |
It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple.
But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?
|
2013/10/23
|
['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']
|
In mathematics, an equals sign connects subject and predicate.
The statement, apple=orange, is the same as the statement, an apple is an orange.
In order to determine an apple is an apple, you used the principle of identity. That which is the same is the same.
In order to determine an apple is not an orange, we use the principle of difference. That which is the same is not different, or two different things are not the same.
General reasoning from sense infers that apples are not oranges. However, if we use the power of abstraction, we can take the concept of an apple, its "appleness", and a concept of an orange, its "orangeness". These conceptions are known though general reasoning from sense and are often informed from the rest of society, e.g. academia.
An apple's "appleness" can only belong to apples. An orange's "orangeness" can only belong to oranges. "appleness" contains no "orangeness". Therefore, something containing "orangeness", namely an orange, is never something containing "appleness", namely an apple, i.e. apples are never oranges.
|
the logic used here is mathematical logic . but a mathematical logic is only accepted if there is no way to disprove the given logic i.e to say 2+3 =5 and 3+2 also=5 assures the logic that counting 5 pieces from left or right will always remain same because we cant find any two no's which dont obey this logic .
so if we assume apple as x and orange as y such that we know always x=x and y=y is true(because any experiment cant disprove this .an apple remains an apple forever)
now if somehow apple could change into orange after a few years then x=x would have been wrong and then x=y would hold good
also falsness of only x=x directly assures the validity x=y.
but validity of x=x doesnt directly assures the falsness of x=y
note:apple=apple means apple will never change to anything else (including orange)
and orange=orange means orange will never change to anything else (including apple)
so both the chances are finished and there is no other way by which we can say that apple = orange.if one of the two statements x=x and y=y becomes false then x=y can be true means both x=x and y=y should be true
|
8,459 |
It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple.
But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?
|
2013/10/23
|
['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']
|
What are these "apple" and "orange" that you speak of? In fact, none of the **terms** used in predicate logic have any meaning. The terms need to be **interpreted** according to a **model** or a domain of discourse. See [this SEP entry on Classical Logic](http://plato.stanford.edu/entries/logic-classical/), especially section 4, Semantics, for a whirl-wind tour, or [section 3.2 of the handouts by Voronkov](http://www.voronkov.com/lics_doc.cgi?what=chapter&n=3%E2%80%8E), for a longer explanation.
|
Use *types*:
So that x:Apple, y:Orange
This means that x is an apple, y is an orange.
Then we cannot even compare oranges to apples - they're not of the same type; showing that they *must* be different.
If one had an additional type Fruit from which these descend, then the types Orange and Apple would be comparable; but this would be *additional* type information that is unneccessary to implement and demonstrate the question asked by the OP.
It's also worth noting that in an actually existing type system like Haskell, it would not be legal to construct two types of the same nature and name.
|
8,459 |
It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple.
But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?
|
2013/10/23
|
['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']
|
What are these "apple" and "orange" that you speak of? In fact, none of the **terms** used in predicate logic have any meaning. The terms need to be **interpreted** according to a **model** or a domain of discourse. See [this SEP entry on Classical Logic](http://plato.stanford.edu/entries/logic-classical/), especially section 4, Semantics, for a whirl-wind tour, or [section 3.2 of the handouts by Voronkov](http://www.voronkov.com/lics_doc.cgi?what=chapter&n=3%E2%80%8E), for a longer explanation.
|
It depends on your definition of "apple" and "orange".
Is a human an ape? Most people would say "no", because their definition of 'ape' implicitly excludes humans. (They mostly involve animals hairier than most humans, and less verbose.) But [humans are apes](http://en.wikipedia.org/wiki/Homo) in the sense understood by modern biologists. So without precise definitions, you are unlikely to be able to prove that humans are not apes.
Analogously, oranges are fruit which were introduced only a few hundred years ago to Europe, and this shows in the names given them by different European languages. In particular, in many slavic languages, nordic languages, and also Dutch, the name for "orange" translates into English literally as "Chinese Apple", after the country which they were first imported from.
Clearly in English we distinguish strongly between apples and oranges, but until the mid 1800s we did not distinguish between lemons and limes; so any attempt to prove that a "lemon" was not a "lime" might have proven confusing. And complicating the matter is that technically, lemons, limes, and oranges are all merely cultivars of the same species of tree (you can cross them and get fertile offspring). This is beside the point for the apple/orange distinction, of course, except that it illustrates that distinctions we take for granted now and for practical purposes are both arbitrary (based on which citrus fruit we wish to distinguish from others) and contingent (our sense of what counts as a lime has changed with time).
Another example: how do you prove that Pluto is not a planet? In the year 2000, you couldn't; it was considered a planet. Now, following [the decision by the IAU in 2006](http://en.wikipedia.org/wiki/IAU_definition_of_planet), one would *start from the agreed-upon definition of a planet*, which includes requirements which Pluto does not fulfil.
In short, in order to prove that any A is not a B — *e.g.* where A is an apple, human, lemon, or the planet Pluto, and B is an orange, an ape, a lime, or a planet — definitions of A and B, or at least *some* extralogical information of what these things are, is necessary.
|
8,459 |
It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple.
But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?
|
2013/10/23
|
['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']
|
It's not a *logical truth* that an apple is not an orange, but it's nevertheless *analytic* with respect to the meaning postulate: if predicate P holds uniformly of object a, then for all predicates Q contrary to P, ¬Q(a). For example, if something is uniformly black, then it's not of any color that is contrary to black (say red). Recall that predicates A, B are *contraries* iff they cannot simultaneously be true of an object:
>
> **Definition.** Predicates P and Q are *contraries* =def for all x, either ¬P(x) or ¬Q(x).
>
>
>
Here's how a proof could proceed. We have a meaning postulate, a convention that states that:
>
> **P1.** For all P, x: if P(x), then for all Q: if P and Q are contraries, then ¬Q(x).
>
>
>
Now we begin with the hypothesis that some object a is an A, and that A and O are contraries:
>
> **P2.** A(a)
>
> **P3.** Predicates A and O are contraries
>
>
>
Then we instantiate (P1) with a for x, obtaining:
>
> **P4.** For all P: if P(a), then for all Q: if P and Q are contraries, then ¬Q(a)
>
>
>
We then instantiate (P4) with A for P and O for Q, obtaining:
>
> **P5.** if A(a), then if A and O are contraries, then ¬O(a)
>
>
>
The rest is two applications of modus ponens starting with (P5) and using (P2) and then (P3):
>
> **P6.** if A and O are contraries, then ¬O(a)
>
> **P7.** ¬O(a)
>
>
>
|
It depends on your definition of "apple" and "orange".
Is a human an ape? Most people would say "no", because their definition of 'ape' implicitly excludes humans. (They mostly involve animals hairier than most humans, and less verbose.) But [humans are apes](http://en.wikipedia.org/wiki/Homo) in the sense understood by modern biologists. So without precise definitions, you are unlikely to be able to prove that humans are not apes.
Analogously, oranges are fruit which were introduced only a few hundred years ago to Europe, and this shows in the names given them by different European languages. In particular, in many slavic languages, nordic languages, and also Dutch, the name for "orange" translates into English literally as "Chinese Apple", after the country which they were first imported from.
Clearly in English we distinguish strongly between apples and oranges, but until the mid 1800s we did not distinguish between lemons and limes; so any attempt to prove that a "lemon" was not a "lime" might have proven confusing. And complicating the matter is that technically, lemons, limes, and oranges are all merely cultivars of the same species of tree (you can cross them and get fertile offspring). This is beside the point for the apple/orange distinction, of course, except that it illustrates that distinctions we take for granted now and for practical purposes are both arbitrary (based on which citrus fruit we wish to distinguish from others) and contingent (our sense of what counts as a lime has changed with time).
Another example: how do you prove that Pluto is not a planet? In the year 2000, you couldn't; it was considered a planet. Now, following [the decision by the IAU in 2006](http://en.wikipedia.org/wiki/IAU_definition_of_planet), one would *start from the agreed-upon definition of a planet*, which includes requirements which Pluto does not fulfil.
In short, in order to prove that any A is not a B — *e.g.* where A is an apple, human, lemon, or the planet Pluto, and B is an orange, an ape, a lime, or a planet — definitions of A and B, or at least *some* extralogical information of what these things are, is necessary.
|
8,459 |
It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple.
But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?
|
2013/10/23
|
['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']
|
It depends on your definition of "apple" and "orange".
Is a human an ape? Most people would say "no", because their definition of 'ape' implicitly excludes humans. (They mostly involve animals hairier than most humans, and less verbose.) But [humans are apes](http://en.wikipedia.org/wiki/Homo) in the sense understood by modern biologists. So without precise definitions, you are unlikely to be able to prove that humans are not apes.
Analogously, oranges are fruit which were introduced only a few hundred years ago to Europe, and this shows in the names given them by different European languages. In particular, in many slavic languages, nordic languages, and also Dutch, the name for "orange" translates into English literally as "Chinese Apple", after the country which they were first imported from.
Clearly in English we distinguish strongly between apples and oranges, but until the mid 1800s we did not distinguish between lemons and limes; so any attempt to prove that a "lemon" was not a "lime" might have proven confusing. And complicating the matter is that technically, lemons, limes, and oranges are all merely cultivars of the same species of tree (you can cross them and get fertile offspring). This is beside the point for the apple/orange distinction, of course, except that it illustrates that distinctions we take for granted now and for practical purposes are both arbitrary (based on which citrus fruit we wish to distinguish from others) and contingent (our sense of what counts as a lime has changed with time).
Another example: how do you prove that Pluto is not a planet? In the year 2000, you couldn't; it was considered a planet. Now, following [the decision by the IAU in 2006](http://en.wikipedia.org/wiki/IAU_definition_of_planet), one would *start from the agreed-upon definition of a planet*, which includes requirements which Pluto does not fulfil.
In short, in order to prove that any A is not a B — *e.g.* where A is an apple, human, lemon, or the planet Pluto, and B is an orange, an ape, a lime, or a planet — definitions of A and B, or at least *some* extralogical information of what these things are, is necessary.
|
Use *types*:
So that x:Apple, y:Orange
This means that x is an apple, y is an orange.
Then we cannot even compare oranges to apples - they're not of the same type; showing that they *must* be different.
If one had an additional type Fruit from which these descend, then the types Orange and Apple would be comparable; but this would be *additional* type information that is unneccessary to implement and demonstrate the question asked by the OP.
It's also worth noting that in an actually existing type system like Haskell, it would not be legal to construct two types of the same nature and name.
|
8,459 |
It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple.
But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?
|
2013/10/23
|
['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']
|
It's not a *logical truth* that an apple is not an orange, but it's nevertheless *analytic* with respect to the meaning postulate: if predicate P holds uniformly of object a, then for all predicates Q contrary to P, ¬Q(a). For example, if something is uniformly black, then it's not of any color that is contrary to black (say red). Recall that predicates A, B are *contraries* iff they cannot simultaneously be true of an object:
>
> **Definition.** Predicates P and Q are *contraries* =def for all x, either ¬P(x) or ¬Q(x).
>
>
>
Here's how a proof could proceed. We have a meaning postulate, a convention that states that:
>
> **P1.** For all P, x: if P(x), then for all Q: if P and Q are contraries, then ¬Q(x).
>
>
>
Now we begin with the hypothesis that some object a is an A, and that A and O are contraries:
>
> **P2.** A(a)
>
> **P3.** Predicates A and O are contraries
>
>
>
Then we instantiate (P1) with a for x, obtaining:
>
> **P4.** For all P: if P(a), then for all Q: if P and Q are contraries, then ¬Q(a)
>
>
>
We then instantiate (P4) with A for P and O for Q, obtaining:
>
> **P5.** if A(a), then if A and O are contraries, then ¬O(a)
>
>
>
The rest is two applications of modus ponens starting with (P5) and using (P2) and then (P3):
>
> **P6.** if A and O are contraries, then ¬O(a)
>
> **P7.** ¬O(a)
>
>
>
|
the logic used here is mathematical logic . but a mathematical logic is only accepted if there is no way to disprove the given logic i.e to say 2+3 =5 and 3+2 also=5 assures the logic that counting 5 pieces from left or right will always remain same because we cant find any two no's which dont obey this logic .
so if we assume apple as x and orange as y such that we know always x=x and y=y is true(because any experiment cant disprove this .an apple remains an apple forever)
now if somehow apple could change into orange after a few years then x=x would have been wrong and then x=y would hold good
also falsness of only x=x directly assures the validity x=y.
but validity of x=x doesnt directly assures the falsness of x=y
note:apple=apple means apple will never change to anything else (including orange)
and orange=orange means orange will never change to anything else (including apple)
so both the chances are finished and there is no other way by which we can say that apple = orange.if one of the two statements x=x and y=y becomes false then x=y can be true means both x=x and y=y should be true
|
8,459 |
It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple.
But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?
|
2013/10/23
|
['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']
|
What are these "apple" and "orange" that you speak of? In fact, none of the **terms** used in predicate logic have any meaning. The terms need to be **interpreted** according to a **model** or a domain of discourse. See [this SEP entry on Classical Logic](http://plato.stanford.edu/entries/logic-classical/), especially section 4, Semantics, for a whirl-wind tour, or [section 3.2 of the handouts by Voronkov](http://www.voronkov.com/lics_doc.cgi?what=chapter&n=3%E2%80%8E), for a longer explanation.
|
As has been pointed out already, if you are using logic to talk about apples and oranges you have already provided some model (say, *a* is an apple and *o* is an orange - formally speaking you've set up a function from constants in your logical language to objects or types or fruit or whatever). So I'm reasonably comfortable that the following proof is no less rigorous than what you've got already: let *P* (a one-place predicate) be assigned the meaning 'needs to be peeled to be eaten'\*. Then *Po* is true and *Pa* is false, so then clearly ¬(*x* = *y*) holds.
\*obviously if you don't peel your oranges feel free to substitute some other predicate that fits
---
To generalise a little, in case the moral of the above isn't clear, we 'prove' that two objects are distinct by providing some property that holds of one but not the other. It's an open question in metaphysics whether distinct objects can share every property (contenders might be the object of 52 cards and the object of the deck, I guess). Within logic, though, if two elements of your domain are distinct but the same predicates hold of them there isn't a way to prove that they are distinct - you could show that rigorously in a quite straightforward way; proof systems for first-order logic use (roughly) the above method for proving inequality.
|
8,459 |
It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple.
But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?
|
2013/10/23
|
['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']
|
In mathematics, an equals sign connects subject and predicate.
The statement, apple=orange, is the same as the statement, an apple is an orange.
In order to determine an apple is an apple, you used the principle of identity. That which is the same is the same.
In order to determine an apple is not an orange, we use the principle of difference. That which is the same is not different, or two different things are not the same.
General reasoning from sense infers that apples are not oranges. However, if we use the power of abstraction, we can take the concept of an apple, its "appleness", and a concept of an orange, its "orangeness". These conceptions are known though general reasoning from sense and are often informed from the rest of society, e.g. academia.
An apple's "appleness" can only belong to apples. An orange's "orangeness" can only belong to oranges. "appleness" contains no "orangeness". Therefore, something containing "orangeness", namely an orange, is never something containing "appleness", namely an apple, i.e. apples are never oranges.
|
Use *types*:
So that x:Apple, y:Orange
This means that x is an apple, y is an orange.
Then we cannot even compare oranges to apples - they're not of the same type; showing that they *must* be different.
If one had an additional type Fruit from which these descend, then the types Orange and Apple would be comparable; but this would be *additional* type information that is unneccessary to implement and demonstrate the question asked by the OP.
It's also worth noting that in an actually existing type system like Haskell, it would not be legal to construct two types of the same nature and name.
|
36,437,655 |
I have been trying to create a product using Rest API for Magento Version 2.0.
I am using Postman to test the rest api.
URL : <http://13.91>.***.***/rest/V1/products
I have added the following headers to the request.
Authorization : Bearer \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
Content-Type : application/json
JSON BODY
```
{
"sku":"10090-White-XL",
"store_view_code":"",
"attribute_set_code":"ColorSize",
"product_type":"virtual",
"categories":"Menswear/Tops",
"product_websites":"base",
"name":"10090-White-XL",
"description":"<p>Precise Long-Sleeve Shirt in Black, Denim, or White.</p>",
"short_description":"",
"weight":"",
"product_online":1,
"tax_class_name":"Taxable Goods",
"visibility":"Not Visible Individually",
"price":119,
"special_price":"",
"special_price_from_date":"",
"special_price_to_date":"",
"url_key":"10090-white-xl",
"meta_title":"Precise Long-Sleeve Shirt",
"meta_keywords":"Precise Long-Sleeve Shirt",
"meta_description":"Precise Long-Sleeve Shirt <p>Precise Long-Sleeve Shirt in Black, Denim, or White.</p>",
"base_image":"",
"base_image_label":"",
"small_image":"",
"small_image_label":"",
"thumbnail_image":"",
"thumbnail_image_label":"",
"swatch_image":"",
"swatch_image_label":"",
"created_at":"3/23/16, 2:15 PM",
"updated_at":"3/23/16, 2:15 PM",
"new_from_date":"",
"new_to_date":"",
"display_product_options_in":"Block after Info Column",
"map_price":"",
"msrp_price":"",
"map_enabled":"",
"gift_message_available":"",
"custom_design":"",
"custom_design_from":"",
"custom_design_to":"",
"custom_layout_update":"",
"page_layout":"",
"product_options_container":"",
"msrp_display_actual_price_type":"",
"country_of_manufacture":"",
"additional_attributes":"color=White,size=XL",
"qty":null,
"out_of_stock_qty":0,
"use_config_min_qty":1,
"is_qty_decimal":0,
"allow_backorders":0,
"use_config_backorders":1,
"min_cart_qty":1,
"use_config_min_sale_qty":1,
"max_cart_qty":10000,
"use_config_max_sale_qty":1,
"is_in_stock":0,
"notify_on_stock_below":1,
"use_config_notify_stock_qty":1,
"manage_stock":0,
"use_config_manage_stock":0,
"use_config_qty_increments":1,
"qty_increments":0,
"use_config_enable_qty_inc":0,
"enable_qty_increments":0,
"is_decimal_divided":0,
"website_id":1,
"related_skus":"",
"crosssell_skus":"",
"upsell_skus":"",
"additional_images":"",
"additional_image_labels":"",
"hide_from_product_page":"",
"bundle_price_type":"",
"bundle_sku_type":"",
"bundle_price_view":"",
"bundle_weight_type":"",
"bundle_values":"",
"configurable_variations":"",
"configurable_variation_labels":"",
"associated_skus":""
```
}
The error that I get is `{"message":"%fieldName is a required field.","parameters":{"fieldName":"product"}}`
It will be great if someone could let me know how I could add a product. I have checked all the documents and but could not find an answer.
|
2016/04/05
|
['https://Stackoverflow.com/questions/36437655', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2556858/']
|
I have found the answer to my question. The json structure need to be in this format:
```
{
"product":{
"id": 12345,
"sku": "10090-White-XL",
"name": "10090-White-XL",
"attribute_set_id": 9,
"price": 119,
"status": 1,
"visibility": 1,
"type_id": "virtual",
"created_at": "2016-04-05 23:04:09",
"updated_at": "2016-04-05 23:04:09",
"product_links": [],
"options": [],
"tier_prices": [],
"custom_attributes": [
{
"attribute_code": "description",
"value": "<p>Precise Long-Sleeve Shirt in Black, Denim, or White.</p>"
},
{
"attribute_code": "meta_title",
"value": "Precise Long-Sleeve Shirt"
},
{
"attribute_code": "meta_keyword",
"value": "Precise Long-Sleeve Shirt"
},
{
"attribute_code": "meta_description",
"value": "Precise Long-Sleeve Shirt <p>Precise Long-Sleeve Shirt in Black, Denim, or White.</p>"
},
{
"attribute_code": "color",
"value": "11"
},
{
"attribute_code": "options_container",
"value": "container2"
},
{
"attribute_code": "required_options",
"value": "0"
},
{
"attribute_code": "has_options",
"value": "0"
},
{
"attribute_code": "url_key",
"value": "10090-white-xl"
},
{
"attribute_code": "msrp_display_actual_price_type",
"value": "0"
},
{
"attribute_code": "tax_class_id",
"value": "2"
},
{
"attribute_code": "size",
"value": "8"
}
]
},"saveOptions": true
}
```
The important thing to note is the product tag in the json.The swagger document help to idenity it. Here is the link to it: <http://devdocs.magento.com/swagger/#!/catalogProductRepositoryV1/catalogProductRepositoryV1SavePost>
|
Simple product with custom attributes (ex: remarks).
Just take note of the media\_gallery\_entries. Make sure to supply a valid base64\_encoded\_data image content and mime type.
URL: <http://domain/index.php/rest/V1/products>
METHOD: POST
HEADER:
application/json
Authorization: Bearer
POST DATA / RAW PAYLOAD:
```html
{
"product": {
"sku": "TESTPRD002",
"name": "Women's Running - Pure Boost X Shoes",
"attribute_set_id": 4,
"price": 84,
"status": 1,
"visibility": 4,
"type_id": "simple",
"created_at": "2016-12-16 15:20:55",
"updated_at": "2016-12-16 15:20:23",
"weight": 2.5,
"extension_attributes": {
"stock_item": {
"item_id": 1,
"stock_id": 1,
"qty": 20,
"is_in_stock": true,
"is_qty_decimal": false
}
},
"product_links": [],
"options": [],
"media_gallery_entries": [
{
"media_type": "image",
"label": "Women's Running - Pure Boost X Shoes",
"position": 1,
"disabled": false,
"types": [
"image",
"small_image",
"thumbnail"
],
"content": {
"base64_encoded_data": "<ENCODED IMAGE DATA>",
"type": "image/jpeg",
"name": "TESTPRD002-01.jpg"
}
}
],
"tier_prices": [],
"custom_attributes": [
{
"attribute_code": "description",
"value": "<p>Lightweight and sleek, these women's running shoes are fueled by boost™ energy. The low-profile runners blend an energy-returning boost™ midsole with a STRETCHWEB outsole for a cushioned ride with terrific ground-feel. They feature a breathable mesh upper with a sock-like fit that offers all-around support. With a full boost™ midsole that keeps every stride charged with light, fast energy, the shoe has an upper that hovers over a free-floating arch.</p>"
},
{
"attribute_code": "short_description",
"value": "<p>PURE BOOST X SHOES</p><p>NATURAL RUNNING SHOES WITH ARCH SUPPORT.</p>"
},
{
"attribute_code": "meta_title",
"value": "PURE BOOST X SHOES"
},
{
"attribute_code": "meta_keyword",
"value": "boost X, running, shoes, adidas"
},
{
"attribute_code": "meta_description",
"value": "NATURAL RUNNING SHOES WITH ARCH SUPPORT."
},
{
"attribute_code": "category_ids",
"value": [
"2", "3"
]
},
{
"attribute_code": "url_key",
"value": "womens-running-pure-boost-x-shoes"
},
{
"attribute_code": "tax_class_id",
"value": "1"
},
{
"attribute_code": "remarks",
"value": "Lorem ipsum.."
}
]
},
"saveOptions": true
}
```
|
3,144,190 |
I know that if $ G\_1, G\_2 $ are cyclic groups then $ G\_1 \times G\_2 $ is cyclic if and only if $ |G\_1| $ and $ |G\_2| $ are coprimes. But I have to reponds a similar question in the context of category theory:
show that $ \mathbb{Z}\_n $, $ \mathbb{Z}\_m $ have a product in the category of cyclic groups if and only if $ n, m $ are coprimes.
For the implication $ \leftarrow \ $ I consider that $ n,m $ coprimes $ \rightarrow \mathbb{Z}\_n \times \mathbb{Z}\_m $ is cyclic, so this group is an element of the cateogory. Now we can take the proyection
$$
p\_1 : \mathbb{Z}\_n \times \mathbb{Z}\_m \rightarrow \mathbb{Z}\_n
,\ \ \ \
p\_1(x,y) = x
$$
and
$$
p\_2 : \mathbb{Z}\_n \times \mathbb{Z}\_m \rightarrow \mathbb{Z}\_m
, \ \ \ \
p\_2(x,y) = y
$$
that are homomorphism. Easily I can show that $ \mathbb{Z}\_n \times \mathbb{Z}\_m $ and $ p\_1, p\_2 $ form a product of $ \mathbb{Z}\_n $ and $ \mathbb{Z}\_m $ in the category of cyclic groups.
But I am stuck in the proof of the implication $ \rightarrow $.
|
2019/03/11
|
['https://math.stackexchange.com/questions/3144190', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114670/']
|
This should also follow from a naive count of the number of homomorphisms between cyclic groups: specifically, $$\lvert \operatorname{Hom}(\mathbb{Z}\_a, \mathbb{Z}\_b) \rvert = \gcd(a,b).$$
Suppose $\mathbb{Z}\_p$ is the product of $\mathbb{Z}\_m$ and $\mathbb{Z}\_n$ in the category of cyclic groups. Then it satisfies universal property $$\operatorname{Hom}(\mathbb{Z}\_t, \mathbb{Z}\_p) \cong \operatorname{Hom}(\mathbb{Z}\_t, \mathbb{Z}\_m) \times \operatorname{Hom}(\mathbb{Z}\_t, \mathbb{Z}\_n)$$ for all $t$. Counting both sides, we obtain the relation $$\gcd(t,p) = \gcd(t,m) \cdot \gcd(t,n)$$ for all $t$. In particular, if $t = m$, we get $$\gcd(m,p) = m \cdot \gcd(m,n).$$ The left hand side is at most $m$, but in case $m, n$ are not coprime, $\gcd(m,n) > 1$, and the right hand side is strictly bigger than $m$. This would give a contradiction.
|
I think you can use the fact that every finite abelian group can be written as $(\mathbb{Z}\_{n\_1})^{\oplus m\_1}\oplus\cdots\oplus (\mathbb{Z}\_{n\_i})^{\oplus m\_i}$. So suppose now that $A$ is a categorical product of $\mathbb{Z}\_n$ and $\mathbb{Z}\_m$ in the category of cyclic groups, and let us show that it is also a categorical product in the category of finite abelian groups :
Let $X$ be a finite abelian group, together with two maps $X \to \mathbb{Z}\_m$ and $X\to \mathbb{Z}\_n$. Writing $X = (\mathbb{Z}\_{n\_1})^{\oplus m\_1}\oplus\cdots\oplus (\mathbb{Z}\_{n\_i})^{\oplus m\_i}$, and precomposing by the various inclusions, we get a families of maps $f\_{n\_k}^j : \mathbb{Z}\_{n\_k}\to\mathbb{Z}\_n$ and $g\_{n\_k}^j : \mathbb{Z}\_{n\_k}\to\mathbb{Z}\_m$, for $j\leq m\_k$. We can now use the universal property of the product in the category of cyclic groups for each pair $(f\_{n\_k}^j,g\_{n\_k}^j)$ to get maps $h\_{n\_k}^j : \mathbb{Z}\_{n\_k}\to A$. Now let us this this family of maps for the universal property of the coproduct in the category of finite abelian groups, to get a map $h : X\to A$. You can prove that this map commutes with the initial $f,g$ modulo the projection (this is a trivial diagram, if you have understood the above construction).
So if $A$ is a categorical product in the category of cyclic group, it is also a categorical product in the category of finite abelian groups, and thus it is given by the cartesian product of groups.
This proof presuppose that you already know that $\times$ and $\oplus$ are respectively the product and coproduct in the category of finite abelian groups, but I think these are easier results.
|
46,349,085 |
Trying to get the correct gradient colors to show based on php-time. When I try it, the gradients mismatch (I.E. topcolor from first hour-chunk and bottomcolor from fourth-hour chunk match together).
```
<?php
$time = date("H");
if( $time >= 06 && $time < 12 )
$topcolor = 'black';
$bottomcolor = 'orange';
if( $time >= 12 && $time < 18 )
$topcolor = 'pink';
$bottomcolor = 'purple';
if( $time >= 18 && $time < 24 )
$topcolor = 'yellow';
$bottomcolor = 'blue';
if( $time >= 24 && $time < 6 )
$topcolor = 'red';
$bottomcolor = 'green';
?>
<style>
body {
background: <?php echo $bottomcolor;?>;
background: -webkit-linear-gradient(<?php echo $topcolor;?>, <?php echo $bottomcolor;?>) <?php echo $bottomcolor;?>;
background: -o-linear-gradient(<?php echo $topcolor;?>, <?php echo $bottomcolor;?>) <?php echo $bottomcolor;?>;
background: -moz-linear-gradient(<?php echo $topcolor;?>, <?php echo $bottomcolor;?>) <?php echo $bottomcolor;?>;
background: linear-gradient(<?php echo $topcolor;?>, <?php echo $bottomcolor;?>) <?php echo $bottomcolor;?>;
background-repeat: no-repeat;
}
</style>
```
|
2017/09/21
|
['https://Stackoverflow.com/questions/46349085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8303473/']
|
You need to wrap the statements after each `if` condition in braces:
```
if( $time >= 06 && $time < 12 )
$topcolor = 'black';
$bottomcolor = 'orange';
```
->
```
if( $time >= 06 && $time < 12 ) {
$topcolor = 'black';
$bottomcolor = 'orange';
}
```
If you omit these, then only the first statement will be evaluated. See <http://php.net/manual/en/control-structures.if.php>
The reason the last `$bottomcolor` is taking effect is that all of the assignments to that variable are running regardless of the `$time` value, and the last one is taking precedence.
|
As you can learn from the [documentation](http://php.net/manual/en/control-structures.if.php) an `if` statement looks like:
```
if (expression)
statement
```
And about [statements](http://php.net/manual/en/control-structures.intro.php):
>
> A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well.
>
>
>
According to the new wisdom we just got, your code is the same as this (and the indentation doesn't matter, it is there only for beauty):
```
$time = date("H");
if ($time >= 06 && $time < 12)
$topcolor = 'black';
$bottomcolor = 'orange';
if ($time >= 12 && $time < 18)
$topcolor = 'pink';
$bottomcolor = 'purple';
if ($time >= 18 && $time < 24)
$topcolor = 'yellow';
$bottomcolor = 'blue';
if ($time >= 24 && $time < 6) // <--- this condition is impossible
$topcolor = 'red';
$bottomcolor = 'green';
```
As you can see, no matter the value of `$time` is, the value of `$bottomcolor` is changed to `'orange'` then to `'purple'` and so on and everytime its final value is the one produced by the last assignment (`$bottomcolor = 'green';`).
It is [recommended](http://www.php-fig.org/psr/psr-2/#control-structures) to always use blocks for the statements of [`if`](http://php.net/manual/en/control-structures.if.php), [`else`](http://php.net/manual/en/control-structures.else.php), [`elseif/else`](http://php.net/manual/en/control-structures.elseif.php), [`while`](http://php.net/manual/en/control-structures.while.php), [`do-while`](http://php.net/manual/en/control-structures.do.while.php), [`for`](http://php.net/manual/en/control-structures.for.php) and [`foreach`](http://php.net/manual/en/control-structures.foreach.php) [control structures](http://php.net/manual/en/language.control-structures.php), even when they contain only one statement. This way the code is easier to read and understand by the programmers. It doesn't make any difference for the compiler.
Back to your code, you can simplify the tests by using [`elseif`](http://php.net/manual/en/control-structures.elseif.php) statements:
```
$time = date('H');
if ($time < 6) {
// night
$topcolor = 'red';
$bottomcolor = 'green';
} elseif ($time < 12) {
// morning
$topcolor = 'black';
$bottomcolor = 'orange';
} elseif ($time < 18) {
// afternoon
$topcolor = 'pink';
$bottomcolor = 'purple';
} else {
// evening
$topcolor = 'yellow';
$bottomcolor = 'blue';
}
```
|
51,422,311 |
I have a problem with the layout on the Android Studio. The Editor (XML file) and Emulator (Nexus 10) shows the layout right. But if I run the app on my Huawei Mediaped M5, the layout changes and everything is mixed.
The Emulator and my device have the same Resolution(2560\*1600).



The XML file:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button_fahrzeugsimulation"
android:layout_width="461dp"
android:layout_height="203dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="108dp"
android:layout_marginTop="173dp"
android:background="@android:color/holo_blue_dark"
android:text="Fahrzeugsimulation"
android:textColor="#ffffff"
android:textSize="38sp"
android:textStyle="bold" />
<Button
android:id="@+id/button_uebungen"
android:layout_width="457dp"
android:layout_height="182dp"
android:layout_alignParentBottom="true"
android:layout_alignStart="@+id/button_fahrzeugsimulation"
android:layout_marginBottom="106dp"
android:background="@android:color/holo_blue_dark"
android:text="Übungen"
android:textColor="#ffffff"
android:textSize="38sp"
android:textStyle="bold" />
<Button
android:id="@+id/button_Weiterbildungsangebot"
android:layout_width="wrap_content"
android:layout_height="207dp"
android:layout_alignBottom="@+id/button_fahrzeugsimulation"
android:layout_alignParentEnd="true"
android:layout_marginEnd="107dp"
android:background="@android:color/holo_blue_dark"
android:text="Weiterbildungsangebot"
android:textColor="#ffffff"
android:textSize="38sp"
android:textStyle="bold" />
<Button
android:id="@+id/button_Unterlagen"
android:layout_width="498dp"
android:layout_height="185dp"
android:layout_alignStart="@+id/button_Weiterbildungsangebot"
android:layout_alignTop="@+id/button_uebungen"
android:layout_marginStart="-6dp"
android:layout_marginTop="-2dp"
android:background="@android:color/holo_blue_dark"
android:text="Unterlagen"
android:textColor="#ffffff"
android:textSize="38sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView_eMobility"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="eMobility"
android:textColor="@android:color/holo_blue_dark"
android:textStyle="bold"
android:textSize="64sp" />
<TextView
android:id="@+id/textView_Lab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView_eMobility"
android:layout_toEndOf="@+id/textView_eMobility"
android:text="Lab"
android:textColor="@android:color/holo_red_light"
android:textStyle="bold"
android:textSize="52sp" />
```
|
2018/07/19
|
['https://Stackoverflow.com/questions/51422311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10105210/']
|
I found the problem. So firstly I setup configuration like this and put in the rules collection:
```
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
}
```
After that I was getting error that my path is not working. That is cause my font url paths weren't relative to my root scss file. They were relative to the scss file were they used. Sass/libsass does not provide url rewriting, so all linked assets must be relative to the output. I fixed this using resolve-url-loader.
[sass-loader problems-with-url](https://github.com/webpack-contrib/sass-loader#problems-with-url)
[resolve-url-loader](https://github.com/bholloway/resolve-url-loader)
```
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader',
'resolve-url-loader'
],
},
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'resolve-url-loader',
'sass-loader?sourceMap'
],
}
```
And if you are using vue-loader you need also this:
```
'scss': [
'vue-style-loader',
'css-loader',
'resolve-url-loader',
'sass-loader?sourceMap',
{
```
|
Move your file-loader options to `rules` collection instead of `loaders`, it was deprecated and seems to have been overwritten by `rules` collection.
|
11,859,456 |
To work with Solr, I need my searchbox to be suggesting whenever user type.. with a dropdown menu. How can i get it done? Any existing example?
|
2012/08/08
|
['https://Stackoverflow.com/questions/11859456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775856/']
|
[Here](http://blog.trifork.com/2012/02/15/different-ways-to-make-auto-suggestions-with-solr/) is an article I wrote about different ways to make auto suggestions and how to make the right choice. If you want something even more advanced and flexible there is [this other article](http://www.cominvent.com/2012/01/25/super-flexible-autocomplete-with-solr/), which contains an example as well.
|
Have a look at the Suggester component - <http://wiki.apache.org/solr/Suggester/>
|
11,859,456 |
To work with Solr, I need my searchbox to be suggesting whenever user type.. with a dropdown menu. How can i get it done? Any existing example?
|
2012/08/08
|
['https://Stackoverflow.com/questions/11859456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775856/']
|
Have a look at the Suggester component - <http://wiki.apache.org/solr/Suggester/>
|
There are multiple ways of providing autosuggest capabilities.
*Single term suggestion*
This method looks for the first letter, then the first word in a phrase, a search for “men’s shirts” must begin with “m,” then “men’s,” to bring up “men’s shirts” as a response.
This could be done by using following field type and querying with `my little po*`
```
<fieldType name="suggestion_text" class="solr.TextField" positionIncrementGap="100">
<analyzer>
<tokenizer class="solr.KeywordTokenizerFactory" />
</analyzer>
</fieldType>
```
*Multiterm unordered suggestions*
This autocomplete method recognizes “shirts” as part of the phrase, like “men’s shirts,” and suggests it to the customer along with “women’s shirts,” “work shirts,” and other phrases that contain “men’s.”
This one could be done by using following field type and querying with `my AND little AND po*`
```
<fieldType name="prefix_text" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.StandardTokenizerFactory" />
</analyzer>
</fieldType>
```
*Multiterm ordered suggestions*
The third method matches everything that contains a subphrase of the complete phrase as long as it’s in the correct order, i.e. “men’s shir,” but not “shirts me.”
Solr doesn’t have built-in features to generate this, but we can implement our own token filter. For more information on this and previous implementation (as well as complete information) - take a look at this [blog post](https://blog.griddynamics.com/implementing-autocomplete-with-solr)
|
11,859,456 |
To work with Solr, I need my searchbox to be suggesting whenever user type.. with a dropdown menu. How can i get it done? Any existing example?
|
2012/08/08
|
['https://Stackoverflow.com/questions/11859456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775856/']
|
[Here](http://blog.trifork.com/2012/02/15/different-ways-to-make-auto-suggestions-with-solr/) is an article I wrote about different ways to make auto suggestions and how to make the right choice. If you want something even more advanced and flexible there is [this other article](http://www.cominvent.com/2012/01/25/super-flexible-autocomplete-with-solr/), which contains an example as well.
|
There are multiple ways of providing autosuggest capabilities.
*Single term suggestion*
This method looks for the first letter, then the first word in a phrase, a search for “men’s shirts” must begin with “m,” then “men’s,” to bring up “men’s shirts” as a response.
This could be done by using following field type and querying with `my little po*`
```
<fieldType name="suggestion_text" class="solr.TextField" positionIncrementGap="100">
<analyzer>
<tokenizer class="solr.KeywordTokenizerFactory" />
</analyzer>
</fieldType>
```
*Multiterm unordered suggestions*
This autocomplete method recognizes “shirts” as part of the phrase, like “men’s shirts,” and suggests it to the customer along with “women’s shirts,” “work shirts,” and other phrases that contain “men’s.”
This one could be done by using following field type and querying with `my AND little AND po*`
```
<fieldType name="prefix_text" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.StandardTokenizerFactory" />
</analyzer>
</fieldType>
```
*Multiterm ordered suggestions*
The third method matches everything that contains a subphrase of the complete phrase as long as it’s in the correct order, i.e. “men’s shir,” but not “shirts me.”
Solr doesn’t have built-in features to generate this, but we can implement our own token filter. For more information on this and previous implementation (as well as complete information) - take a look at this [blog post](https://blog.griddynamics.com/implementing-autocomplete-with-solr)
|
67,541,800 |
I want to know what might be the possible advantages of passing by value over passing by const reference for primitive types like int, char, float, double, etc. to function? Is there any performance benefit for passing by value?
Example:
```
int sum(const int x,const int y);
```
or
```
int sum(const int& x,const int& y);
```
For the second case, I have hardly seen people using this. I know there is benefit of passing by reference for big objects.
|
2021/05/14
|
['https://Stackoverflow.com/questions/67541800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7908900/']
|
In every ABI I know of, references are passed via something equivalent to pointers. So when the compiler cannot inline the function or otherwise must follow the ABI, it will pass pointers there.
Pointers are often larger than values; but more importantly, pointers do not point at registers, and while the top of the stack is almost always going to be in cache, what it points at may not. In addition, many ABIs have primitives passed via register, which can be faster than via memory.
The next problem is within the function. Whenever the code flow could possible modify an `int`, data from a `const int&` parameter must be reloaded! While the reference is to const, the data it refers to can be changed via other paths.
The most common ways this can happen is when you leave the code the complier can see while understanding the function body or modify memory through a global variable, or follow a pointer to touch an `int` elsewhere.
In comparison, an `int` argument whose address is not taken *cannot* be legally modified through other means than directly. This permits the compiler to understand it isn't being mutated.
This isn't just a problem for the complier trying to optimize and getting confused. Take something like:
```
struct ui{
enum{ defFontSize=9;};
std:optional<int> fontSize;
void reloadFontSize(){
fontSize=getFontSizePref();
fontSizeChanged(*fontSize),
}
void fontSizeChanged(int const& sz){
if(sz==defFontSize)
fontSize=std:nullopt;
else
fontSize=sz;
drawText(sz);
}
void drawText(int sz){
std::cout << "At size " << sz <<"\n";
}
};
```
and the optional, to whom we are passing a reference, gets destroyed and used after destruction.
A bug like this can be far less obvious than this. If we defaulted to passing by value, it could not happen.
|
Typically, primitive types are not passed by reference, but sometimes there is a point in that. E.g, on x64 machine `long double` is 16 bytes long and pointer is 8 bytes long. So it will be a little bit better to use a reference in this case.
In your example, there is no point in that: usual `int` is 4 bytes long, so you can pass two integers instead of one pointer.
You can use `sizeof()` to measure the size of the type.
|
24,854,623 |
Grandfather process should go through numbers from 3 to N-1. Send each number through pipe(filedes) to Father.
Father should check the content of the pipe and compute something for each number in there. If the result is positive, create children to further compute it. Children should write their results into pipe(filedes1) to grandfather. Grandfather should check the pipe before communicating with Father.
In a nutshell:
```
Grandfather - sends data to Father
Father sends data to Children
Children send data to Grandfather
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#define N 20
int pid[N],child_no=0;
int prim(int m)
{
int i;
for (i=2; i<=m/2; i++)
if (m%i==0)
return 0;
return 1; //prim
}
int check_multiples(int i, int filedes11);
int main()
{
int filedes1[2], //grandpa->father
filedes2[2], //father->child
filedes3[2]; //child->grandpa
//pid[N],,i=0
if (pipe(filedes1)<0)
{
perror("pipe1");
exit(EXIT_FAILURE);
}
if (pipe(filedes2)<0)
{
perror("pipe2");
exit(EXIT_FAILURE);
}
if (pipe(filedes3)<0)
{
perror("pipe3");
exit(EXIT_FAILURE);
}
if ((pid[child_no]=fork())<0)
{
perror("fork");
exit(EXIT_FAILURE);
}
else
if (pid[child_no]==0) //father
{
int m,v[N],j=0;
close(filedes1[1]);
while (read(filedes1[0],&m,sizeof(m)))
{
if (prim(m))
v[j]=m;
child_no++;
if ((pid[child_no]=fork())<0)
{
perror("fork");
exit(EXIT_FAILURE);
}
else
if (pid[child_no]==0)
{
int k;
close(filedes3[0]);
for (k=2; k*m<=N; k++)
{
write(filedes3[1],&(int){k*m},sizeof(k*m));
write(filedes3[1], &(int){0}, sizeof(int));
exit(0);
}
}
}
int k;
printf("Prime numbers between 3 and N-1 are: ");
for (k=0; k<N; k++)
printf("%d ",v[k]);
printf("\n");
}
else //grandfather
{
int i,m,check=0;
close(filedes3[1]);
close(filedes1[0]);
for (i=3; i<N; i++)
{
printf("Checking %d...\n",i);
if (i!=3)
{
while (read(filedes3[0],&m,sizeof(m))!=0)
{
printf("%d\n",&m);
if (m==0)
break;
if (i==m)
{
check=1;
break;
}
}
}
printf("Finished checking %d.\n",i);
if (check==0)
write(filedes1[1],&i,sizeof(i));
}
}
return 0;
}
```
|
2014/07/20
|
['https://Stackoverflow.com/questions/24854623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2636820/']
|
Just try with:
```
list($month, $day, $year) = explode('/', $birthdate);
```
|
list($month, $day, $year) = explode('/', $birthdate);
|
24,854,623 |
Grandfather process should go through numbers from 3 to N-1. Send each number through pipe(filedes) to Father.
Father should check the content of the pipe and compute something for each number in there. If the result is positive, create children to further compute it. Children should write their results into pipe(filedes1) to grandfather. Grandfather should check the pipe before communicating with Father.
In a nutshell:
```
Grandfather - sends data to Father
Father sends data to Children
Children send data to Grandfather
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#define N 20
int pid[N],child_no=0;
int prim(int m)
{
int i;
for (i=2; i<=m/2; i++)
if (m%i==0)
return 0;
return 1; //prim
}
int check_multiples(int i, int filedes11);
int main()
{
int filedes1[2], //grandpa->father
filedes2[2], //father->child
filedes3[2]; //child->grandpa
//pid[N],,i=0
if (pipe(filedes1)<0)
{
perror("pipe1");
exit(EXIT_FAILURE);
}
if (pipe(filedes2)<0)
{
perror("pipe2");
exit(EXIT_FAILURE);
}
if (pipe(filedes3)<0)
{
perror("pipe3");
exit(EXIT_FAILURE);
}
if ((pid[child_no]=fork())<0)
{
perror("fork");
exit(EXIT_FAILURE);
}
else
if (pid[child_no]==0) //father
{
int m,v[N],j=0;
close(filedes1[1]);
while (read(filedes1[0],&m,sizeof(m)))
{
if (prim(m))
v[j]=m;
child_no++;
if ((pid[child_no]=fork())<0)
{
perror("fork");
exit(EXIT_FAILURE);
}
else
if (pid[child_no]==0)
{
int k;
close(filedes3[0]);
for (k=2; k*m<=N; k++)
{
write(filedes3[1],&(int){k*m},sizeof(k*m));
write(filedes3[1], &(int){0}, sizeof(int));
exit(0);
}
}
}
int k;
printf("Prime numbers between 3 and N-1 are: ");
for (k=0; k<N; k++)
printf("%d ",v[k]);
printf("\n");
}
else //grandfather
{
int i,m,check=0;
close(filedes3[1]);
close(filedes1[0]);
for (i=3; i<N; i++)
{
printf("Checking %d...\n",i);
if (i!=3)
{
while (read(filedes3[0],&m,sizeof(m))!=0)
{
printf("%d\n",&m);
if (m==0)
break;
if (i==m)
{
check=1;
break;
}
}
}
printf("Finished checking %d.\n",i);
if (check==0)
write(filedes1[1],&i,sizeof(i));
}
}
return 0;
}
```
|
2014/07/20
|
['https://Stackoverflow.com/questions/24854623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2636820/']
|
Just try with:
```
list($month, $day, $year) = explode('/', $birthdate);
```
|
If your format is fixed and you don't need to validate the date, you can directly use `substr`:
```
echo substr($birthdate,0,2); // month
echo substr($birthdate,3,2); // day
echo substr($birthdate,6,4); // year
```
|
24,854,623 |
Grandfather process should go through numbers from 3 to N-1. Send each number through pipe(filedes) to Father.
Father should check the content of the pipe and compute something for each number in there. If the result is positive, create children to further compute it. Children should write their results into pipe(filedes1) to grandfather. Grandfather should check the pipe before communicating with Father.
In a nutshell:
```
Grandfather - sends data to Father
Father sends data to Children
Children send data to Grandfather
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#define N 20
int pid[N],child_no=0;
int prim(int m)
{
int i;
for (i=2; i<=m/2; i++)
if (m%i==0)
return 0;
return 1; //prim
}
int check_multiples(int i, int filedes11);
int main()
{
int filedes1[2], //grandpa->father
filedes2[2], //father->child
filedes3[2]; //child->grandpa
//pid[N],,i=0
if (pipe(filedes1)<0)
{
perror("pipe1");
exit(EXIT_FAILURE);
}
if (pipe(filedes2)<0)
{
perror("pipe2");
exit(EXIT_FAILURE);
}
if (pipe(filedes3)<0)
{
perror("pipe3");
exit(EXIT_FAILURE);
}
if ((pid[child_no]=fork())<0)
{
perror("fork");
exit(EXIT_FAILURE);
}
else
if (pid[child_no]==0) //father
{
int m,v[N],j=0;
close(filedes1[1]);
while (read(filedes1[0],&m,sizeof(m)))
{
if (prim(m))
v[j]=m;
child_no++;
if ((pid[child_no]=fork())<0)
{
perror("fork");
exit(EXIT_FAILURE);
}
else
if (pid[child_no]==0)
{
int k;
close(filedes3[0]);
for (k=2; k*m<=N; k++)
{
write(filedes3[1],&(int){k*m},sizeof(k*m));
write(filedes3[1], &(int){0}, sizeof(int));
exit(0);
}
}
}
int k;
printf("Prime numbers between 3 and N-1 are: ");
for (k=0; k<N; k++)
printf("%d ",v[k]);
printf("\n");
}
else //grandfather
{
int i,m,check=0;
close(filedes3[1]);
close(filedes1[0]);
for (i=3; i<N; i++)
{
printf("Checking %d...\n",i);
if (i!=3)
{
while (read(filedes3[0],&m,sizeof(m))!=0)
{
printf("%d\n",&m);
if (m==0)
break;
if (i==m)
{
check=1;
break;
}
}
}
printf("Finished checking %d.\n",i);
if (check==0)
write(filedes1[1],&i,sizeof(i));
}
}
return 0;
}
```
|
2014/07/20
|
['https://Stackoverflow.com/questions/24854623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2636820/']
|
list($month, $day, $year) = explode('/', $birthdate);
|
If your format is fixed and you don't need to validate the date, you can directly use `substr`:
```
echo substr($birthdate,0,2); // month
echo substr($birthdate,3,2); // day
echo substr($birthdate,6,4); // year
```
|
1,936,525 |
**Updated Question Further Down**
I've been experimenting with expression trees in .NET 4 to generate code at runtime and I've been trying to implement the `foreach` statement by building an expression tree.
In the end, the expression should be able to generate a delegate that does this:
```
Action<IEnumerable<int>> action = source =>
{
var enumerator = source.GetEnumerator();
while(enumerator.MoveNext())
{
var i = enumerator.Current;
// the body of the foreach that I don't currently have yet
}
}
```
I've come up with the following helper method that generates a BlockExpression from an IEnumerable:
```
public static BlockExpression ForEachExpr<T>(this IEnumerable<T> source, string collectionName, string itemName)
{
var item = Expression.Variable(typeof(T), itemName);
var enumerator = Expression.Variable(typeof(IEnumerator<T>), "enumerator");
var param = Expression.Parameter(typeof(IEnumerable<T>), collectionName);
var doMoveNext = Expression.Call(enumerator, typeof(IEnumerator).GetMethod("MoveNext"));
var assignToEnum = Expression.Assign(enumerator, Expression.Call(param, typeof(IEnumerable<T>).GetMethod("GetEnumerator")));
var assignCurrent = Expression.Assign(item, Expression.Property(enumerator, "Current"));
var @break = Expression.Label();
var @foreach = Expression.Block(
assignToEnum,
Expression.Loop(
Expression.IfThenElse(
Expression.NotEqual(doMoveNext, Expression.Constant(false)),
assignCurrent
, Expression.Break(@break))
,@break)
);
return @foreach;
}
```
The following code:
```
var ints = new List<int> { 1, 2, 3, 4 };
var expr = ints.ForEachExpr("ints", "i");
var lambda = Expression.Lambda<Action<IEnumerable<int>>>(expr, Expression.Parameter(typeof(IEnumerable<int>), "ints"));
```
Generates this expression tree:
```
.Lambda #Lambda1<System.Action`1[System.Collections.Generic.IEnumerable`1[System.Int32]]>(System.Collections.Generic.IEnumerable`1[System.Int32] $ints)
{
.Block() {
$enumerator = .Call $ints.GetEnumerator();
.Loop {
.If (.Call $enumerator.MoveNext() != False) {
$i = $enumerator.Current
} .Else {
.Break #Label1 { }
}
}
.LabelTarget #Label1:
}
}
```
This seems to be OK, but calling `Compile` on that expression results in an exception:
```
"variable 'enumerator' of type 'System.Collections.Generic.IEnumerator`1[System.Int32]' referenced from scope '', but it is not defined"
```
Didn't I define it here:
```
var enumerator = Expression.Variable(typeof(IEnumerator<T>), "enumerator");
```
?
Of course, the example here is contrived and doesn't have a practical use yet, but I'm trying to get the hang of expression trees that have bodies, in order to dynamically combine them at runtime in the future.
---
**EDIT:** My initial problem was solved by Alexandra, thanks! Of course, I've run into the next problem now. I've declared a `BlockExpression` that has a variable in it. Inside that expression, I want another expression that references that variable. But I don't have an actual reference to that variable, just its name, because the expression is supplied externally.
```
var param = Expression.Variable(typeof(IEnumerable<T>), "something");
var block = Expression.Block(
new [] { param },
body
);
```
The `body` variable is passed in externally and has no direct reference to `param`, but does know the name of the variable in the expression (`"something"`). It looks like this:
```
var body = Expression.Call(typeof(Console).GetMethod("WriteLine",new[] { typeof(bool) }),
Expression.Equal(Expression.Parameter(typeof(IEnumerable<int>), "something"), Expression.Constant(null)));
```
This is the "code" that this generates:
```
.Lambda #Lambda1<System.Action`1[System.Collections.Generic.IEnumerable`1[System.Int32]]>(System.Collections.Generic.IEnumerable`1[System.Int32] $something)
{
.Block(System.Collections.Generic.IEnumerable`1[System.Int32] $something) {
.Call System.Console.WriteLine($something== null)
}
}
```
However, it doesn't compile. With the same error as before.
**TLDR:** How do I reference a variable by identifier in an expression tree?
|
2009/12/20
|
['https://Stackoverflow.com/questions/1936525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61632/']
|
You problem is that you didn't pass parameters and variables to your block expression. You use them in the "inner" expressions, but the block expression knows nothing about them. Basically, all you need to do is to pass all your parameters and variables to a block expression.
```
var @foreach = Expression.Block(
new ParameterExpression[] { item, enumerator, param },
assignToEnum,
Expression.Loop(
Expression.IfThenElse(
Expression.NotEqual(doMoveNext, Expression.Constant(false)),
assignCurrent,
Expression.Break(@break))
, @break)
);
```
|
Sorry if this is thread necromancy, but in case other people are running into the same or similar problem:
You can try to write an ExpressionVisitor that replaces a parameter with the same name and type in the external body expression with the variable parameter you have declared when creating the block expression. That way the parameter in the body will be the same object as the parameter in the block declaration and so the LambdaExpression should compile.
|
1,936,525 |
**Updated Question Further Down**
I've been experimenting with expression trees in .NET 4 to generate code at runtime and I've been trying to implement the `foreach` statement by building an expression tree.
In the end, the expression should be able to generate a delegate that does this:
```
Action<IEnumerable<int>> action = source =>
{
var enumerator = source.GetEnumerator();
while(enumerator.MoveNext())
{
var i = enumerator.Current;
// the body of the foreach that I don't currently have yet
}
}
```
I've come up with the following helper method that generates a BlockExpression from an IEnumerable:
```
public static BlockExpression ForEachExpr<T>(this IEnumerable<T> source, string collectionName, string itemName)
{
var item = Expression.Variable(typeof(T), itemName);
var enumerator = Expression.Variable(typeof(IEnumerator<T>), "enumerator");
var param = Expression.Parameter(typeof(IEnumerable<T>), collectionName);
var doMoveNext = Expression.Call(enumerator, typeof(IEnumerator).GetMethod("MoveNext"));
var assignToEnum = Expression.Assign(enumerator, Expression.Call(param, typeof(IEnumerable<T>).GetMethod("GetEnumerator")));
var assignCurrent = Expression.Assign(item, Expression.Property(enumerator, "Current"));
var @break = Expression.Label();
var @foreach = Expression.Block(
assignToEnum,
Expression.Loop(
Expression.IfThenElse(
Expression.NotEqual(doMoveNext, Expression.Constant(false)),
assignCurrent
, Expression.Break(@break))
,@break)
);
return @foreach;
}
```
The following code:
```
var ints = new List<int> { 1, 2, 3, 4 };
var expr = ints.ForEachExpr("ints", "i");
var lambda = Expression.Lambda<Action<IEnumerable<int>>>(expr, Expression.Parameter(typeof(IEnumerable<int>), "ints"));
```
Generates this expression tree:
```
.Lambda #Lambda1<System.Action`1[System.Collections.Generic.IEnumerable`1[System.Int32]]>(System.Collections.Generic.IEnumerable`1[System.Int32] $ints)
{
.Block() {
$enumerator = .Call $ints.GetEnumerator();
.Loop {
.If (.Call $enumerator.MoveNext() != False) {
$i = $enumerator.Current
} .Else {
.Break #Label1 { }
}
}
.LabelTarget #Label1:
}
}
```
This seems to be OK, but calling `Compile` on that expression results in an exception:
```
"variable 'enumerator' of type 'System.Collections.Generic.IEnumerator`1[System.Int32]' referenced from scope '', but it is not defined"
```
Didn't I define it here:
```
var enumerator = Expression.Variable(typeof(IEnumerator<T>), "enumerator");
```
?
Of course, the example here is contrived and doesn't have a practical use yet, but I'm trying to get the hang of expression trees that have bodies, in order to dynamically combine them at runtime in the future.
---
**EDIT:** My initial problem was solved by Alexandra, thanks! Of course, I've run into the next problem now. I've declared a `BlockExpression` that has a variable in it. Inside that expression, I want another expression that references that variable. But I don't have an actual reference to that variable, just its name, because the expression is supplied externally.
```
var param = Expression.Variable(typeof(IEnumerable<T>), "something");
var block = Expression.Block(
new [] { param },
body
);
```
The `body` variable is passed in externally and has no direct reference to `param`, but does know the name of the variable in the expression (`"something"`). It looks like this:
```
var body = Expression.Call(typeof(Console).GetMethod("WriteLine",new[] { typeof(bool) }),
Expression.Equal(Expression.Parameter(typeof(IEnumerable<int>), "something"), Expression.Constant(null)));
```
This is the "code" that this generates:
```
.Lambda #Lambda1<System.Action`1[System.Collections.Generic.IEnumerable`1[System.Int32]]>(System.Collections.Generic.IEnumerable`1[System.Int32] $something)
{
.Block(System.Collections.Generic.IEnumerable`1[System.Int32] $something) {
.Call System.Console.WriteLine($something== null)
}
}
```
However, it doesn't compile. With the same error as before.
**TLDR:** How do I reference a variable by identifier in an expression tree?
|
2009/12/20
|
['https://Stackoverflow.com/questions/1936525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61632/']
|
You problem is that you didn't pass parameters and variables to your block expression. You use them in the "inner" expressions, but the block expression knows nothing about them. Basically, all you need to do is to pass all your parameters and variables to a block expression.
```
var @foreach = Expression.Block(
new ParameterExpression[] { item, enumerator, param },
assignToEnum,
Expression.Loop(
Expression.IfThenElse(
Expression.NotEqual(doMoveNext, Expression.Constant(false)),
assignCurrent,
Expression.Break(@break))
, @break)
);
```
|
Don't forget to dispose IEnumerator in try/finally - lots of code (such as File.ReadLines()) depends on that.
|
1,936,525 |
**Updated Question Further Down**
I've been experimenting with expression trees in .NET 4 to generate code at runtime and I've been trying to implement the `foreach` statement by building an expression tree.
In the end, the expression should be able to generate a delegate that does this:
```
Action<IEnumerable<int>> action = source =>
{
var enumerator = source.GetEnumerator();
while(enumerator.MoveNext())
{
var i = enumerator.Current;
// the body of the foreach that I don't currently have yet
}
}
```
I've come up with the following helper method that generates a BlockExpression from an IEnumerable:
```
public static BlockExpression ForEachExpr<T>(this IEnumerable<T> source, string collectionName, string itemName)
{
var item = Expression.Variable(typeof(T), itemName);
var enumerator = Expression.Variable(typeof(IEnumerator<T>), "enumerator");
var param = Expression.Parameter(typeof(IEnumerable<T>), collectionName);
var doMoveNext = Expression.Call(enumerator, typeof(IEnumerator).GetMethod("MoveNext"));
var assignToEnum = Expression.Assign(enumerator, Expression.Call(param, typeof(IEnumerable<T>).GetMethod("GetEnumerator")));
var assignCurrent = Expression.Assign(item, Expression.Property(enumerator, "Current"));
var @break = Expression.Label();
var @foreach = Expression.Block(
assignToEnum,
Expression.Loop(
Expression.IfThenElse(
Expression.NotEqual(doMoveNext, Expression.Constant(false)),
assignCurrent
, Expression.Break(@break))
,@break)
);
return @foreach;
}
```
The following code:
```
var ints = new List<int> { 1, 2, 3, 4 };
var expr = ints.ForEachExpr("ints", "i");
var lambda = Expression.Lambda<Action<IEnumerable<int>>>(expr, Expression.Parameter(typeof(IEnumerable<int>), "ints"));
```
Generates this expression tree:
```
.Lambda #Lambda1<System.Action`1[System.Collections.Generic.IEnumerable`1[System.Int32]]>(System.Collections.Generic.IEnumerable`1[System.Int32] $ints)
{
.Block() {
$enumerator = .Call $ints.GetEnumerator();
.Loop {
.If (.Call $enumerator.MoveNext() != False) {
$i = $enumerator.Current
} .Else {
.Break #Label1 { }
}
}
.LabelTarget #Label1:
}
}
```
This seems to be OK, but calling `Compile` on that expression results in an exception:
```
"variable 'enumerator' of type 'System.Collections.Generic.IEnumerator`1[System.Int32]' referenced from scope '', but it is not defined"
```
Didn't I define it here:
```
var enumerator = Expression.Variable(typeof(IEnumerator<T>), "enumerator");
```
?
Of course, the example here is contrived and doesn't have a practical use yet, but I'm trying to get the hang of expression trees that have bodies, in order to dynamically combine them at runtime in the future.
---
**EDIT:** My initial problem was solved by Alexandra, thanks! Of course, I've run into the next problem now. I've declared a `BlockExpression` that has a variable in it. Inside that expression, I want another expression that references that variable. But I don't have an actual reference to that variable, just its name, because the expression is supplied externally.
```
var param = Expression.Variable(typeof(IEnumerable<T>), "something");
var block = Expression.Block(
new [] { param },
body
);
```
The `body` variable is passed in externally and has no direct reference to `param`, but does know the name of the variable in the expression (`"something"`). It looks like this:
```
var body = Expression.Call(typeof(Console).GetMethod("WriteLine",new[] { typeof(bool) }),
Expression.Equal(Expression.Parameter(typeof(IEnumerable<int>), "something"), Expression.Constant(null)));
```
This is the "code" that this generates:
```
.Lambda #Lambda1<System.Action`1[System.Collections.Generic.IEnumerable`1[System.Int32]]>(System.Collections.Generic.IEnumerable`1[System.Int32] $something)
{
.Block(System.Collections.Generic.IEnumerable`1[System.Int32] $something) {
.Call System.Console.WriteLine($something== null)
}
}
```
However, it doesn't compile. With the same error as before.
**TLDR:** How do I reference a variable by identifier in an expression tree?
|
2009/12/20
|
['https://Stackoverflow.com/questions/1936525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61632/']
|
Don't forget to dispose IEnumerator in try/finally - lots of code (such as File.ReadLines()) depends on that.
|
Sorry if this is thread necromancy, but in case other people are running into the same or similar problem:
You can try to write an ExpressionVisitor that replaces a parameter with the same name and type in the external body expression with the variable parameter you have declared when creating the block expression. That way the parameter in the body will be the same object as the parameter in the block declaration and so the LambdaExpression should compile.
|
29,570,594 |
I'm stumped why the mousewheel will not increment/decrement the value in a simple form element.
```html
<input type="number" step="0.125" min="0" max="0.875">
```
It works on this snippet just fine, but not when I create a simple generic html document:
```
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="">
<input type="number" step="0.125" min="0" max="0.875">
</form>
</body>
</html>
```
When I view this in several browsers, the mousewheel does not scroll. I've disabled browser extensions and such as well. Several other machines around me behave the same way.
**What causes this to not work? Is this an OS/browser issue?**
I almost feel like this might be something deeper, possibly the type of mouse/driver issue?
---
What I have tested on:
* Win 7
* Chrome - fail
* Firefox - fail
* Firefox Dev Edition - fail
* Safari - pass
* IE11 - fail
* IE9 - fail
* OSX
* Chrome - fail
* Safari - fail
* Firefox - fail
|
2015/04/10
|
['https://Stackoverflow.com/questions/29570594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/901449/']
|
Snippet runs in an IFRAME. Put your code into IFRAME and it will work too. Why - I don't know but it works.
i.e.
<http://codecorner.galanter.net/bla2.htm> - doesn't work (code by itself)
<http://codecorner.galanter.net/bla.htm> - works - previous page in an IFRAME
EDIT: Here's a demo of it working in Chrome 41: <http://codecorner.galanter.net/bla_mousescroll.mp4>
**EDIT 2:** I think I figured it out, and it's not IFRAMEs. In order for scroll event to happen - actual content has to be scrollable. For example if you redo your example like this:
```
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="" style="width:200px;overflow:scroll">
<div style="width:300px">
<input type="number" step="0.125" min="0" max="0.875">
</div>
</form>
</body>
</html>
```
where container form is smaller then its content - DIV - the scrolling wheel works on number field: <http://codecorner.galanter.net/bla3.htm>
|
So I think I figured it out.
First I copied your code into a html document and opened it in Chrome, and the increment didn't work.
Second I removed everything from the code except the input box, still didn't work.
Then I injected that code into random websites using the chrome inspector, I tried it on gmail, reddit and my own website. Gmail worked, reddit worked, but my own website didn't work.
So then I disabled javascript and it didn't work anywhere.
So to answer your question, stackoverflow / many other sites use javascript that automatically add that functionality to number inputs.
|
29,570,594 |
I'm stumped why the mousewheel will not increment/decrement the value in a simple form element.
```html
<input type="number" step="0.125" min="0" max="0.875">
```
It works on this snippet just fine, but not when I create a simple generic html document:
```
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="">
<input type="number" step="0.125" min="0" max="0.875">
</form>
</body>
</html>
```
When I view this in several browsers, the mousewheel does not scroll. I've disabled browser extensions and such as well. Several other machines around me behave the same way.
**What causes this to not work? Is this an OS/browser issue?**
I almost feel like this might be something deeper, possibly the type of mouse/driver issue?
---
What I have tested on:
* Win 7
* Chrome - fail
* Firefox - fail
* Firefox Dev Edition - fail
* Safari - pass
* IE11 - fail
* IE9 - fail
* OSX
* Chrome - fail
* Safari - fail
* Firefox - fail
|
2015/04/10
|
['https://Stackoverflow.com/questions/29570594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/901449/']
|
To avoid the browser issue altogether, you might try using the [jQuery mousewheel](https://github.com/jquery/jquery-mousewheel) plugin to manually change your input value. For example:
**index.html**
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="jquery.mousewheel.js"></script>
<script type="text/javascript" src="scroll.js"></script>
</head>
<body>
<form action="">
<input id="myInput" type="number" step="0.125" min="0" max="0.875">
</form>
</body>
</html>
```
**scroll.js**
```
$(function() {
$('#myInput').on("mousewheel", function(event) {
event.preventDefault();
$this = $(this);
$inc = parseFloat($this.attr('step'));
$max = parseFloat($this.attr('max'));
$min = parseFloat($this.attr('min'));
$currVal = parseFloat($this.val());
// If blank, assume value of 0
if (isNaN($currVal)) {
$currVal = 0.0;
}
// Increment or decrement numeric based on scroll distance
if (event.deltaFactor * event.deltaY > 0) {
if ($currVal + $inc <= $max) {
$this.val($currVal + $inc);
}
} else {
if ($currVal - $inc >= $min) {
$this.val($currVal - $inc);
}
}
});
});
```
Works for me in both Chrome and Firefox. The `mousewheel` event can be triggered when the mouse is hovering over the input as well, not just when it is selected.
|
So I think I figured it out.
First I copied your code into a html document and opened it in Chrome, and the increment didn't work.
Second I removed everything from the code except the input box, still didn't work.
Then I injected that code into random websites using the chrome inspector, I tried it on gmail, reddit and my own website. Gmail worked, reddit worked, but my own website didn't work.
So then I disabled javascript and it didn't work anywhere.
So to answer your question, stackoverflow / many other sites use javascript that automatically add that functionality to number inputs.
|
13,383,647 |
I have Google Translate on my page. It looks like a drop-down list, but all other drop-down lists on my page have another style. So I created jQuery function which change Google Translator drop down list styles. This function adds or deletes some style parameters. I'd like to know when I should call this function? In current code I call it after 3 sec. after document.ready
```
$(document).ready(function () {
setTimeout(wrapGoogleTranslate, 3000);
});
```
Current situation is that I hide the Div where Google translate is placed and show it after it's styles are corrected by my function. It means that my page loads, then it wait for 3 seconds, and *then* Google Translate appears with corrected styles.
I'd like to know how I can determine that Google Translate drop-down was loaded and then call my function to change the style. I don't want to make users wait for 3 seconds (maybe in some situations Google Translate would loads more than 3 seconds, then my function would never be executed).
|
2012/11/14
|
['https://Stackoverflow.com/questions/13383647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1753077/']
|
I recently wanted to change "Select Language" to simply "Language", so I also had to run code after Google's code had been executed. Here's how I did it:
**HTML**
It's important to set Google's `div` to `display:none` -- we'll fade it in with JavaScript so that the user doesn't see the text switching from "Select Language" to "Language".
```
<div id="google_translate_element" style="display:none;"></div>
<script type="text/javascript">function googleTranslateElementInit() {new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, gaTrack: true, gaId: 'UA-35158556-1'}, 'google_translate_element');}</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
```
**JavaScript**
```
function changeLanguageText() {
if ($('.goog-te-menu-value span:first-child').text() == "Select Language") {
$('.goog-te-menu-value span:first-child').html('Language');
$('#google_translate_element').fadeIn('slow');
} else {
setTimeout(changeLanguageText, 50);
}
}
changeLanguageText();
```
|
You can do it with pure JavaScript. It says in the W3 docs for the [`onLoad` attribute](http://www.w3schools.com/jsref/event_onload.asp) that you can add an attribute in a HTML element which takes as a parameter, the JavaScript code to be executed when the element has loaded.
Problem is, the attribute is only supported for a few elements which are:-
* `<body>`
* `<frame>`
* `<frameset>`
* `<iframe>`
* `<img>`
* `<input type="image">`
* `<link>`
* `<script>`
* `<style>`
So, I'd recommend going with an `<iframe>` or `<frame`. It should now look something like this:
```
<frame onLoad="wrapGoogleTranslate();" />
```
Or else, you can try this with jQuery:
```
$("div#googleTranslateWrapper").load(function() {
setTimeout(wrapGoogleTranslate, 3000);
});
```
Here's the documentation for jQuery's [`load` method](http://api.jquery.com/load/)
|
13,383,647 |
I have Google Translate on my page. It looks like a drop-down list, but all other drop-down lists on my page have another style. So I created jQuery function which change Google Translator drop down list styles. This function adds or deletes some style parameters. I'd like to know when I should call this function? In current code I call it after 3 sec. after document.ready
```
$(document).ready(function () {
setTimeout(wrapGoogleTranslate, 3000);
});
```
Current situation is that I hide the Div where Google translate is placed and show it after it's styles are corrected by my function. It means that my page loads, then it wait for 3 seconds, and *then* Google Translate appears with corrected styles.
I'd like to know how I can determine that Google Translate drop-down was loaded and then call my function to change the style. I don't want to make users wait for 3 seconds (maybe in some situations Google Translate would loads more than 3 seconds, then my function would never be executed).
|
2012/11/14
|
['https://Stackoverflow.com/questions/13383647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1753077/']
|
I had a similar situation where i had to change "Select Language" to just display "Language". Here is my CSS solution:
```
div#google_translate_element{
display: inline-block;
vertical-align: top!important;
}
div#google_translate_element *{
margin: 0px;
padding: 0px;
border: none!important;
display: inline-block;
vertical-align: top!important;
}
div#google_translate_element .goog-te-gadget-icon{
display: none;
}
div#google_translate_element .goog-te-menu-value{
color: #899290;
}
div#google_translate_element .goog-te-menu-value:hover{
color: #a6747e;
}
div#google_translate_element .goog-te-menu-value *{
display: none;
}
div#google_translate_element .goog-te-menu-value span:nth-child(3){
display: inline-block;
vertical-align: top!important;
}
div#google_translate_element .goog-te-menu-value span:nth-child(3)::after{
content: "Language"!important;
}
```
|
You can do it with pure JavaScript. It says in the W3 docs for the [`onLoad` attribute](http://www.w3schools.com/jsref/event_onload.asp) that you can add an attribute in a HTML element which takes as a parameter, the JavaScript code to be executed when the element has loaded.
Problem is, the attribute is only supported for a few elements which are:-
* `<body>`
* `<frame>`
* `<frameset>`
* `<iframe>`
* `<img>`
* `<input type="image">`
* `<link>`
* `<script>`
* `<style>`
So, I'd recommend going with an `<iframe>` or `<frame`. It should now look something like this:
```
<frame onLoad="wrapGoogleTranslate();" />
```
Or else, you can try this with jQuery:
```
$("div#googleTranslateWrapper").load(function() {
setTimeout(wrapGoogleTranslate, 3000);
});
```
Here's the documentation for jQuery's [`load` method](http://api.jquery.com/load/)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.