source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0040183772.txt"
] | Q:
R: How to parse a CFDi XML document
I'm just starting with R. I´m trying to parse a CFDi XML document. CFDi is a mexican standard for electronic invoices. I´ve tried the XML library normal parsing process with no success:
library(XML)
xmlurl <- "CFDi.xml"
xmlfile <- xmlTreeParse(xmlurl)
xmltop <- xmlRoot(xmlfile)
xmltable <- xmlSApply(xmltop, function(x) xmlSApply(x, xmlValue))
My xmltable ends up being a Value list rather than a Data matrix:
$Emisor
$Emisor$DomicilioFiscal
character(0)
$Emisor$ExpedidoEn
character(0)
$Emisor$RegimenFiscal
character(0)
$Receptor
$Receptor$Domicilio
character(0)
$Conceptos
$Conceptos$Concepto
character(0)
$Conceptos$Concepto
character(0)
$Conceptos$Concepto
character(0)
$Conceptos$Concepto
character(0)
$Conceptos$Concepto
character(0)
$Conceptos$Concepto
character(0)
$Conceptos$Concepto
character(0)
$Conceptos$Concepto
character(0)
$Conceptos$Concepto
character(0)
$Impuestos
Traslados
""
$Complemento
$Complemento$TimbreFiscalDigital
character(0)
I guess my error is related to the schema of the XML but not sure. Here's the CFDi.xml file (https://dl.dropboxusercontent.com/u/2736898/CFDi.xml). Thanks.
A:
Your code is correct but it does not work in this case because the XML file you provided does not have values to extracts.
Tags of your file do not have values inside them but only attributes that is why with xmlValue no values are returned.
Furthermore tag names are a little bit tricky because they have a colon inside it.
Here there are some examples:
The last liste of this cose allows you to see the tag names.
xmlfile <- xmlTreeParse(xmlurl, useInternalNodes = T)
xmltop <- xmlRoot(xmlfile)
names_file <- xmlSApply(xmltop, xmlName, full = TRUE)
names_file
Emisor Receptor Conceptos Impuestos
"cfdi:Emisor" "cfdi:Receptor" "cfdi:Conceptos" "cfdi:Impuestos"
Complemento
"cfdi:Complemento"
Suppose we want to extract all values (of the attributes) of the cfdi:Impuestos:
xml_impuest <- xpathApply(xmltop, "cfdi:Impuestos", xmlAttrs)
xml_impuest
[[1]]
totalImpuestosTrasladados
"207.440000"
Ad you can see, "Impuestos" has only one attributes.
It is better that you define well how parse what and "what" has "what" in terms of attributes and write a precise xPath query to investigate your data (by using xpathApply).
|
[
"stackoverflow",
"0028687882.txt"
] | Q:
Cutting SciPy hierarchical dendrogram into clusters via a threshold value
I'm trying to use SciPy's dendrogram method to cut my data into a number of clusters based on a threshold value. However, once I create a dendrogram and retrieve its color_list, there is one fewer entry in the list than there are labels.
Alternatively, I've tried using fcluster with the same threshold value I identified in dendrogram; however, this does not render the same result -- it gives me one cluster instead of three.
here's my code.
import pandas
data = pandas.DataFrame({'total_runs': {0: 2.489857755536053,
1: 1.2877651950650333, 2: 0.8898850111727028, 3: 0.77750321282732704, 4: 0.72593099987615461, 5: 0.70064977003207007,
6: 0.68217502514600825, 7: 0.67963194285399975, 8: 0.64238326692987524, 9: 0.6102581538587678, 10: 0.52588765899448564,
11: 0.44813665774322564, 12: 0.30434031343774476, 13: 0.26151929543260161, 14: 0.18623657993534984, 15: 0.17494230269731209,
16: 0.14023670906519603, 17: 0.096817318756050832, 18: 0.085822227670014059, 19: 0.042178447746868117, 20: -0.073494398270518693,
21: -0.13699665903273103, 22: -0.13733324345373216, 23: -0.31112299949731331, 24: -0.42369178918768974, 25: -0.54826542322710636,
26: -0.56090603814914863, 27: -0.63252372328438811, 28: -0.68787316140457322, 29: -1.1981351436422796, 30: -1.944118415387774,
31: -2.1899746357945964, 32: -2.9077222144449961},
'total_salaries': {0: 3.5998991340231234,
1: 1.6158435140488829, 2: 0.87501176080187315, 3: 0.57584734201367749, 4: 0.54559862861592978, 5: 0.85178295446270169,
6: 0.18345463930386757, 7: 0.81380836410678736, 8: 0.43412670908952178, 9: 0.29560433676606418, 10: 1.0636736398252848,
11: 0.08930130612600648, 12: -0.20839133305170349, 13: 0.33676911316165403, 14: -0.12404710480916628, 15: 0.82454221267393346,
16: -0.34510456295395986, 17: -0.17162157282367937, 18: -0.064803261585569982, 19: -0.22807757277294818, 20: -0.61709008778669083,
21: -0.42506873158089231, 22: -0.42637946918743924, 23: -0.53516500398181921, 24: -0.68219830809296633, 25: -1.0051418692474947,
26: -1.0900316082184143, 27: -0.82421065378673986, 28: 0.095758053930450004, 29: -0.91540963929213015, 30: -1.3296449323844519,
31: -1.5512503530547552, 32: -1.6573856443389405}})
from scipy.spatial.distance import pdist
from scipy.cluster.hierarchy import linkage, dendrogram
distanceMatrix = pdist(data)
dend = dendrogram(linkage(distanceMatrix, method='complete'),
color_threshold=4,
leaf_font_size=10,
labels = df.teamID.tolist())
len(dend['color_list'])
Out[169]: 32
len(df.index)
Out[170]: 33
Why is dendrogram only assigning colors to 32 labels, although there are 33 observations in the data? Is this how I extract the labels and their corresponding clusters (colored in blue, green and red above)? If not, how else do I 'cut' the tree properly?
Here's my attempt at using fcluster. Why does it return only one cluster for the set, when the same threshold for dend returns three?
from scipy.cluster.hierarchy import fcluster
fcluster(linkage(distanceMatrix, method='complete'), 4)
Out[175]:
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
A:
Here's the answer - I didn't add 'distance' as an option to fcluster. With it, I get the correct (3) cluster assignments.
assignments = fcluster(linkage(distanceMatrix, method='complete'),4,'distance')
print assignments
[3 2 2 2 2 2 2 2 2 2 2 2 1 2 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
cluster_output = pandas.DataFrame({'team':df.teamID.tolist() , 'cluster':assignments})
print cluster_output
cluster team
0 3 NYA
1 2 BOS
2 2 PHI
3 2 CHA
4 2 SFN
5 2 LAN
6 2 TEX
7 2 ATL
8 2 SLN
9 2 SEA
10 2 NYN
11 2 HOU
12 1 BAL
13 2 DET
14 1 ARI
15 2 CHN
16 1 CLE
17 1 CIN
18 1 TOR
19 1 COL
20 1 OAK
21 1 MIL
22 1 MIN
23 1 SDN
24 1 KCA
25 1 TBA
26 1 FLO
27 1 PIT
28 1 LAA
29 1 WAS
30 1 ANA
31 1 MON
32 1 MIA
|
[
"stackoverflow",
"0047081606.txt"
] | Q:
Can 'git log' ignore certain commits based on commit message?
I'm using git log in order to generate a diff between two branches. The exact command I'm using is:
git log --left-right --graph --cherry-pick --oneline sourceBranch...targetBranch
What I'm wondering is if I can exclude some of the log entries based on the commit message. For example, all of the commits by our test automation team contain a certain identifier, we'll call it TEST_AUTO. Currently, the output from my diff looks like this:
> 1e31b8x Merge pull request #1225 in base/project from feature/ABCD-1111 to master
|\
| > b2f0dfx [ABCD-1111] rework help tour // fixes
| > 270072x [ABCD-1111] rework help tour // merge fixes
| > 98ffeax [ABCD-1111] rework help tour // merge fixes
| > ff2e25x Merge branch 'master' into feature/ABCD-1111-rework-help-tour
| |\
| > | f0daf2x [ABCD-1111] rework help tour // new menu
| > | c519a2x [ABCD-1111] rework help tour
| > | 6873cax [ABCD-1111] rework help tour // animations
| > | 944cc7x [ABCD-1111] rework help tour // fix phone fullscreen
| > | 72b3ffx [ABCD-1111] rework help tour // phone animations
| > | 7f7c50x [ABCD-1111] rework help tour // base logic
| > | b6dccex [ABCD-1111] rework help tour
| > | a30022x [ABCD-1111] rework help tour // code clean up and new icons
> | | c0a3e1x Merge pull request #11361 in base/project from TEST_AUTO-123-bring-automation-code-to to master
|\ \ \
| |_|/
|/| |
| > | 9837a4x [TEST_AUTO-123] Bring Android automation code to 123.X version
| > | 41b33cx Merge branch 'feature/automation' into TEST_AUTO-951-bring-automation-code-to
| > | bb53f6x Merge branch 'feature/automation' into TEST_AUTO-951-bring-automation-code-to
| |\ \
| | > | aa1a90x [TEST_AUTO-123] Bring Android automation code to 123.X version
| | > | 876ee8ex Merge pull request #12261 in base/project from bugfix/TEST_AUTO-789-android-fix to feature/automation
| | |\ \ \
| | | > | | ef3fa1x [TEST_AUTO-456] fixed test_508()
| | | > | | a2d352x [TEST_AUTO-456] fixed test_186 and moved to PortfolioTest
| | | > | | 1880b0x [TEST_AUTO-456] small fix test_493
| | | > | | facc13x [TEST_AUTO-456] fixed test_493
| | | > | | 9ebce6x [TEST_AUTO-456] fix test_31734 (test_493)
| | | > | | 128890x [TEST_AUTO-456] fix test_31621 (test_384) and moved to common/MediaTest
| | | > | | ab64b8x [TEST_AUTO-456] fix test_498()
| | | > | | 7935aax [TEST_AUTO-456] fix test_31740 (test_498) (not ready)
| | | > | | ffb930x [TEST_AUTO-456]fixed test_31751 (test_508) and moved to common/SideMenuTest
| | | | > | 2b810ax Merge remote-tracking branch 'remotes/origin/feature/automation' into bugfix/TEST_AUTO-789-android-fix
These generate a lot of log noise that I'm not interested in.
Ideally, I'd like to exclude any commits from the compare that contain this TEST_AUTO string. I've tried piping the above command to 'grep -v' but that just eliminates the lines that contain it (obviously) and leaves weird gaps in the tree. I want to prevent them from being included at all.
A:
git log --invert-grep --grep=TEST_AUTO
from man git log:
--invert-grep
Limit the commits output to ones with log message that do not match the pattern specified with --grep=<pattern>.
|
[
"stackoverflow",
"0029257244.txt"
] | Q:
Inserting new records into table with row number as id with PostgreSQL
I have a database table, let's call it Foo. Foo has an id column (which is long), and some data columns, let's call them Bar1 and Bar2
There is a script that used to work before there was an id column, that would simply add new stuff into the table like this:
INSERT INTO Foo
SELECT OldBar1, SUM(OldBar2)
FROM OldFoo
GROUP BY OldBar1
Now, after the id has been added, if I have a new, Foo table empty initially, then I can do this:
INSERT INTO Foo
SELECT row_number() OVER() as id, OldBar1, SUM(OldBar2)
FROM OldFoo
GROUP BY OldBar1;
And the data in Foo table will have their ids equal row numbers.
However, when there is existing data in the Foo table and I execute the previous query, I get an exception stating that "Key (id)=(1) already exists".
Obviously, I do not want the row_number to look at the source, the OldFoo table, but rather to the new, Foo table.
To draw a parallel example in Java, using HashMap<Integer, Foo> as the repository:
map.put(map.size() + 1, fooObject);
Is there a way to achieve this, to generate the ID which will be the same as row number in the target table?
A:
I strongly recommend finding a way to use serial. However, assuming that there are no other insert operations occurring on the table, the following should work for you:
INSERT INTO Foo
SELECT (f.maxId + row_number() OVER() )as id, OldBar1, SUM(OldBar2)
FROM OldFoo CROSS JOIN
(SELECT MAX(id) as MAX(ID) FROM Foo) f
GROUP BY OldBar1, f.maxId;
A piece of advice: when using INSERT always include the column names. So your query should read something like INSERT INTO Foo(Id, OldBar). This makes the code easier to maintain and to understand.
|
[
"math.stackexchange",
"0000759972.txt"
] | Q:
Intersection of an $n-$sphere and a plane (when non-empty and not a point)
Let the n-sphere of radius $r$ centered at $(0,0,...,0,y)\in\mathbb{R}^{n+1}$ be defined by
$$
\mathcal{S} \iff {x_1}^2 + {x_2}^2 + ... + {x_n}^2 + (x_{n+1}-y)^2 = r^2
$$
and consider the function $d$ which to any point in the unit-ball $B(0,r)\subset \mathbb{R}^n$ associates the dependent coordinate $x_{n+1}\leq y$ in the lower hemisphere of $\mathcal{S}$:
$$
d\ :\ v\in B(0,r)\ \mapsto\ y -\sqrt{r^2 - \|v\|^2}
$$
For a given $v = (v_1,...,v_n)\in B(0,r)$, consider now the function
$$
\forall t\in I_v\subset\mathbb{R},\quad \psi_v(t) = \big( tv_1, tv_2, ..., tv_n, d(tv) \big)
$$
Is the image of $\psi_v$ a circle?
A:
By definition of $d$ and for a given $v$, the image of $\psi_v$ will always be a half-circle of radius $r$ centered at $y$ in the plane $(x-y)\cdot(\psi_v(0)\wedge\psi_v(1)) = 0$.
|
[
"stackoverflow",
"0022616165.txt"
] | Q:
How use Java FileChannel to copy preserving timestamps
How use Java FileChannel to copy preserving timestamps for files and directories?
Looks like the files are not preserving timestamps while copying to another location.
How is that possible using FileChannel in Java?
A:
You can not do it by FileChannel, you can use apache commons io :
IOUtils.copy(new FileInputStream(file), new FileOutputStream(file2));
// copy file and preserve the time stamp. the sourceFile and destFile are of type java.io.File
FileUtils.copyFile(sourceFile,destFile);
Reference : http://www.studytrails.com/java-io/file-copying-and-moving-deleting.jsp
|
[
"serverfault",
"0000016284.txt"
] | Q:
Postfix local delivery rewriting address so that it is not deliverable
I have a basic Ubuntu Server 9.04 install with Postfix freshly installed via apt-get. When I do a
sendmail -bv [email protected]
where vlewis is a unix account.
The delivery report I get says that it failed to deliver because the address [email protected] is a bad recipient address.
This is the mail system at host moose.bunner.ath.cx.
Enclosed is the mail delivery report that you requested.
The mail system
: delivery via local: delivers to command:
/usr/bin/procmail
: delivery via local: bad recipient address syntax:
[email protected]
Why is it rewriting the username. Please help. This is driving me nuts!
(I'm adding this string to make this problem less Google resistant because you cannot Google for -f- so I add dash f dash in an attempt to help).
A:
Does that user have a .forward file setup?
|
[
"math.stackexchange",
"0002413493.txt"
] | Q:
Direct Proof - Discrete Mathematics
I am given
Prove that there are no integer solutions to the equation
$$x^2=4y+3$$
I started off by proving the square of the integer is either $0 \pmod{4}$ or $1 \pmod{4}$. If $x$ is even then $x=2k$ for some integer $k$. Then $x^2=(2k)^2=4k^2$.
Will this satisfy the question?
A:
$$x^2=\underbrace{4y}_{even}+\underbrace{3}_{odd} \to x \text { must be odd }$$
take x odd like 2k+1
so
$$x^2=(2K+1)^2=4k^2+4k+1=4\underbrace{k(k+1)}_{even}+1\\\to x^2=8q+1$$ now check in first equation
$$x^2=4y+3\\8q+1=4y+3\\8q-4y=2\\\div 4 \\\underbrace{2q-y}_{\in \mathbb{Z}}=\frac 12$$and it is impossible
A:
$x$ must be odd (since rhs is odd), i.e $x=2k+1$ for $k\in\mathbb{Z}$. But then lhs is
$$x^2=(2k+1)^2=4(k^2+k)+1\equiv 1\pmod{4}$$
but rhs
$$4y+3\equiv 3\pmod{4}$$
|
[
"stackoverflow",
"0041038110.txt"
] | Q:
Does the API allow access to document metadata on Evernote?
I have a smart pen that automatically uploads my notes to Evernote. My handwritten notes are OCR'ed and are searchable in Evernote (premium). Is there any way to programmatically access the digitalised version of my notes via Evernote's API? (I assume the digitalised text is added as meta content to the file).
A:
Yes you can.
Take a look at https://dev.evernote.com/doc/articles/image_recognition.php and https://dev.evernote.com/doc/reference/NoteStore.html#Fn_NoteStore_getResourceRecognition
It should help.
NB : The Evernote API terms of service prohibit you from simply using Evernote as a cloud OCR engine.
|
[
"stackoverflow",
"0028297060.txt"
] | Q:
Can I get invited to the iOS Developer Programm and then manage everything on my own?
An acquaintance and I like to publish an iOS app to the Apple App Store.
Can he enroll into the iOS Developer Programm ($99/year) with his AppleID and invite my AppleID as a member, then make me an admin, so that I am able to develop/ publish and maintain everything without his help? Or do I need to enroll, too?
Thanks for your answer!
A:
You can do that. Instructions for that can be found in the apple developer guides
https://developer.apple.com/library/ios/recipes/MemberCenter_Recipes/AddingTeamAdminsandMembers/AddingTeamAdminsandMembers.html
|
[
"math.stackexchange",
"0000048689.txt"
] | Q:
A balanced latin rectangle (more rows than columns)
In psychology we sometimes use balanced latin squares for the order of our tests to counterbalance first-order carry-over effects (fatigue, learning, etc.) .
For our current study we want to pretest 12 stimuli (let's call them A-F) to see whether they're useful for a later study. We don't want to bore our participants, so we wanted to give them only half of all the material we need to test. We're indifferent about the size of the subset of 12 as long as it is anything between 4-8 stimuli per participant.
For a different reason (to achieve sufficient statistical power) we need at least 132 participants (at least 11 runs where each stimulus occurs first), we don't want to exceed this too heavily.
A balanced latin square 6*6 isn't too hard to construct. There is a Matlab script as well.
A B F C E D
B C A D F E
C D B E A F
D E C F B A
E F D A C B
F A E B D C
But is it also possible to construct a balanced (latin) rectangle (6 columns wide), where each letter is followed by another letter an equal amount of times? How many rows (participants) would this yield?
Maybe somebody with a bit more handle on this problem will enjoy the puzzle!
Sorry if my language is too idiosyncratic, if I can clarify with the appropriate jargon I'll duly comply, this is quite outside my field.
Splitting it in the middle and then adding the broken-up orders seemed the wrong approach to me.
Edit: Can I find one computationally? I have no idea how ridiculous that question is, but the sheer number of permutations (479 001 600) does seem daunting.
Edit 2: I didn't want to make this question too much about our experiment, but apparently that made it less clear. I'm sorry. I edited the clarifications into the question.
A:
I need to change your parameters a bit, but it sounded like you would be flexible, so let me suggest the following idea.
The idea only works when the number of stimuli is a prime number $p$. So if you need to test exactly 12 stimuli, then this is useless, but may be you can leave one out, or add a placebo/null test to the mix, and use this idea with $p=11$ or $p=13$.
The scheme has $p(p-1)$ rows and $k$ columns, where $k$ is any number between $2$ and $p$ inclusive.
Instead of letters A,B,... I use numbers $0,1,\ldots,p-1$ as table entries. One of the standard constructions for Latin squares is the following: First pick a parameter $m$ that is an integer in the range $1\le m<p$. Then put on row #$i$ and column #$j$ the number that equals the remainder of $i+mj$ when divided by $p$. This gives us a $p\times p$ Latin square. Call it $L(m,p)$. In this Latin square all the pairs of consecutive entries on all rows differ by $m$. Therefore this square alone is the very opposite of balanced. Within this square a zero is always followed by an $m$, a one by $m+1$ et cetera. Note that we count cyclically $\pmod p$, so an entry $p-m$ is always followed by $(p-m)+m=p\equiv 0$, and so forth.
Here comes the trick. We build a larger table with $p(p-1)$ rows by putting all the Latin squares $L(1,p)$, $L(2,p)$, $\ldots$, $L(p-1,p)$ on top of each other. By using all the possible values of $m$ we get a balanced table in the end!
We can take the $k$ first columns of this large table, and be done with it. Each entry occurs on all the columns exactly $p-1$ times. If two distinct entries, say $a$ and $b$, differ by $m=b-a$, the pair $(a,b)$ appears in the rows of $L(m,p)$ exactly $k-1$ times - once per each pair of adjacent columns, and doesn't appear on any other rows. There are no repetitions of stimuli within rows, as the rows are parts of rows of a Latin square.
Why doesn't this work with $p=12$? IOW, why do I insist that $p$ must be a prime? The reason is that the formula $i+m*j \bmod p$ gives a Latin square only, when $m$ is coprime to $p$. For example, if $p=12$ and $m=6$, then the rows of $L(6,12)$ look like 0,6,0,6,...; 1,7,1,7,...
With $p=13$ you get 156 rows, so the table may be too large for you. Another possibly troubling feature of this construction is the following. The rows of the Latin square $L(1,p)$ look like 0,1,2,...; 1,2,3,...; so they have intersections of $k-1$ elements. This may be bad for eliminating secondary correlations from your test. If you do $k=6$ tests per participant, then five participants will see stimulus #1 followed by stimulus #2. That's ok, but I am a bit troubled by the fact that four out of those five will see stimulus #3 next. And the fifth person won't see anything, because his/her day ends after stimulus #2. Similar patterns appear in other component squares $L(m,p)$. If these shortcomings make the construction unusable, then I apologize for wasting your time.
[Edit: Oh boy, I should learn to proofread and not post in such haste. I apologize for the mostly illegible first version :-(]
A:
If I understand the question correctly, you are seeking a $12 \times 6$ Latin rectangle (strictly speaking, this is the transpose of a Latin rectangle) in which each of 12 symbols (each representing a stimulus) occurs exactly once in each column (representing a round of experimentation) and at most once in each row (representing the participants). There is an additional condition that the Latin rectangle be balanced (i.e. each possible pair of symbols occurs in horizontally neighbouring cells).
This cannot be achieved since there will be exactly 6 copies of any symbol in the Latin rectangle, but there will be 11 other symbols. Simply put, they won't fit. The closest you could get is to take a balanced Latin square and chop off the last 6 columns (this is probably not suitable for your experiment).
A natural next step would be to modify the scheme so as to incorporate more rows (i.e. participants) and weaken the "Latin" property. I.e., several participants may receive the same stimulus at the same time. In such a modified scheme, we could balance the carry-over effects by ensuring that each ordered pair of symbols (A,B) appear in horizontally adjacent cells an equal number of times (as opposed to exactly once in the Latin square case). If you stick to exactly 6 rounds of testing, then each row contains exactly 5 ordered pairs. Unfortunately, there are $12 \times 11=132$ ordered pairs in total (which is coprime with 5), implying that the smallest balanced such scheme would require at least 132 participants.
If you're flexible on the number of rounds, if you had 7 rounds of testing, it's likely going to be possible to find such a scheme with only 22 participants (since there are 6 ordered pairs per row, and 132 is divisible by 6). That is, it seems likely there will be a $22 \times 7$ matrix containing the symbols $1,2,\ldots,12$ that is balanced (although actually finding one might be a bit tricky).
|
[
"pets.stackexchange",
"0000008087.txt"
] | Q:
Why is my cat losing her hair and not wanting to use the litter boxes?
My cat is 9 yrs old, and over the past year she has started losing hair around her back legs and tail. Initially, I thought it may have been due to fleas, so I got her on a once a month flea tablet that works very well. However, her hair still hasn't been coming back and now she will not use any of the litter boxes. We have not changed the type of litter we use or any of her food, so I am at a loss. We have other cats and dogs and none of them show any signs of illness or behaviors like she has. Any help would be appreciated.
A:
As someone who has similar issues with my own cat, this kind of behavior around the litter box always ends with the same results... my cat has a UTI.
If your cat is acting strange she is trying to tell you something, "Take me to the vet!"
The hairless hindquarters in my experience is usually allergy related, not necessarily like a rash, but an internal allergic reaction that usually requires regular treatment.
But only your vet can tell you for sure.
|
[
"stackoverflow",
"0014094086.txt"
] | Q:
Renaming imports on pre-compiled class files (Java)
What is the issue?
I'm a Minecraft server admin/ server host / plugin developer, but find it an absolute annoyance to have to update my own personal plugins on every new release of the core game. It wasn't always like this, I've had plugins work across 20 versions without breaking in the past. To have to sit by and update 40 plugins once every month is, as you can imagine, an unneeded annoyance in my life considering I've never had to do this in the past.
What is causing the issue?
Upon each new release, they require you to use different imports in your compiled jar files, thus forcibly breaking any outdated (but possibly still working) jar files. Believe me. I can read an error log and know when I need to actually go out and download a new update. I don't need to be protected from myself right now. It's just a game, I don't have much riding on it.
So what do I want to do about it?
To this end, I'd like to make a simple program that automatically updates all my plugins for me. (Plugins come in the form of packaged .jar files.) It needs to do the following:
Get a list of all jar files in X_Folder
for each jar file, get all classes encased.
for each class file, search for any instance of Y_STRING and replace it with Z_STRING.
make sure everything gets put back into the jar files correctly.
done.
Question?
How would I code the class file editing method? I don't even know how to begin.
Disclaimer
Sorry for sounding like I haven't even begun working on this. I just, don't have any experience with byte code manipulation. I've seen a few examples, but haven't seen anything about renaming imports yet. Hopefully someone here can help me. Thank you!
A:
Get a list of all jar files in X_Folder
for each jar file, get all classes encased.
for each class file, search for any instance of Y_STRING and replace it with Z_STRING.
make sure everything gets put back into the jar files correctly.
done.
1) This is basic file manipulation. Look into java.io.File#listFiles() or its overloads.
2) a JAR file is a ZIP file with specific contents. Look into java.util.jar.JarFile or java.util.zip.ZipInputStream; Iterate over its entries (JarFile#entries()) and decompress each class file within (JarFile#getInputStream(ZipEntry)).
3) The class file is a binary format but it's documented very well. The general layout is documented on wikipedia: http://en.wikipedia.org/wiki/Java_class_file#General_layout
Of special interest is the Constant pool, which starts at byte 10 of the class file and enumerates all constants referred to from within the class file. It is, again, documented on Wikipedia: http://en.wikipedia.org/wiki/Java_class_file#The_constant_pool . Its number of entries is stored in bytes 8 and 9 (big-endian).
Of special interest within the constant pool are strings and class references.
Strings are identified by the first byte being 1. The next two bytes are the byte length of the string, and the remaining bytes are in UTF-8 (almost). Unlike UTF-8, higher planes are stored as surrogate pairs (6 bytes instead of 4) and the code point 0 is stored denormalised.
A class reference is nothing but a pointer to the constant pool, pointing to the class' fully qualified name. The fully qualified name is stored with forward slashes instead of dots to separate the fully qualified name (java/lang/Object). It's marked as the type 7.
Other entries in the constant pool: types 3,4,9-12 are four-byte, types 7 and 8 are two-byte. Types 5 and 6 are eight-byte but they also take up two slots in the constant pool.
The rest of the class file doesn't seem to mind if the byte length of the constant pool changes. Adding entries at the end of the constant pool seems safe as well (be sure to update the constant pool length).
4) Since a jar file is just a zip file, all you need is to repackage the original file with the updated contents. I don't expect this to be possible in-place, so you might need some file shuffling. Look into java.util.zip.ZipOutputStream for the implementation.
|
[
"stackoverflow",
"0014738945.txt"
] | Q:
Tridion Copy/Paste In the same org item causes TCM54 Error
We are experiencing a strange issue after upgrading from Tridion 2011 GA to 2011 SP1 HR1. When doing a copy-paste of components within the same folder we normally get a popup asking if we want to paste with a different name, however, in our case we see an error message as follows:
/WebUI/Models/TCM54/Services/General.svc/CopyPasteItem failed to execute. STATUS (500): Internal Server Error The page cannot be displayed because an internal server error has occurred.
The only thing that is visible in the Event Viewer logs are warnings, which are expected (because my test VM gets them too). We don't actually see any errors other than the one in the GUI.
When copy/pasting components within a folder:
Unable to paste the item into this Folder.
Name must be unique for items of type: Component within this Folder and its BluePrint context. Source or sources of conflict: tcm:4-81455.
Error Code:
0x80040329 (-2147220695)
Call stack:
UtilitiesBL.AssertUniqueTitle
UtilitiesBL.CloneItem
ComponentBL.Clone
Tridion.ContentManager.ContentManagement.RepositoryLocalObject.Copy(OrganizationalItem,Boolean)
Tridion.ContentManager.BLFacade.ContentManagement.RepositoryLocalObjectFacade.Clone(UserContext,String,String,Boolean)
Folder.PasteItem
When copy/pasting Pages in Structure Groups:
It is not possible to paste this item into a Structure Group.
Name and File name both must be unique for items of type: Page within this Structure Group and its BluePrint context. Source or sources of conflict: tcm:5-82986-64.
Error Code:
0x80040329 (-2147220695)
Call stack:
UtilitiesBL.AssertUniqueTitleAndFileName
UtilitiesBL.AssertUniqueTitleAndFilename
UtilitiesBL.CloneItem
PageBL.Clone
Tridion.ContentManager.ContentManagement.RepositoryLocalObject.Copy(OrganizationalItem,Boolean)
Tridion.ContentManager.BLFacade.ContentManagement.RepositoryLocalObjectFacade.Clone(UserContext,String,String,Boolean)
StructureGroup.PasteItem
As mentioned above, these are normal warnings generated in the Event log, but we should be getting a popup, not the error.
We have tried restarting the server thinking it's a one-off type of quirk, but that didn't help. I understand that "TCM54" as mentioned in the error message refers to code running through COM+. Can anyone please offer some advice?
A:
Take a look at this post: Unable to save Publication Targets in Tridion 2011 SP1
I seem to recall that pasting uses the old (COM based) code like Publication Targets do.
|
[
"stackoverflow",
"0053400063.txt"
] | Q:
overriding partially an numpy array does not work
I tried to override a numpy array partially
does anyone know how to do that in such comfort indexing way?
Thanks!
A:
Setup
a = np.array([[1,2,3], [1,1,1], [1,1,1]])
b = np.array([[888,888], [99, 99]])
You are operating on a copy of the array, so the modifications are not persisted, use numpy.ix_ here:
>>> a[np.ix_([1,2], [0,1])] = b
>>> a
array([[ 1, 2, 3],
[888, 888, 1],
[ 99, 99, 1]])
|
[
"stackoverflow",
"0012174793.txt"
] | Q:
Django Access Data in "through" table given both entities
I have browsed through lots of "through table access" in SO so if I missed something, feel free to close this.
I have a table A, a table B, in an n-n relationship and a through table C. C contains the "in_stock"property. Obviously, a pairing of object A1 and B1 will always be unique. So if I am given A1, and B1, how do I access in a template, the "in_stock" property in the "through table" C?
Additional INfo:
I am looping over the Bs A1 has in the template, so in an iteration I can have A1-B1, on another A1-B2, etc.
A:
I use a custom tag to do so :
(assuming you have A1 in the template)
{% load custom_tag %}
<ul>
{% for b in Bs %}
{% autoescape off %}
<li>in_stock for {{ A1 }} and {{ b }} : {{ A1|through:b }}</li>
{% endautoescape %}
</ul>
{% endfor %}
custom_tag.py
register = template.Library()
def through(A1, b):
t = "%s" % (C.objects.get(b=b, a=A1).in_stock)
return t
register.filter(through)
|
[
"stackoverflow",
"0040991114.txt"
] | Q:
Issue communication with postMessage from parent to child iFrame
I'm having an issue communicating from my parent window to the child iFrame. But in the other side, everything works perfectly.
Here is how I get the chil iFrame object in order to fire the postMessage function:
var iFrame = document.getElementById('Frame').contentWindow;
When I print it int he console, I get the following:
Window {parent: Window, opener: null, top: Window, length: 0, frames: Window…}
When I proceed to the postMessage function as follows:
iFrame.postMessage("message", "http://contoso.com");
It shows me an error when loading the page: iFrame.postMessage is not a function.
When I execute the postMessage in console, I get an undefined
What am I doing wrong ?
A:
try this
var iFrame = document.getElementById('Frame');
iFrame.contentWindow.postMessage("message", "http://contoso.com");
I had this problem too. I found solution from this website https://www.viget.com/articles/using-javascript-postmessage-to-talk-to-iframes
|
[
"math.stackexchange",
"0000027217.txt"
] | Q:
We have angle=arctan(dy/dx), but what happens when dx=0?
Here is a formula: $\text{angle}=\arctan(dy/dx)$.
I can find an angle with my calculator for any value except $dx=0$.
My question is: is there no angle or, is there something that says when $dx=0$ the angle is found differently?
A:
If $dx$ is $0$, if you look in the Cartesian plane, you are standing in the y-axis, so the angle would be $\frac{\pi}{2}$ or $\frac{3\pi}{2}$, depending if $dy > 0$ or $dy < 0$.
A:
Since none of the answers have mentioned this, I'm putting this for completeness' sake: advanced calculators and computing environments provide for a "two-argument" arctangent function $\arctan(x,y)$ (denoted as atan2() in some environments, and with the order of the arguments sometimes reversed) that is especially intended for polar coordinate conversions. Briefly, $\arctan(x,y)$ gives the same results as $\arctan\frac{y}{x}$, adjusted when necessary so that the result is within $(-\pi,\pi]$, taking into account which quadrant the point $(x,y)$ is in. When $x=0$ and $y\neq 0$, $\arctan(0,y)=\frac{\pi}{2}\mathrm{sign}\,y$.
|
[
"meta.stackexchange",
"0000299965.txt"
] | Q:
What should I do if I deleted all my bad low quality unanswered questions and I am permanently blocked from asking and answering questions?
I deleted all my bad low quality unanswered questions and they are unrecoverable, so I am unable to fix or improve my bad low quality unanswered questions.
I am also permanently blocked from asking questions and answering questions, so I have no way to contribute to the community in any way.
Is it a sign that I am doomed forever? I guess that yes I am.
Well I still can use email of someone else if I want to post, but with my email I can't post anymore forever. Is that true? I guess that yes it is.
A:
If you deleted all your bad low quality unanswered questions then you should always be able to undelete them.
Consequently, I see no reason why you should consider them to be unrecoverable.
Once you are satisfied that you can undelete those questions, by testing one first, follow all of these instructions:
What can I do when getting "We are no longer accepting questions/answers from this account"?
I would advise strongly against using another email address to try and circumvent a question/answer ban because that will only deepen the level at which the ban applies. I recommend reading and acting upon the instructions above instead.
Note that you can always undelete your own questions, but if they were deleted more than 60 days ago you may not be able to find them. If you suspect that some of these are keeping you in your question ban I think your best option is to ask the moderators of your site to provide you with links to them.
|
[
"stackoverflow",
"0015376192.txt"
] | Q:
Eliminate inefficient code
I was wondering if one is inefficient over the other (two codes below)?
if ( abc & myType == myType )
{
if (myValue)
{
// do something
}
}
OR
if ( (abc & myType) && myValue )
{
// do something
}
A:
They are not equivalent, a "corrected" second one would be
if ( (abc & myType == myType) && myValue )
{
// do something
}
In this case, any decent compiler will emit the same code for both.
Also, it's almost never sensible to do this kind of micro-optimization - you waste time around a difference that will be at most of one or two assembly instruction, maybe even in a code path that isn't critical. Here, where there's no real difference in performance, the real optimization to do is towards clarity of your code.
Real optimization is about not caring about these micro-differences (which are probably already taken of by the compiler), and instead profiling the code to find the real bottlenecks.
A:
A few others have pointed out that the two are not equivalent for this reason:
if (abc & myType == myType )
{
if (myValue) {}
}
// OR
if ( (abc & myType) && myValue ) // missing myType == myType
{}
However there is a second reason the two are not equivalent: the == operator has higher precedence than the & operator (see this link). Your first expression therefore evaluates as follows:
if (abc & myType == myType) // Evaluates to (abc & true)
{
if (myValue) {}
}
You probably intended this:
if ((abc & myType) == myType) // Now the bitwise and happens before
// the comparison is made
{
if (myValue) {}
}
To avoid exactly this kind of bug, I always use parentheses to enforce precedence any time there is any possibility of ambiguity from a human's perspective (even though the compiler will never find it ambiguous), on the assumption that the reader has no clue what the actual precedences are. This has the added benefit of making the code easier to read.
|
[
"stackoverflow",
"0022005049.txt"
] | Q:
permission denied while trying to copy files from local server to remote server in ubuntu
I am working in a remote server,i need some files from my local server.I am using the following commands for copy files from local server to my remote server
rsync -v -e ssh /home/tanveer/myfilename username@server:/path-in-serve
but i am facing a 'Permission denied' exception.The Error is..
rsync: mkstemp "/home/.shutterstock.tar.gz.dIldLF" failed: Permission denied (13)
sent 10161405 bytes received 31 bytes 131115.30 bytes/sec
total size is 10160081 speedup is 1.00
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1070) [sender=3.0.9]
My question is that whether the command is right for copying files from local server to remote server?If it is ,how do i get permission to copy the files.
A:
Your command is correct, but I expect you are trying to copy the files to the wrong location. Have you tried copying the files to your home directory?
rsync -v -e ssh /home/tanveer/myfilename username@server:~
You can also shorten your command by leaving out the -e ssh which is normally set by default. You might also want to preserve the copied files' properties -a, copy symlinks as symlinks -l and limit your copying to a single partition -x:
rsync -valx /home/tanveer/myfilename username@server:~
One thing to look out for when using rsync is the effect of adding a trailing / to a source directory. Without a trailing / the directory will be copied as a directory, with the trailing / only its contents will be copied.
|
[
"pt.stackoverflow",
"0000178522.txt"
] | Q:
Problemas com sizeof
Estou tentando retornar o tamanho do array, mas está dando erro. O que fazer?
#include <stdio.h>
char *palavra[] = {"casa", "carro"};
int main(){
int i;
for(i = 0;i < sizeof(palavra);i++){ //Segmentation fault aqui.
printf(palavra[i]);
}
return 0;
}
A:
O erro não está nessa linha, está na debaixo, quando vai acessar o elemento. Acesso o elemento 0 e está ok, acesso o elemento 1 e está ok, quando vai acessar o 3 dá o erro. Porque está tentando acessar o 3? Por que o erro no cálculo errado do sizeof.
O sizeof pega o tamanho de todo o array, todo espaço ocupado na memória. No caso o array é do tipo ponteiro, e em arquitetura 32 bits possui o tamanho 4 bytes. Como são dois elementos, o array tem tamanho 8. O que você deseja é o tamanho 2. Então tem que dividir o tamanho do array pelo tamanho do elemento, assim dá o resultado esperado. 8 que é o tamanho total, dividido por 4 que é o tamanho do ponteiro, dá 2, que é o resultado correto.
#include <stdio.h>
int main() {
char *palavra[] = {"casa", "carro"};
for (int i = 0; i < sizeof(palavra) / sizeof(palavra[0]); i++) printf("%s", palavra[i]);
}
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
A:
sizeof retorna o tamanho da memoria alocada pelo ponteiro, não o numero dos elementos.
Pra percorrer com esse for voce precisa saber o numero de elementos do array e usar esse valor como condição de parada
#include <stdio.h>
char *palavra[] = {"casa", "carro"};
int tamanho = 2;
int main(){
int i;
for(i = 0; i < tamanho; i++){
printf(palavra[i]);
}
return 0;
}
|
[
"gaming.stackexchange",
"0000317006.txt"
] | Q:
Deus Ex: Mankind Divided. Cannot purchase Icarus Landing augmentation
I am currently at the start of M10 (Facing the Enigma), and I just realized that I cannot unlock the Icarus Landing augmentation (neither the Descent Velocity Modulator sub-aug). The augmentation is red and crossed-out. I'm currently at 100% System Status and have 8 Praxis points. Did I miss something? Is this a bug?
I'm playing on PS4.
A:
Without Koller installing the Neruoplasticity module, enabling experimental augmentations increases your overclock state. The only way to bring down the overclocking is to disable one of your regular augmentations. Disabling it prevents you from putting Praxis points into it, which leads to this state.
Once Koller is available to install the module, it should re-enable your Icarus Landing System, allowing you to put points into it.
|
[
"stackoverflow",
"0038724425.txt"
] | Q:
How do I apply column and row styles on a TableLayoutPanel programmatically?
In the beginning there is a TableLayoutPanel with only one row and no columns. By the press of a button I want this panel to be transformed with 5 rows and 3 columns.
private void button_Click(object sender, EventArgs e)
{
this.tableLayoutPanel1.ColumnCount = 3;
this.tableLayoutPanel1.RowCount = 5;
}
The problem is that you get this as a result!
The boxes that are created with the rows and columns do not contain the same area in the panel, as you can see.
In the case of 3 columns and 5 rows, the columns must share the 100% of the tablelayoutpanel, so 30% per each. In the case of 5 rows, each row must take 20%.
So I append to the button_Click method the next two lines of code.
this.tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));
this.tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 20F));
But I get the same result!
What I am missing?
A:
Probably you are adding styles to an already defined TableLayoutPanel without resetting the current styles.
tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Controls.Clear();
tableLayoutPanel1.ColumnStyle.Clear();
tableLayoutPanel1.RowStyle.Clear();
tableLayoutPanel1.RowCount = 5;
for(int x = 0; x < tableLayoutPanel1.RowCount; x++)
tableLayoutPanel1.RowStyles.Add(new RowStyle() { Height = 20, SizeType = SizeType.Percent });
tableLayoutPanel1.ColumnCount = 3;
for(int x = 0; x < tableLayoutPanel1.ColumnCount; x++)
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle() { Width = 33, SizeType = SizeType.Percent });
|
[
"stackoverflow",
"0060534897.txt"
] | Q:
Rounding mode from java Math package for .555 not works
How about my problem is the following, I am using the rounding mode to round and truncate some quantities but none of the enumerations works for the business rule that my client needs, I give as an example the following:
new BigDecimal(5.551).setScale(2, RoundingMode.[ENUM]) <-- DEberia regresar 5.55 OK
new BigDecimal(5.554).setScale(2, RoundingMode.[ENUM]) <-- DEberia regresar 5.55 OK
new BigDecimal(5.555).setScale(2, RoundingMode.[ENUM]) <-- DEberia regresar 5.55 It should be 5.56
new BigDecimal(5.559).setScale(2, RoundingMode.[ENUM]) <-- DEberia regresar 5.56 OK
I had used HALF_DOWN which was the closest one but I came across this case in which I have pure fives and so it didn't work anymore.
A:
Do it as follows:
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
System.out.println(new BigDecimal(String.valueOf(5.551)).setScale(2, RoundingMode.HALF_UP));
System.out.println(new BigDecimal(String.valueOf(5.554)).setScale(2, RoundingMode.HALF_UP));
System.out.println(new BigDecimal(String.valueOf(5.555)).setScale(2, RoundingMode.HALF_UP));
System.out.println(new BigDecimal(String.valueOf(5.559)).setScale(2, RoundingMode.HALF_UP));
}
}
Output:
5.55
5.55
5.56
5.56
|
[
"stackoverflow",
"0009966781.txt"
] | Q:
Trying to get the intValue of a textfield's text in the debugger
Why can't I print my text field's text's intValue in the debugger?
Printing description of textField:
<UITextField: 0x8e65550; frame = (87 11; 194 18); text = '2'; autoresize = W+RM+H+BM; tag = 5; layer = <CALayer: 0x8e64040>>
(lldb) po textField.text.intValue
error: property 'text' not found on object of type 'UITextField *'
error: 1 errors parsing expression
(lldb) po textField.text
error: property 'text' not found on object of type 'UITextField *'
error: 1 errors parsing expression
(lldb) po textField
(UITextField *) $15 = 0x08e65550 <UITextField: 0x8e65550; frame = (87 11; 194 18); text = '2'; autoresize = W+RM+H+BM; tag = 5; layer = <CALayer: 0x8e64040>>
A:
The syntax you can use in the debugger isn't always exactly the same as the syntax you'd use in your source, and LLDB is still a work in progress. The double use of dot syntax seems to be confusing it. Try using bracket syntax:
(lldb) po [[textField text] intValue]
|
[
"stackoverflow",
"0021919522.txt"
] | Q:
App Crash when I Add a Button - has both the Button AND a listview in Activity
My application has one activity, and its corresponding java code extends Activity. The XML has a button and a listview inside it. Each button can be clicked to go to another activity (which I have not finished that part yet).
99% of my code works, except when I "findViewById" my button, the application completely crashes. If I erase this line, then the application works fine (except for the fact that my button would then be useless).
My XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="@+id/bAddLexicon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/new_pic"
android:contentDescription="New Lexicon"/>
</LinearLayout>
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"></ListView>
</LinearLayout>
My Java Code:
package com.example.lexicav1;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class ListLexica extends Activity {
ListView listview;
Button createLexicon;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listlexica);
listview = (ListView) findViewById(android.R.id.list);
//THE FOLLOWING LINE MAKES MY APP CRASH,
//IF I ERASED THIS ONE LINE IT WOULD WORK BUT THEN
//I WOULD NOT BE ABLE TO DO ANYTHING WITH THE BUTTON???
createLexicon = (Button) findViewById(R.id.bAddLexicon);
List<String> items = new ArrayList<String>();
items.add("Lexicon 1");
items.add("Lexicon 2");
items.add("Lexicon 3");
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
//to change later
Intent intent = new Intent("android.intent.action.booklistactivity");
startActivity(intent);
}
});
}
}
A:
Type cast button to ImageButton
Current you are casting to Button
|
[
"softwareengineering.stackexchange",
"0000200796.txt"
] | Q:
How is dependency injection not just moving the complexity into a separate class?
I've been looking into using the Typhoon framework for dependency injection this week. I get that separating the construction of objects is beneficial for replacing arbitrary components with mocks during unit testing, and so far I have seen benefits from this alone.
But I cannot help but think that where before I had a humongous view controller class that had tens of header imports, I now have a humongous factory class that has tens of header imports. Am I supposed to avoid having a massive factory class?
A:
Dependency Injection simply helps define how one object knows about another dependent object. It is not going to help you reduce the overall complexity of the system. If you needed tens of import before DI, you will still need tens of imports after. The difference is that these imports will be in a location (class) that makes more sense (factory, builder, etc).
By allowing dependencies to be provided through a constructor or method you allow yourself the flexibility to supply a different, yet still valid, dependent object to your class and increase cohesion of said class by removing concerns.
There are several principles that are similar and are often used together: Dependency Injection (DI), Inversion of Control (IoC), and the Dependency Inversion Principle (DIP)
From this article
http://martinfowler.com/articles/dipInTheWild.html
DI is about wiring, IoC is about direction, and DIP is about shape
A:
Dependency injection does not reduce complexity, but it increases manitainability through separation of concerns and reduced coupling.
But I cannot help but think that where before I had a humongous view controller class that had tens of header imports, I now have a humongous factory class that has tens of header imports. Am I supposed to avoid having a massive factory class?
You're supposed to avoid "humongous" classes, period. So let's say you split up the view controller into smaller, more maintainable classes. Now all of them are responsible to get hold of their dependencies. DI helps you to move this dependency management from all of those classes into a factory/configuration class which is only responsible for dependency management - see Single Responsibility Principle. And while it will certainly be much less "humongous" than the original view controller, if it gets too big you always have the option to split it into smaller dependency-management classes that are responsible for different parts of the application.
|
[
"stackoverflow",
"0015039375.txt"
] | Q:
flexUnit pure AS3 IntelliJ
Is it possible to have FlexUnit 4.1 in IntelliJ with project set up as Pure AS3 which meens no Flex Runner.
What I get is an error
Error #1065: Variable mx.core::FlexVersion is not defined.
ReferenceError: Error #1065: Variable mx.core::FlexVersion is not defined.
But if I uncheck the Pure AS3 from module setting everything works.
The reason why I check pure AS3 is that I dont get Flex completion, and possible there are reasons that I still dont know.
A:
I assume your inspiration is running it on a continuous integration system like Hudson, Bamboo, or TeamCity.
You need a windowing environment, but there are some workarounds to provide one.
Look at this FlexUnit Wiki:
http://docs.flexunit.org/index.php?title=Continuous_Integration_Support
|
[
"stackoverflow",
"0035270156.txt"
] | Q:
reading/writing variables from text files to variables
I need to make a system for storing customer information and all quotations to an external file as well as entering more customers, listing customers, and the same with the quotations. As well as this I need to link all quotations/customers to an ID. I basically need to do SQL in java. However, I really need help with my input and output system, and writing all info to an array. I have got two main pieces of code but they are very inefficient and I need some suggestions, improvements or an entirely different system.
Input from file Code:
import java.io.*; //import classes
import java.util.ArrayList;
import java.util.Iterator;
public class MyTextReader{
public static void main(String[] args){
String myDirectory = System.getProperty("user.dir");
String fullDirectory = myDirectory + "\\myText.txt";
String input_line = null;
ArrayList<String> textItems = new ArrayList<String>(); //create array list
try{
BufferedReader re = new BufferedReader(new FileReader(fullDirectory));
while((input_line = re.readLine()) != null){
textItems.add(input_line); //add item to array list
}
}catch(Exception ex){
System.out.println("Error: " + ex);
}
Iterator myIteration = textItems.iterator(); //use Iterator to cycle list
while(myIteration.hasNext()){ //while items exist
System.out.println(myIteration.next()); //print item to command-line
}
}
}
Output to File
import java.io.FileWriter; //import classes
import java.io.PrintWriter;
public class MyTextWriter{
public static void main(String[] args){
FileWriter writeObj; //declare variables (uninstantiated)
PrintWriter printObj;
String myText = "Hello Text file";
try{ //risky behaviour – catch any errors
writeObj = new FileWriter("C:\\Documents\\myText.txt" , true);
printObj = new PrintWriter(writeObj);//create both objects
printObj.println(myText); //print to file
printObj.close(); //close stream
}catch(Exception ex){
System.out.println("Error: " + ex);
}
}
}
A:
For reading text from a file
FileReader fr = new FileReader("YourFile.txt");
BufferedReader br = new BufferedReader(fr);
String s="";
s=br.readLine();
System.out.println(s);
For Writting Text to file
PrintWriter writeText = new PrintWriter("YourFile.txt", "UTF-8");
writeText.println("The first line");
writeText.println("The second line");
writeText.close();
|
[
"stackoverflow",
"0013827805.txt"
] | Q:
serialize and unserialize $_session['cart']
I have a shooping cart and I would like to save the $_SESSION['cart'] which contains the $product_id => $quantity of the products that the user have choosen.
For example:
[cart] => Array
(
[366] => 2000
[215] => 456
)
First I serialize the $_SESSION['cart'] before I INSERT IT in my data base.
<?php
if($_SESSION['cart'])
{
$pedido= serialize($_SESSION['cart']);
}
?>
$sql1="insert into pedido(orden) values ('$pedido')";
Now in a different page I want to view the $_SESSION['cart']. So I use:
$sql2 = "SELECT orden FROM pedido where id_pedido = '$ID'";
$rs2 = mysql_query($sql2, $conexio) or die("Error al consultar: ".mysql_error());
$row2 = mysql_fetch_row($rs2);
$id_usuario=$row2[0];
$_SESSION['cartguardado']= unserialize($id_usuario);
I know that In this last step I am doing something wrong. Any body could help me and help me finding the mistake?
A:
Try to output $row2
$sql2 = "SELECT orden FROM pedido where id_pedido = '$ID'";
$rs2 = mysql_query($sql2, $conexio) or die("Error al consultar: ".mysql_error());
$row2 = mysql_fetch_row($rs2);
print_r($row2);
$id_usuario=$row2[0];
$_SESSION['cartguardado']= unserialize($id_usuario);
if $row2[0] is empty so something wrong with your data
|
[
"stackoverflow",
"0048166238.txt"
] | Q:
open.spotify.com redirected you too many times
Today I was starting a web app I am developing that embeds a Spotify widget player in an iframe. Strangely it doesn't load the widget and instead reports this message
"open.spotify.com redirected you too many times"
I went to Spotify Widget examples page and it shows the same behaviour (here's a ).
I cleaned the the cache, cookies, but it doesn't seem to sort this. Should I assume there is an API request threshold that I've just hit?
Has anyone have had the same problem and has solution?
Thanks
A:
That was a temporary issue in our service. It's resolved now.
|
[
"math.stackexchange",
"0000753917.txt"
] | Q:
Quotient of group schemes and its rational points.
At the moment I have some difficulties in understanding the quotient of group schemes and so exact sequences. I am aware that precise answers would be difficult to be given without speaking of sheaves over categories, that is why I am just looking for the idea behind. In particular I have the following questions.
If $k$ is a field, $F$ a field extending $k$, and
$$1\longrightarrow H\longrightarrow G\longrightarrow K\longrightarrow 1$$
is an exact sequence of group schemes over $k$. Is it true that then
$$1\longrightarrow H(F)\longrightarrow G(F)\longrightarrow K(F)\longrightarrow 1$$
is an exact sequence of groups?
What is the relation between $G/H$ and $K$?
And what can we say about $(G/H)(F)$, $G(F)$ and $H(F)$? I mean, is there something like $(G/H)(F)=G(F)/H(F)$ or $(G/H)(F)\simeq G(F)/H(F)$ holding?
Thank you.
A:
The exactness of $1\to H\to G\to K$ means $H\to G$ induces an isomorphism from $H$ to the kernel of $G\to K$ which is the fibere product $G\times_K \{1_K\}$. The exactness of $G\to K\to 1$ means $G\to K$ is faithfully flat. This is equivalent to $G\to K$ is surjective when $G, K$ are smooth over $k$.
For any field extension $F/k$,
$$ 1\to H(F)\to G(F) \to K(F)$$
is exact because $(G\times_K \{1_K\})(F)=G(F)\times_{K(F)} \{ 1_K\}$ by the universal product of fiber product. This exactness can also be seen directly.
If moreover $F$ is algebraically closed, $G(F) \to K(F)\to 1$ is also exact at least if your group schemes are of finite type over $k$. This is because $G\to K$ is a surjective morphism.
However, for a general extension $F/k$, $G(F) \to K(F)\to 1$ is not exact in general. If $F$ is perfect, we can use Galois cohomology to bound the cokernel:
$$ 1\to H(F)\to G(F) \to K(F) \to H^1(F, H(F^{alg})). $$
To give an example example of non-exactness at right, fix an odd integer $n\ge 3$ and consider the Kummer exact sequence for the multiplicative group $\mathbb G_m$ over $k=\mathbb Q$:
$$ 1\to \mu_n \to \mathbb G_m \xrightarrow{()^n} \mathbb G_m \to 1 $$
where $\mu_n$ is the group of the $n$-th roots of unit and the second map is the power $n$ map. When you take rational points over $\mathbb Q$, you get
$$ 1\to 1 \to \mathbb Q^* \xrightarrow{()^n} \mathbb Q^*$$
where the last map the power $n$ map. It is of course not surjective.
Finally, $G/H=K$ by definition, and $G(F)/H(F)$ is a subgroup of $K(F)$, not equal to $K(F)$ in general by the above example.
|
[
"stats.stackexchange",
"0000459408.txt"
] | Q:
How to test for significant difference between 2 linear regression models?
The following scatterplot represents the Number of Users in a website against Number of Day.
After the first month, on day number 31, a campaign was launched and the users went slightly up.
I fitted a linear regression model for the first month, and then a second one for the second month.
So my questions are:
Is this uplift the result of a better campaign or is the result of the already existing trend? In other words, is the difference between the two slopes significantly different or not? What about the intercepts? How can I compare the 2 models?
What is a big enough sample to fit the models before and after the campaign launch?
Are there any other methods besides linear regression models? Maybe a T-test or an Anova model?
For anyone that wants to reproduce the scatterplot and the models, the dataset I used was this one:
Day_Number Users Campaign
1 114 0
2 151 0
3 155 0
4 157 0
5 143 0
6 188 0
7 143 0
8 181 0
9 224 0
10 155 0
11 223 0
12 247 0
13 210 0
14 184 0
15 231 0
16 255 0
17 292 0
18 245 0
19 254 0
20 246 0
21 343 0
22 329 0
23 284 0
24 287 0
25 338 0
26 341 0
27 352 0
28 358 0
29 350 0
30 362 0
31 503 1
32 582 1
33 524 1
34 400 1
35 285 1
36 559 1
37 648 1
38 392 1
39 642 1
40 665 1
41 631 1
42 789 1
43 459 1
44 625 1
45 586 1
46 854 1
47 818 1
48 670 1
49 594 1
50 672 1
51 919 1
52 900 1
53 960 1
54 899 1
55 1046 1
56 901 1
57 759 1
58 813 1
59 923 1
60 887 1
A:
Are you currently using Campaign in your model, or are you just using it as a way to divide your data to fit two models? Right now, it looks like you are fitting two separate versions of
\begin{equation}
\text{Users} = \beta_0 + \beta_\text{1}\text{Day}
\end{equation}
Testing for differences in the models shouldn't be difficult if you nest them. If you use Campaign as a second predictor in your model, you can determine whether there is a significant difference in the intercepts based on whether Campaign is significant. Because Campaign is 0 or 1, that term will be an additional constant that is added depending on whether the campaign is happening or not.
\begin{equation}
\text{Users} = (\beta_0 + \beta_2\text{Campaign})+ \beta_\text{1}\text{Day}
\end{equation}
If you add a Campaign x Day interaction, then that can tell you whether there is a significant difference in your slopes. Similar to the equation above, when the campaign is happening, your slope will change from beta_1 to (beta_1 + beta_12)
\begin{equation}
\text{Users} = (\beta_0 + \beta_2\text{Campaign}) + (\beta_\text{1}+ \beta_{12}\text{Campaign})\cdot\text{Day}
\end{equation}
|
[
"stackoverflow",
"0035494716.txt"
] | Q:
Insert C++ vector by "replacing" the iterator at the insertion point (with a complication)
Is there a simple way to add a vector into another vector, and to delete
the iterator at the insertion position afterwards (practically "replacing the iterator" with a new vector)?
What i wish to do is (read comment in Code):
struct Data
{
Data(int i) :d(i) {}
vector<Data> vec;
int d;
};
vector<Data> dataVector = { Data(1), Data(2), Data(3) };
dataVector[1].vec = { Data(41), Data(42) };
// Task: replace Data(2) in dataVector with dataVector[1].vec to get {Data(1),Data(41),Data(42),Data(3)};
for (auto it = dataVector.begin(); it != dataVector.end();) {
if ((*it).d == 2) {
it = dataVector.insert(it,(*it).vec.begin(),(*it).vec.end());
// Now delete Data(2) somehow
// it = dataVector.erase(...
}
else it++;
}
is there an elegant way to achieve this without incrementing "it" n times or using additional variables?
In general I would have vectors of arbitrary length, and I would prefer to add append the new vector at the end, but that is not crucial.
A:
I just found a solution:
it = dataVector.insert(it+1,it->vec.begin(),it->vec.end());
it = dataVector.erase(it-1);
Maybe it is not the best one, but it seems to work even for insertinf at the beginning/end of the vector. Thanks for your help!
|
[
"stackoverflow",
"0014375753.txt"
] | Q:
Parse object dot notation to retrieve a value of an object
I'm finding myself struggling with a little problem.
Let's say I've got an object:
var foo = {
bar: {
baz: true
}
};
Now I also have a String 'foo.bar.baz'. I'd now like to retrieve the value from the object using the string.
Please note: This is just an example, the solution needs to be dynamic.
Update:
I need the variable name also to be dynamic and parsed from the string. Also I can't be sure that my variable is a property of the window.
I have already built a solution using eval, but this is pretty ugly I think:
http://jsfiddle.net/vvzyX/
A:
For example,
function get(obj, path) {
return path.split('.').reduce(function(obj, p) {
return obj[p]
}, obj);
}
Demo:
tree = {
foo: {
bar: 1,
baz: { quux: 3 },
},
spam: 1
}
console.log(get(tree, 'foo.baz.quux')) // 3
A:
Here is how you can do this:
function getValue(namespace, parent) {
var parts = namespace.split('.'),
current = parent || window;
for (var i = 0; i < parts.length; i += 1) {
if (current[parts[i]]) {
current = current[parts[i]];
} else {
if (i >= parts.length - 1)
return undefined;
}
}
return current;
}
var foo = {
bar: {
baz: true
}
};
console.log(getValue('foo.bar.baz')); //true
The first argument of the function is the namespace (dot separated values) and the second one is the parent object, if parent is not provided then window is used.
One more example using the parent argument:
var str = 'foo.bar.baz';
foo = {
bar: {
baz: true
}
};
result = getValue(str, foo);
console.log(result);
Here is an example in jsfiddle.
Similar approach is used in YUI. Their approach is called Namespace pattern. The main benefit is simulation of packages/namespaces. The only difference between this script and the namespace pattern is that the namespace function creates nested structure instead of only returning value.
|
[
"security.stackexchange",
"0000054967.txt"
] | Q:
Are there any exploits that would allow a user to "spoof" a screen capture system?
We have a security system installed that takes pictures of the client user's screen and sends them to a server. The pictures are saved until they get to the point where they are old enough to be deleted. It's been useful for an investigative tool when we need to find out if a user has been up to suspicious activity. The majority of our users on our network are standard user accounts with no special access. With our machines being primarily Windows 7.
As an administrator of this system, I was wondering if this can potentially be "spoofed". As in, a user can exploit the client to send pictures of what he/she desires.
Edit : I'm referring to the user being able to exploit the system and send the image they want sent while doing something else. I'm not referring to being able to create a window in full screen mode.
A:
Yes, long as the user of the computer gains appropriate access to write to memory of your capturing software.
The attacker could use API hooking to spoof the screenshot.
http://www.codeproject.com/Articles/30140/API-Hooking-with-MS-Detours
Just same method used in malware and gamehacking.
You'll want to ensure the user doesn't gain administrator rights and can't use OpenProcess API on your protected processes.
|
[
"stackoverflow",
"0029693186.txt"
] | Q:
Translatable Manytomany fields in admin generate many queries
I am using django-parler (a derivative of django-hvad) for translations. In admin when displaying Foreignkey fields with manytomany relationship, django runs a single query for each:
So when there are 300 services there would be as many queries.
I think the prefetch_related on get_queryset doesn't apply to mantomany filters/lists, correct me if I am wrong:
def get_queryset(self, request):
return super(DoctorAdmin, self).get_queryset(request).prefetch_related('translations', 'services__translations')
has no effect on number of queries. Enabling caching on parler (as the author suggested here) also does not help since the same queries are not repeated but each item on those filters is called in a query for translated items (IDs are different each time). So, what I am looking for is a select_related/prefetch_related on inner filters. I will also review your apps meanwhile, in case you have solved such problem already.
A:
In the hope of being useful for some others, here is how I solved the problem, reducing the queries from 2k to 30 in the admin:
class MyModelAdminForm(TranslatableModelForm):
class Meta:
model = MyModel
exclude = ()
def __init__(self, *args, **kwargs):
super(MyModelAdminForm, self).__init__(*args, **kwargs)
self.fields['services'].queryset = Service.objects.prefetch_related('translations').all()
class MyModelAdmin(TranslatableAdmin):
form = MyModelAdminForm
So, override the form, and once inside, override the queryset with prefetch.
|
[
"stackoverflow",
"0049238099.txt"
] | Q:
Inject varables in css, html, js with Webpack
I have problem, that in my project I use constants, variables in css, html, js and if I wanna something change some constants I need find it in html or css or js, that take long time. And wonder if it possible have separate js file with variables and constants, and inject value from that to html, js, css (sass). Pseudocode below. I wanna know, is even possible do with webpack, if yes, how or where I should look?
document.getElementById(${=name}).style.color = 'white';
.box {
width: ${=width}
}
<div class="box box_${=id}">
Some text
</div>
const css = {
width: '250px',
};
const html = {
id: '2'
};
const js = {
id: 'haha',
};
A:
You can use a webpack plugin for doing all replacement.
for instance:
https://github.com/jamesandersen/string-replace-webpack-plugin
It can replace in any files you want...
for JS (for instance) you would have something like:
module: {
loaders: [
// configure replacements for file patterns
{
test: /.js$/,
loader: StringReplacePlugin.replace({
replacements: [
{
pattern: /DEFAULT_WIDTH/ig,
replacement: function () {
return '100px';
}
}
]})
}
]
},
|
[
"stackoverflow",
"0035737029.txt"
] | Q:
how to generate output for multi-plots within a loop in shiny app?
very simple question: I want several barplots in output,
for example: I have a dataset: data and a list of customer: cname
shinyServer(function(input, output){
for(name in cname){
output[[name]] <- renderPlot({
bp<-barplot(data[data$customer==name,1])
})
}
}
But it doesn't work, it seems the loop is not fully executed, need someone's help here.
A:
So the problem you seem to be running into is related to delayed evaluation. The commands in renderPlot() are not executed immediately. They are captured and run when the plot is ready to be drawn. The problem is that the value of name is changing each iteration. By the time the plots are drawn (which is long after the for loop has completed), the name variable only has the last value it had in the loop.
The easiest workaround would probably be to switch from a for loop to using Map. Since Map calls functions, those functions create closures which capture the current value of name for each iteration. Try this
# sample data
set.seed(15)
cname <- letters[1:3]
data <- data.frame(
vals = rpois(10*length(cname),15),
customer = rep(cname,each=10)
)
runApp(list(server=
shinyServer(function(input, output){
Map(function(name) {
output[[name]] <- renderPlot({
barplot(data[data$customer==name,1])
})
},
cname)
})
,ui=
shinyUI(fluidPage(
plotOutput("a"),
plotOutput("b"),
plotOutput("c")
))
))
|
[
"stackoverflow",
"0012502386.txt"
] | Q:
jQuery blur doesn't work at IE8 and IE7
I have the following code:
jQuery(document).ready(function ($) {
// ...
Sys.Application.add_load(function () {
$(".RadGrid td > .RadInput.RadInput_Default > .riTextBox.riEnabled").each(function () {
$(this).val($(this).val().replace(/,/g, ""));
});
$(".RadGrid td > .RadInput.RadInput_Default > .riTextBox.riEnabled").blur(function () {
$(this).val($(this).val().replace(/,/g, ""));
});
});
}
The reason I have written this code is that I'm using Telerik RadGrid which has some autogenerated columns and a column filter, which formats the value of integer column filter values. For example 1000000 becomes 1,000,000. It works fine, but I have to get rid of the formatting because it bothers some people. Essentially the HTML elements we are talking about are inputs and they are modified by telerik and can be found with the selector you see in the code. I want to make sure that the users will never see comma in these inputs. My code works well in google Chrome, FF and IE9, but it fails to work with IE8 and IE7. In fact after loading my page I don't see commas, however, if I edit them end focus out of the items, the commas appear. These issues are applicable only in IE8 and IE7. How can I fix my code to work in Chrome, FF, IE9, IE8 and IE7?
Thank you in advance for any help.
Best regards,
Lajos Árpád.
A:
From the JQuery documentation:
The blur event is sent to an element when it loses focus. Originally,
this event was only applicable to form elements, such as <input>. In
recent browsers, the domain of the event has been extended to include
all element types.
So if, as I guess, riTextBox is a class of some span containing an input, this should work:
$(".RadGrid td > .RadInput.RadInput_Default > .riTextBox.riEnabled input")
.blur(function () {
$(this).val($(this).val().replace(/,/g, ""));
});
|
[
"stackoverflow",
"0035887269.txt"
] | Q:
Implementing Tabs in Android
I like to check I am doing the right thing or is there a better way than this.
I like to implement tabs in Android application. I found out that I should use Fragment.
Then I implemented my application with TabbedActivity.Inside I added in Tabs.
I have added Tab in the onCreate() of the MainActivity as
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Accelerometer"));
tabLayout.addTab(tabLayout.newTab().setText("Gyroscope"));
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
Since I want to use two xmls for two different fragments (frangment1.xml and frangment2.xml), I created two blank fragments and inside PlaceholderFragment class's, I added frangment1.xml and frangment2.xml using cnt variable
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static int cnt = 0;
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
if(cnt== 0) {
rootView = inflater.inflate(R.layout.tab_fragment1, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.frag1);
cnt++;
}else if(cnt== 1){
rootView = inflater.inflate(R.layout.tab_fragment2, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.frag2);
}
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
I like to check is that the correct way or any other better way for that.
A:
Hey there is not much to say about this code. I have not tried to run your code. But if it run for you its fine. Even I use to do this type of Tabs implementation in android. But since there are many changes from then as per the new android design library. There are tons of new features, not just in designs but also in functionalities. You might wanna check this link for some of them being implemented here.
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
Also for guidelines from google on tabs, their implementations, specifications and all that stuff check this out.
https://www.google.com/design/spec/components/tabs.html#tabs-usage
|
[
"stackoverflow",
"0004705515.txt"
] | Q:
Sphinx search within attribute collection
Is there a way of searching in Sphinx within a collection of attributes?
I've got a property (as in building, not attribute) which among other attributes, has a collection of facilities, e.g. pool, wifi.
Each property has multiple facilities
A:
Figured it out, you have to use "multi" attribute, see attached xmlpipe2 doc + php search example
<?xml version="1.0" encoding="UTF-8"?>
<sphinx:docset>
<sphinx:schema>
<sphinx:field name="capacity"/>
<sphinx:field name="region"/>
<sphinx:field name="facilities"/>
<sphinx:attr name="capacity" type="int"/>
<sphinx:attr name="region" type="int"/>
<sphinx:attr name="facilities" type="multi"/>
</sphinx:schema>
<sphinx:document id="94">
<capacity>37</capacity>
<region>12</region>
<facilities>
<attr>23</attr>
<attr>5</attr>
<attr>2</attr>
<attr>1</attr>
</facilities>
</sphinx:document>
</sphinx:docset>
PHP search:
$sp = new SphinxClient();
$sp->SetMatchMode(SPH_MATCH_ALL);
$sp->SetArrayResult(true);
$sp->SetServer('localhost', 3312);
$sp->SetFilter('facilities', array(23, 5));
$sp->Query();
|
[
"math.stackexchange",
"0002091097.txt"
] | Q:
Using Cartan decomposition to prove $SO(p,q)$ has two connected components
The lie group $SO(p,q)$ has two connected components. The one proof I know uses the transitive action of the group on a two sheeted hyperboloid (can be found on Onishchik and Vinberg book).
I am very confident that we can arrive at the same result by inspecting the Cartan decomposition of $SO(p,q)$.
Recall the Cartan decomposition says in short that given a real Lie subgroup $G$ of $GL_n(\mathbb{C})$ and $K= \{ g \in G : g= (g^*)^{-1} \}$, then the natural map $$ K \times \mathfrak{h} \longrightarrow G$$ $$(k, X) \mapsto k \exp(X),$$
where $\mathfrak{h}$ is the space of all hermitian elements of the Lie algebra of $G$, is a diffeomorphism.
In the case of $O(p,q),$ which has 4 connected components, the Cartan decomposition tells us that $$O(p,q) \simeq O(p) \times O(q) \times \mathfrak{h}$$, where $\mathfrak{h}$ denotes the space of symmetric matrices. Hence, since $O(n)$ has two connected components, it follows $O(p,q)$ must have 4 connected components. This decomposition arises by noting that we can identify $K$ with $O(p) \times O(q)$.
Applying the same reasoning to $SO(p,q)$, I verified we can identify the set $K$ with $SO(p) \times SO(q)$. However, $SO(n)$ is connected, and therefore the product $SO(p) \times SO(q) \times \mathfrak{h}$ is also connected.
Something is clearly escaping me. What have I done wrong?
A:
I think what went wrong is that for $SO(p,q)$ you cannot identify $K$ with $SO(p)\times SO(q)$, but with $S(O(p)\times O(q))=\{(A,B)\in O(p)\times O(q):\det(A)\det(B)=1\}$, which has two connected components. This is exactly the general version of the fact observed in the answer of @JohnHughes for $p=q=1$.
|
[
"arduino.stackexchange",
"0000038567.txt"
] | Q:
SoftwareSerial too slow for MIDI?
I tried to use the SoftwareSerial library for MIDI (by 47 effects), but it seems I get regularly corrupted/unexpected messages.
The circuit I'm using works perfectly when I connect it with the HardwareSerial solution (so the problem must lay in software).
What I see is:
When I press notes and release notes, LED 13 goes on and off correctly.
When I use Serial.print for debugging I get correct messages. However, in the example below I removed the print statements to have a minimal example).
When I use SoftwareSerial, LED 13 goes on and off for every note correctly. However, when I send many messages (for example by aftertouch/pitch bend which send a lot of messages in a short time), I noticed Note On/Off commands with 'random' values are sent.
Some sources say SoftwareSerial should work for MIDI, however, so far it is far from perfect. Do I make some mistake?
(btw, the baudrate of MIDI is 31.250 bps, when I use pitchband several hundreds of bytes per second are sent, so far within the MIDI spec).
The sketch I use is:
#include <MIDI.h> // Add Midi Library
#include <SoftwareSerial.h>
SoftwareSerial swSerial(2, 11); // RX, TX
MIDI_CREATE_INSTANCE(SoftwareSerial, swSerial, midiSw1);
#define LED 13 // Arduino Board LED is on Pin 13
void setup()
{
pinMode (LED, OUTPUT); // Set Arduino board pin 13 to output
midiSw1.begin(MIDI_CHANNEL_OMNI);
midiSw1.setHandleNoteOn(MyHandleNoteOn);
midiSw1.setHandleNoteOff(MyHandleNoteOff);
}
void loop()
{
midiSw1.read();
}
void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
digitalWrite(LED, HIGH); //Turn LED on
}
void MyHandleNoteOff(byte channel, byte pitch, byte velocity)
{
digitalWrite(LED, LOW); //Turn LED off
}
A:
The problem with SoftwareSerial is that while it is receiving a packet the Arduino is unable to do anything else - that includes reading bytes from the RX buffer, so it will easily overflow if you send things too rapidly. With HardwareSerial you are able to read from the buffer while it's receiving data, so overflowing is less of a problem.
As soon as the START bit of a packet is received it enters an ISR and reads each of the remaining 9 bits of data (including the stop bit) in a tight loop. That ISR doesn't exit until the whole packet has been received and stored in the RX buffer. If another byte is sent straight away there is little time between the ISR finishing and it being triggered again. The rest of the code, including the MIDI parsing routines which read data from the RX buffer, are then starved of CPU cycles and can't run properly. Send too many bytes together and the limited RX buffer (64 bytes) fills up and overflows, and you lose data.
Another issue with SoftwareSerial is that it has to capture the START bit at the moment it arrives. Any delay in capturing that edge will result in a drift in the bit sampling timing. If there is anything else that is using interrupts at the same time (such as the millis() timer) will delay the triggering of the PCINT interrupt used for the START bit detection. Even the SoftwareSerial interrupt itself has a certain amount of time after it has finished receiving the packet where it stores it in the RX buffer and returns from the interrupt routine. If the next packet arrives before the ISR is ready to service it there will be a delay - and any delay is bad.
Personally I am of the opinion that SoftwareSerial should never be used for anything, ever. If you need more serial ports then you either need a more powerful chip or you need more than one chip and get them communicating together through another higher speed hardware channel (SPI or I2C, for instance).
SoftwareSerial is only suitable for sending short bursts of data (since it blocks completely while sending) or receiving very short messages sent infrequently.
|
[
"stackoverflow",
"0003510964.txt"
] | Q:
Why is the 'this' keyword required to call an extension method from within the extended class
I have created an extension method for an ASP.NET MVC ViewPage, e.g:
public static class ViewExtensions
{
public static string Method<T>(this ViewPage<T> page) where T : class
{
return "something";
}
}
When calling this method from a View (deriving from ViewPage), I get the error "CS0103: The name 'Method' does not exist in the current context" unless I use the this keyword to call it:
<%: Method() %> <!-- gives error CS0103 -->
<%: this.Method() %> <!-- works -->
Why is the this keyword required? Or does it work without it, but I'm missing something?
(I think there must be a duplicate of this question, but I was not able find one)
Update:
As Ben Robinson says, the syntax to call extension methods is just compiler sugar. Then why can't the compiler automatically check the for extension methods of the current type's base types without requiring the this keyword?
A:
A couple points:
First off, the proposed feature (implicit "this." on an extension method call) is unnecessary. Extension methods were necessary for LINQ query comprehensions to work the way we wanted; the receiver is always stated in the query so it is not necessary to support implicit this to make LINQ work.
Second, the feature works against the more general design of extension methods: namely, that extension methods allow you to extend a type that you cannot extend yourself, either because it is an interface and you don't know the implementation, or because you do know the implementation but do not have the source code.
If you are in the scenario where you are using an extension method for a type within that type then you do have access to the source code. Why are you using an extension method in the first place then? You can write an instance method yourself if you have access to the source code of the extended type, and then you don't have to use an extension method at all! Your implementation can then take advantage of having access to the private state of the object, which extension methods cannot.
Making it easier to use extension methods from within a type that you have access to is encouraging the use of extension methods over instance methods. Extension methods are great, but it is usually better to use an instance method if you have one.
Given those two points, the burden no longer falls on the language designer to explain why the feature does not exist. It now falls on you to explain why it should. Features have enormous costs associated with them. This feature is not necessary and works against the stated design goals of extension methods; why should we take on the cost of implementing it? Explain what compelling, important scenario is enabled by this feature and we'll consider implementing it in the future. I don't see any compelling, important scenario that justifies it, but perhaps there is one that I've missed.
A:
Without it the compiler just sees it as a static method in a static class which takes page as it's first parameter. i.e.
// without 'this'
string s = ViewExtensions.Method(page);
vs.
// with 'this'
string s = page.Method();
A:
On instance methods, 'this' is implicitly passed to each method transparently, so you can access all the members it provides.
Extension methods are static. By calling Method() rather than this.Method() or Method(this), you're not telling the compiler what to pass to the method.
You might say 'why doesn't it just realise what the calling object is and pass that as a parameter?'
The answer is that extension methods are static and can be called from a static context, where there is no 'this'.
I guess they could check for that during compilation, but to be honest, it's probably a lot of work for extremely little payoff. And to be honest, I see little benefit in taking away some of the explicitness of extension method calls. The fact that they can be mistaken for instance methods means that they can be quite unintuitive at times (NullReferenceExceptions not being thrown for example). I sometimes think that they should have introduced a new 'pipe-forward' style operator for extension methods.
|
[
"stackoverflow",
"0001850618.txt"
] | Q:
Problems sending html email in php
I'm trying to send an email to myself that has a layout and images. What I'm I doing wrong?
<?php
$message = $_POST['message'];
$emailsubject = 'site.com';
$webMaster = '[email protected]';
$body = "
<html>
<body bgcolor=\"e7e7e7\">
<style type=\"text/css\">
#body {margin: auto;border: 0;padding: 0;font-family: Georgia, 'Times New Roman', Times, serif;font-size: 12px;}
#emailHeader {width: 500px;height: 131px;background: url(http://www.site.com/images/image.gif) no-repeat;}
#emailContent {width: 500px;background: url(http://www.site.com/images/image2.gif) repeat-y;text-align: left;padding: 0 33px 0 6px;}
#emailFooter {width: 500px;height: 34px;background: url(http://www.site.com/images/image3.gif) no-repeat;}
</style>
<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
<tr>
<td valign=\"top\" align=\"center\">
<table width=\"500\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
<tr>
<td id=\"emailHeader\"></td>
</tr>
<tr>
<td id=\"emailContent\">
content $message
</td>
</tr>
<tr>
<td id=\"emailFooter\"></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>"
$headers .= "Content-type: text/html\r\n";
$success = mail($webMaster, $emailsubject, $body, $headers);
if ($success) {
echo "Your message was sent.";
}
else{
echo "There was a error.";
}
?>
A:
You should use phpmailer instead of PHP's mail()-Function. It allows you to easily send HTML-Mails.
Besides that you can try to validate your HTML-Code to be compatible for emailing.
Best wishes,
Fabian
|
[
"pt.stackoverflow",
"0000390135.txt"
] | Q:
AttributeError: 'str' object has no attribute 'confidence'
Estou desenvolvendo um chatbot e gostaria que ele só respondesse se tivesse determinado nível de confiança na resposta.
# -*- codding: utf-8 -*-
import os
import telebot
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
bot = telebot.TeleBot("TEM UM CÓDIGO DO TELEGRAM AQUI")
#Futaba original
def bot_convencional(message):
chatbot = ChatBot("Futaba")
trainer = ListTrainer(chatbot)
for arquivos in os.listdir('arquivos'):
chats = open('arquivos/' + arquivos, 'r').readlines()
trainer.train(chats)
resposta = chatbot.get_response(message) #ESSE GET DENTRO DO IF DA ÚLTIMA FUNÇÃO
resposta = str(resposta)
mensagem = open("arquivos/teste", "w")
mensagem.write(resposta)
mensagem.close()
#Recebe e envia uma resposta inicial
@bot.message_handler(commands = ["help", "start"])
def enviar_mensagem(message):
bot.reply_to(message, "Hey")
#Recebe qualquer outra mensagem
@bot.message_handler(func=lambda message:True)
def mensagem(message):
bot_convencional(message.text)
resposta = open("arquivos/teste", "r")
resposta = resposta.read()
if float(resposta.confidence) > 0.5:
bot.reply_to(message, resposta)
else:
bot.reply_to(message, "Como você está se sentindo?")
bot.polling()
O problema é que quando eu tento usar o confidence dá o erro
if float(resposta.confidence) > 0.5:
AttributeError: 'str' object has no attribute 'confidence'
Já usei confidence em outro chatbot e não entendo porque está dando esse problema dessa vez. Alguém pode me ajudar?
Eu queria colocar o get.response da função bot_convencional dentro do if do mensagem.
A:
Para o confidence eu precisava a acessar o chatbot.get_response(message). Para isso, criei uma variável chamada corpus pra armazenar esse corpus = chatbot.get_response(message), tornei ela global e acessei pelo if do confidence.
FUNÇÃO QUE ARMAZENA O CHATBOT
def bot_convencional(message):
chatbot = ChatBot("Futaba")
trainer = ListTrainer(chatbot)
for arquivos in os.listdir('arquivos'):
chats = open('arquivos/' + arquivos, 'r').readlines()
trainer.train(chats)
resposta = chatbot.get_response(message)
resposta = str(resposta)
global corpus
corpus = chatbot.get_response(message)
mensagem = open("arquivos/teste", "w")
mensagem.write(resposta)
mensagem.close()
FUNÇÃO QUE RESPONDE AS MENSAGENS
#Recebe qualquer outra mensagem
@bot.message_handler(func=lambda message:True)
def mensagem(message):
bot_convencional(message.text)
resposta = open("arquivos/teste", "r")
resposta = resposta.read()
if float(corpus.confidence) > 0.5:
bot.reply_to(message, resposta)
else:
bot.reply_to(message, "Como você está se sentindo?")
bot.polling()
Eu não sei se isso é certo, mas funcionou.
|
[
"superuser",
"0000264126.txt"
] | Q:
iTunes is playing sound through wrong speakers
I have a Windows 7 laptop (Dell Inspiron) and I'm trying to simply listen to music through headphones. This process used to work flawlessly.
Something changed and now iTunes (as well as WMP and any other audio playing device) will not play through the headphones, which are plugged in. Instead, the music plays through the crappy laptop speakers.
The only thing I can see is that the music seems to be playing through the Speakers/Headphones playback device (seems reasonably named) but should be playing through the Independent R.T.C. Headphones, instead. This info comes from the Sound config area of the Windows 7 Control Panel.
The funny thing is that Skype uses my headphones just fine. I just don't know where to start looking to make sure the media players are using the correct audio when headphones are plugged in.
A:
Itunes --> Edit --> preferences --> play --> play audio with: windows audio session,
restart itunes and it will work again! :)
A:
It is generally a hardware function on the laptop itself that automatically routes sound through the headphones if they are connected.
Have you tried different headphones?
If so, update your system BIOS (download is usually available from the laptop makers webpage). Also, check your BIOS settings for any obvious issues.
If you have some sort of specialized audio driver (RealTek is a common one) it may have settings that determine how the audio auto-routing is handled. Check for any obvious settings regarding where sound is sent when headphones are detected.
Also, download the latest audio drivers from your laptop maker website and install them. Even if they are the same version as your current drivers, reinstalling them may reset the settings to the default you're expecting.
|
[
"stackoverflow",
"0017796815.txt"
] | Q:
Protecting fields from Reflection - The strange case of the System.security
I am currently looking into java security and came across a strange phenomenon. The SecurityManager in java is stored in the field "security" in java.lang.System. Interestingly, the field seems to be protected against reflective access, which does make sense, but as far as I know this field is the only one which is. So here is the example:
for(Field f : System.class.getDeclaredFields())
System.out.println(f);
outputs
public static final java.io.InputStream java.lang.System.in
public static final java.io.PrintStream java.lang.System.out
public static final java.io.PrintStream java.lang.System.err
private static volatile java.io.Console java.lang.System.cons
private static java.util.Properties java.lang.System.props
private static java.lang.String java.lang.System.lineSeparator
Interestingly: the field declared as
private static volatile SecurityManager security = null;
is not in the list, and sure enough a call to
System.class.getDeclaredField("security");
yields a NoSuchFieldException. As I couldn't find anything about this online, and I am pretty sure this field used to be accessible via reflection (see also, for example, this blog post from 2010 which describes accessing this field) I was wondering a) was this implemented as a quick fix to prevent easily disabling the securitymanager via reflection and b) how this is implemented (or rather is there any chance of protecting other private fields from reflection as well).
A:
A colleague pointed out that the answer is not in the jvm but in the jdk, more precisely in the class sun.reflect.Reflection. There you'll find a static initializer that does the following
static {
Map<Class,String[]> map = new HashMap<Class,String[]>();
map.put(Reflection.class,
new String[] {"fieldFilterMap", "methodFilterMap"});
map.put(System.class, new String[] {"security"});
fieldFilterMap = map;
methodFilterMap = new HashMap<Class,String[]>();
}
If we now look a bit closer at the getDeclaredFields method in java.lang.Class we'll find that the fields are filtered using a call to the Reflection class:
Reflection.filterFields(this, getDeclaredFields0(publicOnly));
where filterFields is implemented as
public static Field[] filterFields(Class containingClass,
Field[] fields) {
if (fieldFilterMap == null) {
// Bootstrapping
return fields;
}
return (Field[])filter(fields, fieldFilterMap.get(containingClass));
}
So .. this solves the issue how the field is protected. I am however still curious as to why this was implemented.
|
[
"stackoverflow",
"0060013891.txt"
] | Q:
Closing a UDP Socket when using Non-Blocking IO
The following code opens a socket, sets it to be non-blocking and sends some data over it using UDP, then closes the socket:
int fd = socket(PF_INET, SOCK_DGRAM, 0);
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
sendto(fd, str.c_str(), str.length(), 0,
(struct sockaddr*)&addr, sizeof(addr));
close(fd);
Is there any issue associated with closing the file descriptor as soon as the call to sendto() has completed given that it's non-blocking?
I'm also interested in any thread-safety considerations with doing the above in multiple threads concurrently?
A:
Is there any issue associated with closing the file descriptor as soon
as the call to sendto() has completed given that it's non-blocking?
No problems there -- once sendto() has returned (with a non-error return value), your data has been copied into a system buffer and can be considered "sent". Closing the socket will not prevent the data from going out.
I'm also interested in any thread-safety considerations with doing the
above in multiple threads concurrently?
No problems there either -- since there is no data-sharing across threads, there are no race conditions possible.
|
[
"raspberrypi.stackexchange",
"0000047027.txt"
] | Q:
Can the Pi camera module be used with a longer cable?
It appears the Raspberry Pi camera module v2 includes a 15cm ribbon cable, to connect it to the Pi. But I would like to have the camera sited further from the Pi, maybe a few metres away.
So can this cable be extended, or replaced with a longer cable? What sort of cable is required, and where can I get one? Is there any limit on the maximum cable length that will work?
A:
The length limits come from two requirements: signal quality, and signal delays. A 1m cable will introduce about 5ns of delay (speed of light in circuits is a lower than in vacuum!), so if you are running at 1GHz, there are five symbols in transit on that 1m cable. It this particular case it probably does not matter (it's more important that the signal paths are of exactly the same length), but this is the sort of consideration that most people won't think about.
The standard (at least what's open to the public: http://mipi.org/specifications/physical-layer) only mentions length considerations for M-PHY ("Distance: optimized for short interconnect (<10 cm) but extendable to a meter with good quality interconnect or even further with optical converters and optical waveguides"); D-PHY is a lot simpler, so it should have no problem with longer lengths as far as signal delays are concerned.
As @joan said, a long cable makes you more susceptible to interference from others. It also makes you more likely to interfere with other equipment, your neighbor's old analog TV, or maybe another pi on the next shelf with equally long cables. Hence my original admonition of keeping things as short and as straight as possible.
If you are thinking of shielding the flat cable with aluminum foil, you may or may not get a working cable: you will be adding a lot of capacitance, changing the transmission line characteristics.
I realize this is probably more detail than you needed, but someone may find it useful in the future :)
|
[
"stackoverflow",
"0038211239.txt"
] | Q:
Filter cells of multiple columns by one value Excel
I searched everything but could not find a solution to solve the following problem:
I have multiple columns and the cells of the columns can have the following values: Empty, "W", "A", "S"
And now I want to filter the rows by one cell - so if I put "W" into my "search-cell" there should be only the rows visible where there is the value "W" in one cell of the columns
So before filter:
And after filter:
Is this possible without vba ?
A:
This code is just for scott :P
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("F1")) Is Nothing Then
Application.ScreenUpdating = False
Dim lastRow As Long, varArr As Variant, val As String, rowArr(1) As Range, i As Long
val = LCase(Me.Range("F1").Value2)
Me.UsedRange.EntireRow.Hidden = False
If Len(val) Then
lastRow = Application.Max(Me.Cells(Me.Rows.Count, 1).End(xlUp).Row, _
Me.Cells(Me.Rows.Count, 2).End(xlUp).Row, _
Me.Cells(Me.Rows.Count, 3).End(xlUp).Row, _
Me.Cells(Me.Rows.Count, 4).End(xlUp).Row)
varArr = Me.Range("A1:D" & lastRow).Value2
For i = 3 To lastRow
If val = LCase(varArr(i, 1)) Or val = LCase(varArr(i, 2)) Or val = LCase(varArr(i, 3)) Or val = LCase(varArr(i, 4)) Then
If rowArr(0) Is Nothing Then
Set rowArr(0) = Me.Rows(i)
Else
Set rowArr(0) = Union(rowArr(0), Me.Rows(i))
End If
Else
If rowArr(1) Is Nothing Then
Set rowArr(1) = Me.Rows(i)
Else
Set rowArr(1) = Union(rowArr(1), Me.Rows(i))
End If
End If
Next
rowArr(0).EntireRow.Hidden = False
rowArr(1).EntireRow.Hidden = True
End If
Application.ScreenUpdating = True
End If
End Sub
(search field is F1 and case doesn't matter)
|
[
"stackoverflow",
"0026767782.txt"
] | Q:
understanding out.println in servlets
How in Servlets, out.println writes the html text to container's response object where normally in System.out.println() , it writes the text to the console??
This is creating a problem for me conceptually.
A:
Neither PrintStream nor PrintWriter is specified in terms of a console.
A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. PrintStream
Prints formatted representations of objects to a text-output stream. PrintWriter
They are both about formatting data and passing the formatted data to an output stream. Any output stream. By default, in certain environments, the PrintStream objects initially referenced by each of System.out and System.err send their data to some sort of console, but that is just those particular instances.
Even those can be changed. For example, it can be useful in some types of testing to replace System.out with a PrintStream that sends its data to a ByteArrayOutputStream.
|
[
"stackoverflow",
"0009292934.txt"
] | Q:
Finding files dynamically
I want to be able to repeat an action for every file in a directory.
This is my current code
File file = new File("res\\thing.csv");
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
Dat = new ArrayList<String>();
String line;
try {
while((line = reader.readLine()) != null){
String[] values = line.split(",");
for(String s : values) {
Dat.add(s);
//System.out.println(String.valueOf(Dat));
}
}
}
catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
It then goes on to change the extracted variables before writing to a new file. How can I get this program to automatically do this for every file in a directory?
A:
File dir = new File("directoryName");
if(dir.isDirectory())
{
File filesList[] = dir.listFiles();
for(int i = 0; i < filesList.length; i++)
{
//do your processing here
}
}
|
[
"stackoverflow",
"0018477498.txt"
] | Q:
Qt own enum in class
I want to declare my own enum in a class in Qt and use it for signals and slots, but I get this error.
QObject::connect: Cannot queue arguments of type 'ClassA::MyEnum'
(Make sure 'ClassA::MyEnum' is registered using qRegisterMetaType().)
This is my source code:
ClassA.h
public:
enum MyEnum {
READING = 0,
STOPPED = 1,
FINISHED = 2
};
signals:
void changed(QString text, int readTextInPercent, ClassA::MyEnum status);
ClassA.cpp
emit changed(QString("string"), 50, ClassA::READING);
ClassB.h
public slots:
void changed(QString text, int readTextInPercent, ClassA::MyEnum status);
ClassB.cpp
this->connect(m_ClassA, SIGNAL(changed(QString, int, ClassA::MyEnum)), this, SLOT(changed(QString, int, ClassA::MyEnum)));
void ClassB::changed(QString text, int readTextInPercent, ClassA::MyEnum status) {
}
I don't know where and with which parameter I have to put the qRegisterMetaType.
A:
You have to do:
Q_DECLARE_METATYPE(ClassA::MyEnum)
in your classA.h header.
Then in ClassA constructor (or main() but remember to include classa.h there first):
qRegisterMetaType<ClassA::MyEnum>("ClassA::MyEnum");
Then use like:
connect(whatever, SIGNAL(whatever_uses_myenum(ClassA::MyEnum)), ..., ...)
A:
The error thrown by Qt is very descriptive:
Make sure 'ClassA::MyEnum' is registered using qRegisterMetaType()
So you will need to include this line:
qRegisterMetaType<ClassA::MyEnum>("ClassA::MyEnum");
In any part of your code in which you know it will be called. I use to include the qRegisterMetaType in the main function of my applications. I recommend you to take a look to the Qt Documentation about the topics: qRegisterMetaType & Q_DECLARE_METATYPE.
|
[
"stackoverflow",
"0029412888.txt"
] | Q:
converting a contourf() plot with grid on with matlab2tikz script
When I convert a counterf() plot with matlab2tikz it won't show me the grid. Even though I have set the grid on. In the MATLAB plot I can see the grid, but in the compiled Latex pdf I can't see it.
My MATLAB code:
contourf(v);
colorbar;
title('el. Potential V(x,y)');
grid on;
xlabel('x-Achse');
ylabel('y-Achse');
matlab2tikz('pic1.tikz');
in the MATLAB plot I see this:
and in the compiled LaTeX PDF I see this:
A:
At the moment (Apr. 2015), this behavior is not a feature in matlab2tikz yet. According to this bug report, it is known to the developers and as it seems they plan on adding this feature / removing this bug in the near future.
So as for now, you can either wait for the addition of this feature to matlab2tikz, add it to matlab2tikz yourself and create a pull-request on Github, or manually add the grid to the generated TikZ file.
|
[
"pt.stackoverflow",
"0000073209.txt"
] | Q:
Firebird - função para casas decimais e milhar
Existe alguma função nativa do Firebird que me retorne o formato moeda igual ao brasileiro ou alguma stored procedure que faça esse serviço.
Exemplo: #.###,##
O ponto seria as casas milhar, milhões etc.
A virgula seria as casas decimais, no caso queria que retornasse duas
No mysql seria assim:
select format(<atributo>,2,'de_DE')
A:
Tenta esse cast(tb.SEU_FIELD AS NUMERIC(15,4)) as Saldo ou
cast( replace(tb.SEU_FIELD,',','.') as decimal(18,4))
Esses são os únicos modos que sei para formatar os números.
|
[
"stackoverflow",
"0003967359.txt"
] | Q:
What can be passed in (void *)context?
I'm doing some UIView animation stuff using
[UIView beginAnimations:nil context:nil];
// ... Animation configuration ...
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationEnded:finished:context:)];
[UIView commitAnimations];
Regarding the following question: Apple rejected app because of animationDidStop:finished:context: is a non-public api
I implemented my own method as the "setAnimationDidStopSelector".
My question is regarding the context:(void *)context parameter. Apple defines it as follow :
Additional application-supplied
information that is passed to the
animation delegate messages—the
selectors set using the
setAnimationWillStartSelector: and
setAnimationDidStopSelector: methods.
I'm wondering what king of thing can be passed in as a context. I'm relatively new to Objective-C and C programming and a bit lost with the void* type.
Can we pass in any sort of argument, objects, NSDictionnary, NSString, etc.
Thanks
A:
void * is a pointer to anything. You can pass a pointer to any object or to other stuff such as a struct or a Core Foundation opaque type. To get rid of the compiler warning, cast the pointer to void *:
... context:(void *)myDictionary];
Be aware that the method has no idea what context contains and thus will not retain it or otherwise care for correct memory managemnet. You have to ensure that the thing you pass to context still exists when the animation delegate methods are called.
|
[
"stackoverflow",
"0016810222.txt"
] | Q:
Change Title and/or Snippet of Marker dynamically?
How to change the Title and/or Snippet property of an Marker dynamically ?
A:
There are methods to do that in the API v2:
marker.setTitle(String title);
marker.setSnippet(String snippet);
|
[
"stats.stackexchange",
"0000312870.txt"
] | Q:
Does the likelihood function for the Poisson distribution integrate to 1
The above image shows a Poisson distribution for different values of the mean $\lambda$. If I was to fix a value of $k$ (say $k=3$) and sum over the different $\lambda$, is it true that $\sum_{\lambda}P(X=k| \lambda) = 1$?
If not, is there an obvious way to adapt this distribution so that this property is satisfied?
A:
Besides my comment, the claim is true if you replace the sum with an integral (which makes more sense). Indeed, one can show that for all $k \in \mathbb{N}$: $$\int_0^\infty P(X=k|\lambda)\,d\lambda = \int_0^\infty \frac{\lambda^kexp(-\lambda)}{k!}\,d\lambda = \frac{\Gamma(k+1)}{k!} = \frac{k!}{k!} =1.$$
In fact, the gamma function is already defined by $\Gamma(x) = \int_0^\infty \lambda^{x-1}\exp(-\lambda)\, d\lambda$. Moreover it is well known that $\Gamma(k+1) = k!$ if $k \in \mathbb{N}$.
|
[
"math.meta.stackexchange",
"0000027925.txt"
] | Q:
Is the [orientation] tag useful?
According to the tag description, the orientation is:
For question[sic] regarding the notion of orientation both in topology and in global analysis.
There is no further information in the tag wiki. A quick perusal of the first page of questions tagged with orientation (of which there are only 214) indicates that a fairly nontrivial percentage of them are not related to the orientation of manifolds or global analysis. For example:
Questions about the orientation of the boundary in Stoke's theorem: e.g. [1], [2], [3]
Questions about the orientation of vectors and othe related questions: e.g. [1], [2], [3], [4]
A question about graph theory
Since the tag lacks a decent description and seems likely to cause confusion rather than lend clarity, I would like to propose that this tag be gotten rid of. If it has any use, it is perhaps as a synonym of manifolds.
A:
The tag should be kept, but it requires a better description.
After two years, this question has attracted 8 upvotes and no downvotes (which seems to indicate a moderate consensus towards keeping the tag orientation, I guess?). In the comments, it was suggested that the real issue might be that the tag description is unclear. Yet no one has come forward to write a better description (again, I fee that I am unqualified to write this description).
Can someone qualified please step forward and take action to clarify the tag description?
|
[
"stackoverflow",
"0013905280.txt"
] | Q:
jqGrid - 'in' op not working for filters
I have a simple demo that gets a "greater-than" filter working on a table of test scores. The source can be found by clicking here. If you scroll down to var myfilter, you will see that I have one of the rules commented out.
var myfilter = {
groupOp: "AND",
rules: [
{field: 'score', op: 'gt', data: 70},
//{field: 'grade', op: 'in', data: [10, 11, 12]}
]
};
This rule says to only select rows for grades 10, 11, 12. However, when I uncomment this rule it doesn't work. In fact, it even breaks the table. Is this a bug, or am I going about it wrong?
To be clear, I simply want to find a way to use the op: 'in' feature. The jqGrid wiki on searching lists op: 'in' under the values for sopt, so there should be a way to do it...
A:
You are right. The current implementation of local searching don't support "in" operation. It uses just "eq" instead.
So I would suggest you to use block with "eq" operations instead of "in". The example from your question could be rewritten to the following:
var myfilter = {
groupOp: "AND",
rules: [
{field: 'score', op: 'gt', data: 70},
],
groups: [
{
groupOp: "OR",
rules: [
{field: 'grade', op: 'eq', data: 10}
{field: 'grade', op: 'eq', data: 11}
{field: 'grade', op: 'eq', data: 12}
]
}
]
};
See description of the full format of filters here.
|
[
"meta.stackoverflow",
"0000278756.txt"
] | Q:
Migration - what happens to answers and rep?
I recently answered a question relating to SNMP here.
However someone (validly) pointed out in the comments that because the poster hasn't specified that their question is relating to programming software that uses the SNMP protocol, that the question is more a sys-admin question and should be migrated:
"I know the question has already been answered, but I'd still argue that this is off-topic for Stack Overflow because it concerns system administration, not programming. The question and answers should be migrated to serverfault.com"
In the past when developing SNMP monitoring software I have benefited from SNMP information on Stack Overflow, but I do agree with the fact that this question, as written, isn't specific to programming.
I am not active on serverfault.com, and am wondering what actually happens to answers and rep when questions are migrated?
Note: In the case of this specific question, another user has also answered the question and their answer has been accepted in case that makes any difference to migration(?).
A:
On Stack Overflow, the question would be deleted, together with the reputation changes. For answers on a migrated post, deletion is instant, the question (now a stub) is deleted one month after the post is migrated.
On the target site, you'll gain reputation as votes are migrated along (the votes are re-cast by the Community User *). In essence, you get the same reputation (barring reputation caps). The accepted answer remains accepted.
There is a an exception for questions with a negative score; such questions start at 0 again on the target site. This is to off-set a "you asked this on the wrong site!" backlash, but this doesn't apply to any answers.
If you don't yet have an account on the target site, then the reputation for those votes is held until you create your account; as long as it uses the same login credentials as you use on Stack Overflow your account will automatically be associated.
Also see Do migrated questions migrate reputation and badges?
* Yes, this means that you can upvote a migrated post twice. Once on the source site, once again on the target site. In practice, this is not really much of a problem. See Migrated question's answers can be upvoted twice by the same user
|
[
"stackoverflow",
"0001826044.txt"
] | Q:
secure email form, header injection query
I'm using the following to clean up input from my contact form:
<?php
$name = strip_tags(stripslashes($_POST['name']));
//this is repeated for several other fields, then:
if(isInjected($name)) { die(); }
/* see isInjected function below */
// send the mail
?>
I'm using this function:
<?php
/* function from http://phpsense.com/php/php-mail.html */
function isInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str)) {
return true;
}
else {
return false;
}
}
?>
Is this sufficient to clean up my contact form?
thanks.
A:
As a side note that code is a little bloated. It can be trimmed down quite easily:
/* function from http://phpsense.com/php/php-mail.html */
function isInjected($str) {
$inject = "/(\r|\t|%0A|%0D|%08|%09)+/i";
return (preg_match($inject, $str) > 0);
}
A:
It seems prettey decent and better than average inputvalidation. Personanlly I also prefer handling inputtypes. In my basecontroller I have several functions to check wether input is a valid date of birth, emailaddress, etc. If you add such validation to your existing validation you're handling it well IMO.
|
[
"stackoverflow",
"0056227345.txt"
] | Q:
How to set up UncaughtExceptionHandlers for multiple bindings in spring kafka streams?
Right now, I'm trying to access the underlying kafka streams handle by following - https://cloud.spring.io/spring-cloud-static/Finchley.SR2/multi/multi__apache_kafka_streams_binder.html#_accessing_the_underlying_kafkastreams_object
Was wondering if there is a more idiomatic way to do this. Especially when there are mutliple bindings.
A:
You can call context.getBeansOfType(StreamsBuilderFactoryBean.class, false, false) to get a map of beanName:factoryBean.
However, you should be careful not to do this too early in the context lifecycle because you may cause premature bean instantiation.
Probably best to do it in a SmartInitializingSingleton.
|
[
"stackoverflow",
"0062068072.txt"
] | Q:
How to activate automatic angle bracket `<>` pairing completion in Visual Studio Code?
I just couldn't find out how to activate automatic angle bracket <> pairing in Visual Studio Code
like it exists for parentheses {}, round () or box [] bracket. Anyone has any clue, where in the setting I could configure this?
A:
There is no setting in vscode that allows you to change what is considered to be a bracket, like adding <>.
There is an issue Autoclosing pairs should be configurable that discusses this and you may wish to upvote it. In that issue, it is mentioned that you could edit the language configuration file to add your own "brackets" to the list. On Windows the javascript language configuration file is located at:
C: \Users\Mark\AppData\Local\Programs\Microsoft VS Code\resources\app\extensions\javascript\javascript-language-configuration.json;
as are the other languages (you don't say which language(s) you are interested in). Javascript doesn't normally support bracket matching for <> but I added that functionality by editing the file like so:
{
"comments": {
"lineComment": "//",
"blockComment": [ "/*", "*/" ]
},
"brackets": [
["<", ">"], // added
["{", "}"],
["{", "}"],
["[", "]"],
["(", ")"]
],
"autoClosingPairs": [
{ "open": "<", "close": ">" }, // added
{ "open": "{", "close": "}" },
{ "open": "[", "close": "]" },
{ "open": "(", "close": ")" },
{ "open": "'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "\"", "close": "\"", "notIn": ["string"] },
{ "open": "`", "close": "`", "notIn": ["string", "comment"] },
{ "open": "/**", "close": " */", "notIn": ["string"] }
],
"surroundingPairs": [
["<", ">"], // added
["{", "}"],
["[", "]"],
["(", ")"],
["'", "'"],
["\"", "\""],
["`", "`"]
],
"autoCloseBefore": ";:.,=}])>` \n\t",
"folding": {
"markers": {
"start": "^\\s*//\\s*#?region\\b",
"end": "^\\s*//\\s*#?endregion\\b"
}
}
}
and it works - after a reload, demo in javascript file:
Now, this file will be overwritten on updates so I would keep a copy around elsewhere with a pointer to its location.
The other option - not as nice, no surround feature for example, is to make a snippet with < as the prefix (in one of your snippets files).
"angle bracket": {
"prefix": "<",
"body": [
"<>"
],
"description": "complete angle bracket"
},
After you type < you will have to tab to complete it. this also works.
|
[
"stackoverflow",
"0023912894.txt"
] | Q:
Returning objects or multiple variables (not numbers) in R
I am training multiple SVMs in my R application, and I would like my function to return a holder object to which I can easily access each one of them later in a function.
The SVM is created as this:
svm.model <- svm(x=trainset,y=trainlabels)
svm.pred <- predict(svm.model,testset)
res <- table(pred = svm.pred, true = testlabels)
I want to be able to return the table called "res", or both svm.model and svm.pred. Any will do.
In a Object Oriented language I would use something like Javas ArrayList to do this, but a regular list(which was suggested in many posts) didn't do its job. I was not able to put any of these values, and if I made it, they got "unwrapped" and lost its structure.
Update
Good point in the comment section about how exactly I tried to do this with a list. I did the following:
result<-list()
for i in...
result[i]<-svm.model
result[i+1] <-svm.pred
I have tried the same as above, but with "res"(a table).
Another approach I tried was to create a new list with the previous list each time:
result<-list(result,svm.model,svm.pred)
It gives me only a length 3 size list(I see why) and the two last values are "lists" instead of what they are in fact, hence it doesn't allow me to call "table(pred = svm.pred, true = testlabels) " as it returns an error:
"Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?"
A:
If you have a loop and you want to store all three
result<-list()
for (i in 1:n) {
...
svm.model <- svm(x=trainset,y=trainlabels)
svm.pred <- predict(svm.model,testset)
res <- table(pred = svm.pred, true = testlabels)
result[[i]] <- list(res=res, svm.model=svm.model, svm.pred=svm.pred)
}
Note is is important to use [[ ]] when putting items into a list and getting them out. I also used a named list here to make it easier to get specific objects out. Then if you wanted to re-make the table from the 3rd loop, you could do
table(pred = result[[3]]$svm.pred, true=testlabels)
|
[
"stackoverflow",
"0056819884.txt"
] | Q:
TypeError: Cannot read property 'player' of undefined
I am currently working on a project using Angular. Since I am pretty new to programming, I don't know what to do with this Error:
TypeError: Cannot read property 'player' of undefined.
Basically I don't know where and how to define this property.
Here is the Code I am using:
My game.component.html:
<div class="container">
<div class="playerBox">
<table>
<tr>
<td class="player">Player: </td>
<td class="player" [innerText]="games.player"></td>
</tr>
<tr>
<td class="player">Round: </td>
<td class="player" [innerText]="games.round"></td>
</tr>
</table>
</div>
<div class="content">
<p [innerText]="games.question"></p>
<button class="button" (click)="nextQuestion()">Next</button>
<button class="button" routerLink="/home">Home</button>
</div>
</div>
Game.component.ts:
import { Component, OnInit } from '@angular/core';
import { QuestionService } from '../../services/question.service';
import { Game } from "../../models/game";
@Component({
selector: 'app-game',
templateUrl: './game.component.html',
styleUrls: ['./game.component.sass']
})
export class GameComponent implements OnInit {
games: Game;
constructor(private questionService: QuestionService) { }
ngOnInit() {
this.nextQuestion();
}
nextQuestion() {
this.questionService.getQuestion().subscribe(data => {
this.games = data;
});
}
}
Question.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { O`enter code here`bservable } from 'rxjs';
import { Game } from '../models/game';
@Injectable({
providedIn: 'root'
})
export class QuestionService {
constructor(private http: HttpClient) { }
/* Get question from DB */
getQuestion(): Observable<Game> {
return this.http.get<Game>("//localhost:8443/api/next");
}
resetAll() {
return this.http.get("//localhost:8443/api/reset");
}
}
And finally Game.ts:
export class Game {
player: string;
round: number;
question: string;
}
The error is thrown in game.component.html line 6.
Thank you for any help!
A:
http get request is asynchronous call so in that case the games will be an undefined until it get the value try to set initial value for the games property
games: Game = new Game();
another way is use ?. (safe navigation operator)
<table>
<tr>
<td class="player">Player: </td>
<td class="player" [innerText]="games?.player"></td>
</tr>
<tr>
<td class="player">Round: </td>
<td class="player" [innerText]="games?.round"></td>
</tr>
</table>
|
[
"stackoverflow",
"0011662189.txt"
] | Q:
Weird Deletion null error
I'm trying to delete from a join table I made and I'm getting a weird error I cant figure out.
Here are my models
class ArticlesUser < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :user
belongs_to :article
end
class Article < ActiveRecord::Base
attr_accessible :title
belongs_to :user
has_many :articles_users
has_many :likes, :through => :articles_users, :class_name => 'User', :source => :user
end
class User < ActiveRecord::Base
has_many :articles, :order => 'id DESC'
has_and_belongs_to_many :badges
has_many :articles_users
has_many :likes, :through => :articles_users, :class_name => 'Article', :source => :article
end
Testing in the Rails Console you can see the error:
> a = Article.find(13)
> a.articles_users #works fine, returns an array of users who "like" the article
> a.articles_users.where(user_id: 3) #works as well
> a.articles_users.where(user_id: 3).first.destroy #this is where the error is thrown!
Here is there error:
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'articles_users.' in 'where clause': DELETE FROM `articles_users` WHERE `articles_users`.`` = NULL
Why does it seem to be completely ignoring the where hash? Please help me with this I've spent hours today trying to figure it out.
Thanks!
Edit:
The articles_users table has 2 columns: article_id and user_id
Edit:
This is copy and pasted from the console:
1.9.3p194 :004 > a.articles_users.where(user_id: 3).first
ArticlesUser Load (0.7ms) SELECT `articles_users`.* FROM `articles_users` WHERE `articles_users`.`article_id` = 13 AND `articles_users`.`user_id` = 3 LIMIT 1
=> #<ArticlesUser user_id: 3, article_id: 13>
A:
I tried and reproduced your issue.
From Your output it seems you don't have a id column in ArticlesUser
which is the cause if issue.
=> #<ArticlesUser user_id: 3, article_id: 13>
I tried adding id column to the table and it worked like charm.
Created a new migration and add it
add_column :articles_users, :id, :primary_key
When you destroy a record rails uses its id as a reference to delete it from database.
Check example.
DELETE FROM `articles_users` WHERE `articles_users`.`id` = 1
|
[
"stackoverflow",
"0022776104.txt"
] | Q:
Why pre-checked radio button cannot get value?
I am currently working on a simple project. But unfortunately my radio button cannot work perfectly when I press on submit button. Due to I am using show hide onclick function to disable hide element input text therefore I need to click on radio button first then only can work. What can I do to get "database" radio button id without click on any radio button?
This is HTML code :
<html>
<head>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<meta charset="utf-8">
<title>Send EDMs</title>
</head>
<body>
<form action="confirm_sendemail.php" method="post" enctype="multipart/form-data" name="form1" id="form1" >
Subject : <br/>
<input type="text" name="subject" id="subject" required/> <br/>
Choose your upload type: <br />
<input type="radio" name="email" id="database" onclick="database_csv()" checked="checked" value="database"/>Database
<input type="radio" name="email" id="csv" onclick="database_csv()" value="csv"/>CSV<br/>
<div id="send_type" style="display:none">
<input name="csv" type="file" id="csv" accept=".csv" required/> <br/>
</div>
Content : <br/>
<textarea name="message" cols="50" rows="10" required></textarea><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
This is javascript with onclick show hide function :
<script>
function database_csv(){
$('#send_type').hide().find('input').prop('disabled', true);
}
function csv_database(){
$('#send_type').show().find('input').prop('disabled', false);
}
</script>
A:
You can add one "disable" code on your html input.
this is your code:
<input name="csv" type="file" id="csv" accept=".csv" required/>
replace your code like this :
<input name="csv" type="file" id="csv" accept=".csv" required disabled/>
|
[
"tex.stackexchange",
"0000415213.txt"
] | Q:
Arabic characters does not appear, arabi package
I am trying to write some Arabic using arabi package. Here is the code:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[LAE]{fontenc}
\usepackage[arabic]{babel}
\begin{document}
\selectlanguage{arabic}
مرحبا
\end{document}
I get a blank page with only Arabic number one at the bottom of the page.
My operating system is macOS Sierra, and I use xelatex from MikTex.
Output:
This is XeTeX, Version 3.14159265-2.6-0.99998 (MiKTeX 2.9.6500)
entering extended mode
(ara.tex
LaTeX2e <2017-04-15>
Babel <3.17> and hyphenation patterns for 1 language(s) loaded.
(/usr/local/share/miktex-texmf/tex/latex/base/article.cls
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
(/usr/local/share/miktex-texmf/tex/latex/base/size10.clo))
(/usr/local/share/miktex-texmf/tex/latex/base/inputenc.sty
Package inputenc Warning: inputenc package ignored with utf8 based engines.
) (/usr/local/share/miktex-texmf/tex/latex/base/fontenc.sty
(/Users/taha/.miktex/texmfs/install/tex/latex/arabi/laeenc.def)
(/Users/taha/.miktex/texmfs/install/tex/latex/arabi/laecmr.fd))
(/usr/local/share/miktex-texmf/tex/generic/babel/babel.sty
(/usr/local/share/miktex-texmf/tex/generic/babel/switch.def)
*************************************
* Local config file bblopts.cfg used
*
(/Users/taha/.miktex/texmfs/install/tex/latex/arabi/bblopts.cfg)
(/Users/taha/.miktex/texmfs/install/tex/latex/arabi/arabic.ldf
(/usr/local/share/miktex-texmf/tex/generic/babel/babel.def
(/usr/local/share/miktex-texmf/tex/generic/babel/switch.def)
(/usr/local/share/miktex-texmf/tex/generic/babel/xebabel.def
(/usr/local/share/miktex-texmf/tex/generic/babel/txtbabel.def)))
Package babel Warning: No hyphenation patterns were preloaded for
(babel) the language `Arabic' into the format.
(babel) Please, configure your TeX system to add them and
(babel) rebuild the format. Now I will use the patterns
(babel) preloaded for \language=0 instead on input line 35.
Loading the definitions for the LaTeX{} Arabic encoding
(/Users/taha/.miktex/texmfs/install/tex/latex/arabi/laeenc.def)
Loading the Common definitions for Arabic and Farsi
(/Users/taha/.miktex/texmfs/install/tex/latex/arabi/arabicore.sty
Arabi Core switching commands v1.0 2006/01/01 (may still change) )
Loading the Arabi fonts definitions for Arabic
(/Users/taha/.miktex/texmfs/install/tex/latex/arabi/arabicfnt.sty
Arabic font switching commands v1.0 2006/01/01 (may still change) )
Loading the Common definitions for Arabic and Farsi
(/Users/taha/.miktex/texmfs/install/tex/latex/arabi/arabnovowel.sty)
*************************************
* Local config file arabic.cfg used
*
(/Users/taha/.miktex/texmfs/install/tex/latex/arabi/arabic.cfg))) (ara.aux
LaTeX Font Warning: Font shape `LAE/lmr/m/n' undefined
(Font) using `LAE/cmr/m/n' instead on input line 3.
) (/usr/local/share/miktex-texmf/tex/latex/base/ifthen.sty)
(/usr/local/share/miktex-texmf/tex/latex/lm/ot1lmr.fd) [1] (ara.aux)
LaTeX Font Warning: Some font shapes were not available, defaults substituted.
)
(see the transcript file for additional information)
Output written on ara.pdf (1 page).
Transcript written on ara.log.
A:
Since you are compiling with XeTeX, don't load fontenc or inputenc. You want to use fontspec. Rather than babel, you probably want polyglossia.
Here's a very simple example. You need to specify a suitable font available on your system. On my system, Noto Naskh Arabic supports Arabic.
\documentclass{article}
\usepackage{polyglossia}
\setmainlanguage{arabic}
\newfontfamily\arabicfont[Script=Arabic]{Noto Naskh Arabic}
\begin{document}
مرحبا
\end{document}
|
[
"stackoverflow",
"0054716360.txt"
] | Q:
Incremental Pagination in Scrapy / Python
I came across a paging difficulty with Scrapy.
I usually used the following code successfully
next_page = response.xpath("//div//div[4]//ul[1]//li[10]//a[1]//@href").extract_first()
if next_page is not None:
yield scrapy.Request(url = response.urljoin(next_page), callback=self.parse)
It turns out that in this attempt, I came across a website that uses blocks of 5 pages. See image below.
So, after capturing the first 5 pages, Scrapy jumps to the penultimate page (526).
The paging structure follows the following logic:
https://www.example.com-1-data.html
And it increases numerically.
Can anyone help me with the incremental query (based on the example address) for this pagination?
A:
When it comes to pagination optimal approach really depends on what sort of pagination is being used.
If you:
know url page format
e.g. that url argument page indicates what page your on
know total amount of pages
Then you can schedule all pages at once:
def parse_listings_page1(self, response):
"""
here parse first page, schedule all other pages at once!
"""
# e.g. 'http://shop.com/products?page=1'
url = response.url
# e.g. 100
total_pages = int(response.css('.last-page').extract_first())
# schedule every page at once!
for page in range(2, total_pages + 1):
page_url = add_or_replace_parameter(url, 'page', page)
yield Request(page_url, self.parse_listings)
# don't forget to also parse listings on first page!
yield from self.parse_listings(response)
def parse_listings(self, response):
for url in response.css('.listing::attr(href)'):
yield Request(url, self.parse_product)
The huge benefits of this approach is speed - here you can take of async logic and crawl all pages simultaneously!
Alternatively.
If you:
don't know anything other than next page url is on the page
Then you have to schedule the pages synchronously 1 by 1:
def parse(self, response):
for product in response.css('.product::attr(href)'):
yield Request(product, self.parse_product)
next_page = response.css('.next-page::attr(href)').extract_first()
if next_page:
yield Request(next_page, self.parse)
else:
print(f'last page reached: {response.url}')
In your example your using the second syncronous approach and your fears here are unfounded, you just have to ensure your xpath selector selects the right page.
|
[
"stats.stackexchange",
"0000350976.txt"
] | Q:
Is the normality of residuals necessary to accept the null model in a multiple regression analysis?
Best-subset regression analysis:
I want to test effects of differents ecological variables on my response variable. I am working with function glmulti() of glmulti R-package (method=gaussian and based on aicc values). When I run my scrip, the result output suggest mes the null model (y~1) as best model.
I know that normality of residuals is important in regression analyses to accept the testing model but I'm not sure if you need normality too when your best model is the null model. My results suggest that none of my studied variable have effects on my Y variable, so...I think that it have sense that residuales of null model don't adjust with a normal distribution, what do you think?
This is part of my output with my 3 valid models (by differences <2 unids of AICc among themselves):
model aicc weights
[1] Y ~ 1 33.79708 1.47E-01 #Best model = Null model
[2] Y ~ 1 + F2 34.84813 8.69E-02
[3] Y ~ 1 + F1 35.44111 6.46E-02
Model 1 (Y ~ 1) and normality test (below):
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 8.9914 0.1083 83.05 <2e-16 ***
---
Shapiro-Wilk normality test
data: residuals((test1@objects[[1]]))
W = 0.78784, p-value = 0.0004302 --> No normality
Model 2 (Y ~ 1 + F2) and normality test (below):
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 8.9914 0.1067 84.283 <2e-16 ***
F2 -0.1381 0.1093 -1.263 0.222
---
Shapiro-Wilk normality test
data: residuals((test1@objects[[2]]))
W = 0.93545, p-value = 0.1769 --> Normality
Model 3 (Y ~ 1 + F2) and normality test (below):
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 8.9914 0.1082 83.102 <2e-16 ***
F1 -0.1121 0.1109 -1.011 0.325
---
Shapiro-Wilk normality test
data: residuals((test1@objects[[3]]))
W = 0.86405, p-value = 0.007489 --> No normality
Note: My second model have normal residuals, but F2 is not significant when test the model (only Intercept is significant). This is the same conclusion that the first model show, although this first has no normal residuals. Model 3 is not better than Model 2 because AICc is bigger and also show no-normal residuals.
By this reason I think that I could accept the null model (first model) as best model, what do you think?
Thanks for all.
A:
As a general rule, goodness-of-fit tests comparing regression models are robust to non-normality of the underlying error terms. The reason for this is that most goodness-of-fit statistics are summation statistics that are subject to the central-limit-theorem. It is not necessary for the underlying errors to be normally distributed for the goodness-of-fit statistic to converge in distribution to the distribution used for the test.
For a regression with an intercept and $k$ explanatory variables the AICc statistic can be written as:
$$\begin{equation} \begin{aligned}
\text{AICc}
&= \frac{2nk}{n-k-1} - 2 \hat{\ell}_\mathbb{x,y} \\[6pt]
&= \frac{2nk}{n-k-1} - 2 \sum_{i=1}^n \ln p(\mathbf{x}_i, y_i | \hat{\boldsymbol{\beta}}, \hat{\sigma}) \\[6pt]
&= \frac{2nk}{n-k-1} + n \ln(2 \pi) + 2n \ln(\hat{\sigma}) + \frac{1}{\hat{\sigma}^2} \underbrace{\sum_{i=1}^n ( y_i - \mathbf{x}_i \cdot \hat{\boldsymbol{\beta}} )^2}_{\text{SSE}}. \\[6pt]
\end{aligned} \end{equation}$$
You can see from this expression that the AICc involves the residual-sum-of-squares (SSE). For large $n$ the estimators of parameters converge to their true values, so they are not affected much by individual observations. In this case, the SSE is a sum of (almost) IID random variables, and under some broad assumptions, this converges in distribution to the chi-squared distribution (which converges to normal). Further information on the distribution of the AIC statistic can be found in Yanagihara and Ohmoto (2005), and this can easily be adjusted to the AICc.
Consequently, we can obtain a reasonable distributional approximation for the AICc statistic, even if the underlying error terms are not normally distributed. We still require some conditions on the underlying error terms so that the central limit theorem applies; for example, we will generally require these to have finite variance, which rules out cases of heavy-tailed error distributions.
The above means that your model comparisons are probably quite robust to non-normality of the error terms, so long as $n$ is not too small, and so long as the broad conditions for applying the CLT are present. Of course, regardless of which model you end up using, if the residuals show substantial departure from normality, then this means that the normality assumption in the model is false. You might be able to improve your model using a GLM with a different error distribution, but even without this, many aspects of the model are robust.
|
[
"stackoverflow",
"0057852309.txt"
] | Q:
Inserting HTML form data comes up blank
I am trying to send info I enter into an HTML form, into a MySQL database table. The function works, BUT...It enters BLANK data into the Mysql Database
I dont know what else to try. I am really new to this
THIS IS MY HTML FORM:
<form action="" method="post">
<div class="form-group">
<label for="date">Date</label>
<input type="date" class="form-control" id="date" aria-describedby="emailHelp" placeholder="Date">
<small id="emailHelp" class="form-text text-muted">The date the team went to the job site</small>
</div>
<div class="form-group">
<label for="job_number">Job Number</label>
<input type="text" class="form-control" id="job_number" placeholder="JC2020">
</div>
<div class="form-group">
<label for="job_name">Job Name</label>
<input type="text" class="form-control" id="job_name" placeholder="AVI Tender">
</div>
<div class="form-group">
<label for="team_name">Team Name</label>
<input type="text" class="form-control" id="team_name" placeholder="Shane">
</div>
<div class="form-group">
<label for="pastel_code">Pastel Code</label>
<input type="text" class="form-control" id="pastel_code" placeholder="012">
</div>
<div class="form-group">
<label for="vrn">Vehicle Registration</label>
<input type="text" class="form-control" id="vrn" placeholder="ND 123-456">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
THIS IS MY PHP file that processes the data:
<?php
require_once('config.php');
$date= $_POST['date'];
$job_number= $_POST['job_number'];
$team_name= $_POST['team_name'];
$pastel_code= $_POST['pastel_code'];
$vrn= $_POST['vrn'];
$job_name= $_POST['job_name'];
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO job_records (date, job_number, team_name, pastel_code, vrn, job_name)
VALUES ('$date', '$job_number', '$team_name', '$pastel_code', '$vrn', '$job_name')";
$conn->exec($sql);
echo "<script>alert('Data successfully added!'); window.location='dataentry.php'</script>";
?>
After submitting the form, a message displays saying the data was added, then redirects to the "master data" page with ALL the entries i have entered over time. But all entries i process come out BLANK. What am i doing wrong?
A:
As I mentioned each form element requires a name attribute in order that it will appear in the POST array when the form is submitted. An ID attribute is mainly of use when interacting with the DOM using Javascript so really are not required below / above.
<form action='' method='post'>
<div class='form-group'>
<label for='date'>Date</label>
<input type='date' class='form-control' id='date' name='date' aria-describedby='emailHelp' placeholder='Date'>
<small id='emailHelp' class='form-text text-muted'>The date the team went to the job site</small>
</div>
<div class='form-group'>
<label for='job_number'>Job Number</label>
<input type='text' class='form-control' id='job_number' name='job_number' placeholder='JC2020'>
</div>
<div class='form-group'>
<label for='job_name'>Job Name</label>
<input type='text' class='form-control' id='job_name' name='job_name' placeholder='AVI Tender'>
</div>
<div class='form-group'>
<label for='team_name'>Team Name</label>
<input type='text' class='form-control' id='team_name' name='team_name' placeholder='Shane'>
</div>
<div class='form-group'>
<label for='pastel_code'>Pastel Code</label>
<input type='text' class='form-control' id='pastel_code' name='pastel_code' placeholder='012'>
</div>
<div class='form-group'>
<label for='vrn'>Vehicle Registration</label>
<input type='text' class='form-control' id='vrn' name='vrn' placeholder='ND 123-456'>
</div>
<button type='submit' class='btn btn-primary'>Submit</button>
</form>
That said the main issue, which has been addressed in comments, is that of SQL injection vulnerabilities - one of the benefits of both PDO and mySQLi are prepared statements. As you are using PDO perhaps this might be of use:
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
require_once('config.php');
$args=array(
'date' => FILTER_SANITIZE_STRING,
'job_number' => FILTER_SANITIZE_STRING,
'team_name' => FILTER_SANITIZE_STRING,
'pastel_code' => FILTER_SANITIZE_STRING,
'vrn' => FILTER_SANITIZE_STRING,
'job_name' => FILTER_SANITIZE_STRING
);
$_POST=filter_input_array( INPUT_POST, $args );
$params=array();
$sql='insert into `job_records` ( `date`, `job_number`, `team_name`, `pastel_code`, `vrn`, `job_name` ) values ( :date, :job_number, :team_name, :pastel_code, :vrn, :job_name )';
foreach( array_keys( $args ) as $key ){
$params[ ':'.$key ] = ${$key};
}
$stmt=$conn->prepare( $sql );
$res = $stmt->execute( $params );
exit( header( sprintf( 'Location: dataentry.php?status=%s', $res ? 'ok' : 'fail' ) ) );
}
?>
demo - tested and appears to function OK
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
try{
/* PDO connection */
$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$options=array(
PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL,
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_EMULATE_PREPARES => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_unicode_ci\', @@sql_mode = STRICT_ALL_TABLES, @@foreign_key_checks = 1'
);
$dsn='mysql:host='.$dbhost.';port='.$dbport.';dbname='.$dbname.';charset=UTF8';
$db = $conn = new PDO( $dsn, $dbuser, $dbpwd, $options );
/* disabled as not relevant in demo */
#require_once('config.php');
$args=array(
'date' => FILTER_SANITIZE_STRING,
'job_number' => FILTER_SANITIZE_STRING,
'team_name' => FILTER_SANITIZE_STRING,
'pastel_code' => FILTER_SANITIZE_STRING,
'vrn' => FILTER_SANITIZE_STRING,
'job_name' => FILTER_SANITIZE_STRING
);
$_POST=filter_input_array( INPUT_POST, $args );
extract( $_POST );
$errors=array();
$params=array();
$keys=array_keys( $args );
/* dynamically build sql query from $args array */
$sql=sprintf('insert into `job_records`
( `%s` )
values
( :%s ) ',
implode( '`,`', $keys ),
implode( ', :', $keys )
);
/* check that each variable is set else throw exception and continue */
foreach( array_keys( $args ) as $key ){
try{
/* test variable variable against those generated by `extract` above */
if( empty( ${$key} ) ) throw new Exception( sprintf( 'empty field: %s', $key ) );
/* add the parameter to the args to be executed */
$params[ ':'.$key ] = ${$key};
}catch( Exception $e ){
$errors[]=$e->getMessage();
continue;
}
}
/* If all went well execute the query & redirect user */
if( !empty( $params ) && empty( $errors ) && !empty( $conn ) ){
$stmt=$conn->prepare( $sql );
if( !$stmt ) throw new PDOException('Failed to prepare SQL Query');
$res = $stmt->execute( $params );
exit( header( sprintf( 'Location: dataentry.php?status=%s', $res ? 'ok' : 'fail' ) ) );
}
if( !empty( $errors ) ) printf( '<pre>%s</pre>', print_r($errors,true) );
}catch( PDOException $e ){
exit( $e->getMessage() );
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>PDO form test</title>
</head>
<body>
<form action='' method='post'>
<div class='form-group'>
<label for='date'>Date</label>
<input type='date' class='form-control' id='date' name='date' aria-describedby='emailHelp' placeholder='Date'>
<small id='emailHelp' class='form-text text-muted'>The date the team went to the job site</small>
</div>
<div class='form-group'>
<label for='job_number'>Job Number</label>
<input type='text' class='form-control' id='job_number' name='job_number' placeholder='JC2020'>
</div>
<div class='form-group'>
<label for='job_name'>Job Name</label>
<input type='text' class='form-control' id='job_name' name='job_name' placeholder='AVI Tender'>
</div>
<div class='form-group'>
<label for='team_name'>Team Name</label>
<input type='text' class='form-control' id='team_name' name='team_name' placeholder='Shane'>
</div>
<div class='form-group'>
<label for='pastel_code'>Pastel Code</label>
<input type='text' class='form-control' id='pastel_code' name='pastel_code' placeholder='012'>
</div>
<div class='form-group'>
<label for='vrn'>Vehicle Registration</label>
<input type='text' class='form-control' id='vrn' name='vrn' placeholder='ND 123-456'>
</div>
<button type='submit' class='btn btn-primary'>Submit</button>
</form>
</body>
</html>
|
[
"stats.stackexchange",
"0000281269.txt"
] | Q:
What is the fastest way to calculate the leading singular value of a very large matrix (10mln x 100k)?
I only know of the following power iteration. But it needs to create a huge matrix A'*A when both of rows and columns are pretty large. And A is a dense matrix as well. Is there any alternative to power iteration method below? I have heard of krylov subspace method, but I am not familiar with it. In anycase I am looking for any faster method than the one mentioned below:
B = A'*A; % or B = A*A' if it is smaller
x = B(:,1); % example of starting point, x will have the largest eigenvector
x = x/norm(x);
for i = 1:200
y = B*x;
y = y/norm(y);
% norm(x - y); % <- residual, you can try to use it to stop iteration
x = y;
end;
n3 = sqrt(mean(B*x./x)) % translate eigenvalue of B to singular value of A
A:
There are two approaches that require only small number of multiplications of vectors by $A$ or $A'$, and so have computational complexity $O(MNk)$ for small fixed $k$. Their performance is empirically similar, too.
Lanczos-type algorithms:
Stochastic SVD
You absolutely do not want to implement a Lanczos-type algorithm yourself -- the rounding error is subtle and quick to anger -- but implementations are available in many packages.
You actually can implement Stochastic SVD yourself; there's a very short Matlab implementation at that link.
|
[
"stackoverflow",
"0059896691.txt"
] | Q:
Data not rendered in Vue Js
I have tried to render data to the home page but nothing displayed despite there being no error. Here is my code
app.js
import Home from './components/Home';
const routes = [{ name: 'home',path: '/home',component: Home},];
const router = new VueRouter({ mode: 'history', routes: routes});
const app = new Vue(Vue.util.extend({ router },{data: {message:'Hello Vue!'}}, Home)).$mount('#app');
Home.vue
<p>{{ message }}</p>
A:
You have to access the parent data since your Home component is a child component.
Home vue
<div id="app">
<p>{{ this.$parent.message }}</p>
</div>
|
[
"stackoverflow",
"0060335255.txt"
] | Q:
Rails, trying to create a record
I have a few models, student, Diary and Grade and diary entrys
Every student belongs to a grade, every student has a diary for every grade.
When you create a student record, you select grade, I want to be able to create a diary with the student name and grade.
Diary Model
class Diary < ApplicationRecord
belongs_to :student
belongs_to :user
belongs_to :grade
end
Student model
class Student < ApplicationRecord
belongs_to :user
has_many :diaries, dependent: :destroy
has_many :subjects, dependent: :destroy
has_many :grades #confusing for me also... should be in one grade at a time?
accepts_nested_attributes_for :diaries
accepts_nested_attributes_for :subjects
def subject_list=(subject_string)
subject_name = subject_string.split(“,”).collect{ |s| s.strip.downcase }.uniq
new_or_found_subjects = subject_names.collect { |name| Subject.find_or_create_by(name: name) }
self.subjects = new_or_found_skills
end
def subject_list
self.subjects.collect do |subject|
subject.name
end.join(“,”)
end
end
Model for Grade
class Grade < ApplicationRecord
has_many :subjects
belongs_to :student
belongs_to :diary
end
Student show page
<div class="col-sm-7">
<div class="card">
<div class="card-body">
<%= simple_form_for :diary, url: new_student_diary_path(@student) do |f| %>
<!-- I want to have a button here that creates a diary for the student, without manually entering any information
the information shoud be student_id, user_id and student.grade_id
-->
<%= f.submit "Create Diary", class: "btn btn-primary text-center" %>
<%end%>
</div>
My controller
def create
@student = Student.find(params[:student_id])
@diary = @student.diaries.build(diary_params)
@diary.user = current_user
respond_to do |format|
if @diary.save
format.html { redirect_to @diary, notice: 'Diary was successfully created.' }
format.json { render :show, status: :created, location: @diary }
else
format.html { render :new }
format.json { render json: @diary.errors, status: :unprocessable_entity }
end
end
end
My challenge is both in the models, controllers and views... I can't seem to wrap my head around this.... I would really appreciate a step by step answer so that I can learn how to do this.
A:
According to scenerio
1 student has 1 diary
1 diary has 1 grade
So,
s = Student.new
g = Grade.new
@d = Diary.new(s.id, g.id)
1 student has many grades
|
[
"stackoverflow",
"0013146899.txt"
] | Q:
PyInstaller Runtime Error? (R6034)
I've finally gotten PyInstaller to build an exe file, but it's not running. As soon as I open it, I get this in a dialog:
Runtime Error!
Program C:\.....\MCManager.exe
R6034
An application has made an attempt to load the C runtime library incorrectly.
Please contact the application's support team for more information.
Here's my spec:
# -*- mode: python -*-
a = Analysis(['MCManager.py'],
pathex=['C:\\Users\\Lucas\\Dropbox'],
hiddenimports=[],
hookspath=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name=os.path.join('dist', 'MCManager.exe'),
debug=False,
strip=None,
upx=True,
console=False,
icon='MCManager.ico')
app = BUNDLE(exe,
name=os.path.join('dist', 'MCManager.exe.app'))
I've looked around, and nobody seems to have this same problem.
If it changes things at all, this script uses wxPython.
A:
I was going to leave a comment, but not enough rep. Though this was asked awhile ago I recently ran into the same issue and it turned out to be a Pyinstaller bug with version 3.2.
Resulting exe terminates with R6034 after upgrade to pyinstaller 3.2:
https://github.com/pyinstaller/pyinstaller/issues/1985
PyInstaller 3.2, OneFile R6034, 32-bit Python 2.7.11
https://github.com/pyinstaller/pyinstaller/issues/2042
Looks like they've fixed this in the latest dev version and it's suggested to
pip install https://github.com/pyinstaller/pyinstaller/archive/develop.zip
Using this in my requirements file instead of pyinstaller==3.2 patched it for me!
A:
I recently started getting "Runtime Error? (R6034)"
It was on a solid existing python program which I had used pyinstaller before to compile to a onefile. I noticed that the problem only happened after I renamed the exe after it had been compiled. Once I renamed it back to the original exe name, the R6034 went away.
Leason learned... don't rename your exe after building with pyinstaller. If you need your exe to have a different name, then change the source py name and then recompile.
|
[
"stackoverflow",
"0019078204.txt"
] | Q:
runs animation in translation between two activity
I want to translation between two activity with animation. I want when user touches the image at top of page, the image translate to bottom of screen(slide down) and View of second activity move of top to bottom(slide down) and this like that tow move runs in same time. I dont know How can I implemented this? I use this code .
slide_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:interpolator="@android:anim/linear_interpolator"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
mian:
private OnTouchListener onTouchListener=new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Intent intent=new Intent(MainActivity.this,Test.class);
//overridePendingTransition(R.anim.slide_down, R.anim.slide_down);
startActivity(intent);
overridePendingTransition(R.anim.slide_down, R.anim.slide_down);
return false;
}
};
When I run this code and touch image, the screen becomes black and then second activity starts and then the animation runs. But I want the animation when the first activity closes, second activity starts over the end of first activity
A:
You are on the right path.
overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_bottom);
Must be defined in onCreate of your activity and defines how that activity behaves on enter and exit.
slide_in_top.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="200"
android:fromYDelta="-100%"
android:toYDelta="0%" />
slide_out_bottom.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="200"
android:fromYDelta="0%"
android:toYDelta="100%" />
Edit:
You want the animation for the view only, and then switch to another activity, right?
@Override
public boolean onTouch(View v, MotionEvent event) {
// first animate the view
TranslateAnimation anim = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta)
anim.setDuration(duration);
v.startAnimation(anim);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// wait for the duration of the animation before switching acitivity
// remember to apply the overridePendingTransition to them
// if you want a transition animation on this too
// overridePendingTransition added to both onCreate of Test and MainActivity
Intent intent=new Intent(MainActivity.this,Test.class);
startActivity(intent);
}
}, duration); // <-- notice the wait for animation to complete
return false;
}
|
[
"stackoverflow",
"0048147035.txt"
] | Q:
Laravel Display Product name instead of ID
I want to display the Product name instead of just the Item id.
My code:
{{$fd->purchase->product_id}}
How can I change this? Because in my Feedback DB Table are only the Product ID?
How can I do this with the Laravel Database: Query Builder?
Thanks
A:
Define a relationship:
public function product()
{
return $this->belongsTo(Product::class);
}
And use it:
{{ $fd->purchase->product->name }}
|
[
"stackoverflow",
"0010380365.txt"
] | Q:
CSS design Issue with Safari for facebook like box
I am using Facebook likebox on website and it comesup nicely on all browsers even English version comes right in safari but the Arabic version of website Facebook like box appears outside gray box while it should be inside. This happens only in safari I am using safari 5.1.4. and I am not sure if this is a CSS issue or how to fix with with any CSS property as i tried to change few properties but it didn't work
Help is appreciate in this regard
A:
I'm not quite sure what is causing it (as the containers for the iframe do have position:relative), but it seems to be due to the iframe having a position:absolute. Removing that property from
.fb_iframe_widget iframe {
/* position: absolute; */
}
seems to solve the problem (at least, it shows correctly both in Firefox and Safari).
|
[
"stackoverflow",
"0022287444.txt"
] | Q:
IOException: Cannot run program "javac" when "sudo ./sbt/sbt compile" in Spark?
I'm installing Apache Spark which uses its own copy of SBT to set things up.
I'm using Linux Mint in a VirtualBox VM.
Here's a snippet from the error when I run sudo ./sbt/sbt compile from the Spark directory spark-0.9.0-incubating:
[error] (core/compile:compile) java.io.IOException: Cannot run program "javac": error=2, No such file or directory
[error] Total time: 181 s, completed Mar 9, 2014 12:48:03 PM
I can run java and javac from the command line just fine: e.g. javac -version gives javac 1.6.0_31
The correct jdk1.6.0_31/bin is in my PATH.
I read that the error might be due to the 64-bit JDK that I had installed, but I get the same error with the 32 bit JDK.
How can I sort out the issue?
edit: Using bash shell.
A:
DISCLAIMER I'm mostly guessing now and still am unsure I should've responding here rather than adding a comment. Until it's clear, the DISCLAIMER remains.
When you execute java and javac from the command line, what user are you at that moment? I'm pretty sure your problems surface because the users you operate are different.
Please notice that you're executing sudo ./sbt/sbt compile as root (due to the way sudo works), but you say nothing about what user(s) you've been using to execute javac and java commands.
Add jdk1.6.0_31/bin to PATH for root and you'll be all set (as far as the configuration of Java's concerned).
I'd also recommend setting JAVA_HOME to point to jdk1.6.0_31 as it may help at times -- many applications are using it as the way to find the location of Java.
As a workaround, you may edit ./sbt/sbt and add PATH and JAVA_HOME appropriately.
|
[
"stackoverflow",
"0040399647.txt"
] | Q:
C++primer 5th about func parameter
Its question is" Give the second parameter of make_plural (§ 6.3.2, p. 224) a default argument of 's'. Test your program by printing singular and plural versions of the words success and failure"
here is the make_plural.
string make_plural(size_t ctr, const string& word, const string& ending )
{
return (ctr > 1) ? word + ending : word;
}
Does it mean that change the 'ending', but ending is the third parameter, isn't it?
This question worries me a lot!
Regards!
A:
That must be a typo.
Looking at the code:
string make_plural(size_t ctr, const string& word, const string& ending )
{
return (ctr > 1) ? word + ending : word;
}
the most reasonable thing would be to have "s" as default for ending, as this is how you make the plural by default (not always, but with "bee" -> "bees" e.g. it works).
A much stronger argument is that in C++ it is not possible (unless you find a magic workaround (*)) to have a default argument for the n-th parameter if the (n+1)-th has no default argument:
foo(int first = 0,int second) // not possible !!
With this example it is maybe not so clear why this isnt allowed, but consider having multiple default values. Lets say you would write:
foo(int first = 0,int second,int third = 0); // actually still not allowed
Then there would be no way to know if
foo(1,2);
is supposed to call
foo(0,1,2);
or
foo(1,2,0);
To resolve this ambiguity some rule had to be invented and for C++ the rule is that default arguments have to be provided from right to left.
(*) If you can change the function and are willing to write some extra code, the workaround is rather trivial. You just have to encapsulate all parameters in a struct that provides creation of parameters with whatever combination of defaults you like.
|
[
"stackoverflow",
"0025230064.txt"
] | Q:
Hyperlink returns JSON in new Doc Window. I want it coming back to a variable like "response"
Is there a way to re-route a hyperlink like...
https://api.forecast.io/forecast/private_key/37.8267,-122.423
...into a variable, rather than let it come up into a new window, where I have no control over the data deposited there. This is a weather forecast and it validates the call with a private key, so I cannot offer you mine here. The JSON is rather lengthy, but here are a few lines of it:
{"latitude":37.8267,"longitude":-122.423,"timezone":"America/Los_Angeles","offset":-7,"currently":{"time":1407682322,"summary":"Overcast","icon":"cloudy","nearestStormDistance":7,"nearestStormBearing":166,"precipIntensity":0,"precipProbability":0,"temperature":57.72,"apparentTemperature":57.72,"dewPoint":53.92,"humidity":0.87,"windSpeed":5.82,"windBearing":238,"visibility":7.3,"cloudCover":0.94,"pressure":1014.97,"ozone":326.39},"minutely":{"summary":"Overcast for the hour.","icon":"cloudy","data":[{"time":1407682320,"precipIntensity":0,"precipProbability":0},{"time":1407682380,"precipIntensity":0,"precipProbability":0},{"time":1407682440,"precipIntensity":0,"precipProbability":0},{"time":1407682500,"precipIntensity":0,"precipProbability":0},{"time":1407682560,"precipIntensity":0,"precipProbability":0},{"time":1407682620,"precipIntensity":0,"precipProbability":0},{"time":1407682680,"precipIntensity":0,"precipProbability":0},{"time":1407682740,"precipIntensity":0,"precip
Your help would be appreciated.
DK
A:
The way to go is using ajax, you could use jQuery's jQuery.getJSON() method, check out the jQuery doc linked in the answer, something like following is the way to go:
var latLng = lat + "," + lng;
var url = "https://api.forecast.io/forecast/" + private_key + "/" + latLng + "?callback=?";
$.getJSON(url, function(response) {
//get the response
console.log(response);
});
But note that this will work only if the site https://api.forecast.io allows CORS.
|
[
"stackoverflow",
"0037233317.txt"
] | Q:
trouble writing the output of script to a file
I'm a beginner, just learning Python, but decided to take a break from that to explore some libraries and scripts. I quickly determined that Python might be perfect for automating my search for a new place to live. Anyway,the script writes nice HTML to stdout but I'm struggling to write to a file so I can review the output in a browser.
Here's the code:
#!/usr/bin/python
import requests
import pandas as pd
from bs4 import BeautifulSoup as bs4
url_base = 'http://eugene.craigslist.org/search/apa'
params = dict(bedrooms=2, housing_type=6)
rsp = requests.get(url_base, params=params)
print(rsp.url)
print(rsp.text[:500])
html = bs4(rsp.text, 'html.parser')
print(html.prettify()[:1000])
dwellings = html.find_all('p', attrs={'class': 'row'})
print(len(dwellings))
this_dwelling = dwellings[15]
print(this_dwelling.prettify())
I've looked at this but it's unclear what specifically I'd put in the write() to write the script output to the file.
f = open('house.html','w')
f.write('What goes here?')
f.close()
So then I tried both file redirectionand piping to tee, returning this error:
Traceback (most recent call last):
File "./house.py", line 10, in
print(rsp.text[:500])
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 0: ordinal not in range(128)
Maybe I should have stayed with my introductory Hello World exercises and and stayed in the learning sequence but now I'm frustrated and want to get this script working first. Overall, Python is a lot of fun to work with.
A:
Try writing the dwellings to the file instead of printing it to the screen like this.
f = open('house.html','w')
f.write(this_dwelling.prettify())
f.close()
Put that at the end of your script to populate your HTML file with some of the results.
|
[
"stackoverflow",
"0060352746.txt"
] | Q:
Loop that generates random numbers and print when condition is true
I have got a problem with generating a loop that will provide me with a random numbers that are going to fulfil my condition.
Example:
Generate two Numbers in the bound (401)+100 and print numbers when int
a is going to be bigger than b
Program should work until the condition is going to be true. I was thinking that i should use "while" loop but its not going well.
Thank you for answer.
import java.util.Random;
public class Ex7 {
public static void main(String[] args) {
Random rand = new Random();
int a = rand.nextInt(401) + 100;
int b = rand.nextInt(401) + 100;
while (a > b) {
System.out.println("B value: " + b);
}
}
}
A:
This is an infinite loop that stops when the condition is true, is that what you are looking for?
Random rand = new Random();
int a,b;
while(true)
{
a = rand.nextInt(401) + 100;
b = rand.nextInt(401) + 100;
if(a>b) {
System.out.println("B value: " + b);
break;
}
}
EDIT:
If you don't want it to stop, then simply remove break
|
[
"stackoverflow",
"0049074599.txt"
] | Q:
Writing a nested list into CSV (Python)
I have a list that looks like this:
hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]
And I am simply trying to write it to a csv file, looking like this:
keyword 1 keyword 2 frequency
case iphone 91524
adapter iphone 12233
battery smartphone 88884
I can't figure my way around it. I couldn't transform the list into a DataFrame, either. I tried to apply some code suggested here Writing a Python list of lists to a csv file without any success.
A:
Pandas is convenient for this:
import pandas as pd
hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]
df = pd.DataFrame([[i[0][0], i[0][1], i[1]] for i in hello],
columns=['keyword 1', 'keyword 2', 'frequency'])
# keyword 1 keyword 2 frequency
# 0 case iphone 91524
# 1 adapter iphone 12233
# 2 battery smartphone 88884
df.to_csv('file.csv', index=False)
A:
If in pandas
s=pd.Series(dict(hello)).reset_index()
s.columns=['keyword 1', 'keyword 2', 'frequency']
s
Out[1012]:
keyword 1 keyword 2 frequency
0 adapter iphone 12233
1 battery smartphone 88884
2 case iphone 91524
|
[
"gaming.stackexchange",
"0000167558.txt"
] | Q:
My followers won't stop attacking my horse!
I use EFF and Convenient Horses, and lately I've been having this problem where my followers attack my supposedly friendly and essential horses and I can't get them to stop.
They stand there, slashing at the air, while the horse stands there doing nothing. I can't talk to them, and I don't think EFF has an option like AFT and Vilja do where you can command them not to attack whatever they're attacking.
Stopcombat, unfortunately, doesn't help. They immediately unsheathe their weapons and go back to attacking the horse.
A:
Try the Followers Stop Fighting Each Other mod.
It stop followers fighting each other, although it should work in your situation. Good luck!
|
[
"stackoverflow",
"0035299457.txt"
] | Q:
Getting mime type from file name in php
I have the following function to produce the mime type from a file name:
function get_mime_type($file) {
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $file);
finfo_close($finfo);
}
else {
$mimetype = mime_content_type($file);
}
if (empty($mimetype)) $mimetype = 'application/octet-stream';
return $mimetype;
}
I call this function at this portion of my code:
$out['uploads'][] = array(
'filename' => $fldrow['field_value'],
'mimetype' => get_mime_type($fldrow['field_value']),
'id' => $fldrow['ID'],
);
$fldrow['field_value'] contains 'card.pdf'
I am expecting 'application/pdf'
I am getting 'application/octet-stream'
I also tried this more elaborate approach using Mode=1:
PHP Mime type checking alternative way of doing it?
Same results in Mode=1 and blank in Mode=0.
What may I be doing wrong here?
EDIT
My solution based on Dymen1's response and after looking at other posts in that direction is the following:
function get_mime_type($filename) {
$idx = explode( '.', $filename );
$count_explode = count($idx);
$idx = strtolower($idx[$count_explode-1]);
$mimet = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'docx' => 'application/msword',
'xlsx' => 'application/vnd.ms-excel',
'pptx' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
if (isset( $mimet[$idx] )) {
return $mimet[$idx];
} else {
return 'application/octet-stream';
}
}
A:
If you check the documentation, you can see that you are not doing anything wrong.
But if you do a bit more research:
https://stackoverflow.com/a/3664655/3784145
you can see that the mime type you get is correct, but the extension doesn't need to match with the mime type as explained here:
http://nl3.php.net/manual/en/function.mime-content-type.php#85879
I would therefore use the files suffix to determine the files mime type.
(as seen in the first example)
|
[
"stackoverflow",
"0009709791.txt"
] | Q:
What is wrong for my form for this shallow route?
here is my route
resources :games do
resources :message_templates, :shallow => true
my rake routes is like this
game_message_templates GET /games/:game_id/message_templates(.:format) message_templates#index
POST /games/:game_id/message_templates(.:format) message_templates#create
new_game_message_template GET /games/:game_id/message_templates/new(.:format) message_templates#new
edit_message_template GET /message_templates/:id/edit(.:format) message_templates#edit
message_template GET /message_templates/:id(.:format) message_templates#show
PUT /message_templates/:id(.:format) message_templates#update
DELETE /message_templates/:id(.:format) message_templates#destroy
and my _form.erb, looks like this
<% form_for(@message_template) do |f| %>
but I get this error
undefined method `message_templates_path'
A:
It looks like you're creating a new message template for a given game in which case you need to provide the route with the associated game. If it were an existing message template the path would be message_template_path rather than message_templates_path.
Say:
<% form_for([@game, @message_template]) do |f| %>
|
[
"stackoverflow",
"0053441935.txt"
] | Q:
Open a specific bootstrap tab on page load using jQuery
I try to open a Bootstrap v.3 tab on page load using jQuery. I tried the
$('#activeTab3').addClass("active");
and
$('#activeTab3').tab('show')
which colors the button in the navigation list, but the content which is shown is belongs to the 1st tab.
I also tried:
$("#mytabs").tabs({
active: 1
});
but I get an error that tabs isn't a function..
$('#activeTab3').addClass("active");
//$('#activeTab3').tab('show')
/*
$("#mytabs").tabs({
active: 1
});
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row mtop-2">
<div class="col-md-12 col-xs-10">
<ul class="nav nav-pills" role="tablist" id="mytabs">
<li role="presentation" id="activeTab1"><a href="#tab1" aria-controls="home" role="tab" data-toggle="tab">tab1</a></li>
<li role="presentation" id="activeTab2"><a href="#tab2" aria-controls="home" role="tab" data-toggle="tab">tab2</a></li>
<li role="presentation" id="activeTab3"><a href="#tab3" aria-controls="home" role="tab" data-toggle="tab">tab3</a></li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="tab1">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseMachine1" aria-expanded="true" aria-controls="collapseMachine1">
<i class="fa fa-plus mright-1"></i> panel 1-1
</a>
</h4>
</div>
<div id="collapseMachine1" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseMachine1">
<div class="panel-body">
<div class="row mtop-2">
.... panel 1-1
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseMachine2" aria-expanded="false" aria-controls="collapseMachine2">
<i class="fa fa-edit mright-1"></i> panel 1-2
</a>
</h4>
</div>
<div id="collapseMachine2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseMachine2">
<div class="panel-body">
.... panel 1-3
</div>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="tab2">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseRobot1" aria-expanded="true" aria-controls="collapseRobot1">
<i class="fa fa-plus mright-1"></i> panel 2-1
</a>
</h4>
</div>
<div id="collapseRobot1" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseRobot1">
<div class="panel-body">
panel 2-1
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseRobot2" aria-expanded="false" aria-controls="collapseRobot2">
<i class="fa fa-edit mright-1"></i> panel 2-2
</a>
</h4>
</div>
<div id="collapseRobot2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseRobot2">
<div class="panel-body">
panel 2-2
</div>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="tab3">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseMould1" aria-expanded="true" aria-controls="collapseMould1">
<i class="fa fa-plus mright-1"></i> panel 3-1
</a>
</h4>
</div>
<div id="collapseMould1" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseMould1">
<div class="panel-body">
panel 3-1
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseMould2" aria-expanded="false" aria-controls="collapseMould2">
<i class="fa fa-edit mright-1"></i> panel 3-2
</a>
</h4>
</div>
<div id="collapseMould2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseMould2">
<div class="panel-body">
panel 3-2
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
A:
$(document).ready(function(){
$('#mytabs a[href="#tab3"]').tab('show')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row mtop-2">
<div class="col-md-12 col-xs-10">
<ul class="nav nav-pills" role="tablist" id="mytabs">
<li role="presentation" ><a href="#tab1" aria-controls="home" role="tab" data-toggle="tab">tab1</a></li>
<li role="presentation"><a href="#tab2" aria-controls="home" role="tab" data-toggle="tab">tab2</a></li>
<li role="presentation"><a href="#tab3" aria-controls="home" role="tab" data-toggle="tab">tab3</a></li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="tab1">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseMachine1" aria-expanded="true" aria-controls="collapseMachine1">
<i class="fa fa-plus mright-1"></i> panel 1-1
</a>
</h4>
</div>
<div id="collapseMachine1" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseMachine1">
<div class="panel-body">
<div class="row mtop-2">
.... panel 1-1
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseMachine2" aria-expanded="false" aria-controls="collapseMachine2">
<i class="fa fa-edit mright-1"></i> panel 1-2
</a>
</h4>
</div>
<div id="collapseMachine2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseMachine2">
<div class="panel-body">
.... panel 1-3
</div>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="tab2">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseRobot1" aria-expanded="true" aria-controls="collapseRobot1">
<i class="fa fa-plus mright-1"></i> panel 2-1
</a>
</h4>
</div>
<div id="collapseRobot1" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseRobot1">
<div class="panel-body">
panel 2-1
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseRobot2" aria-expanded="false" aria-controls="collapseRobot2">
<i class="fa fa-edit mright-1"></i> panel 2-2
</a>
</h4>
</div>
<div id="collapseRobot2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseRobot2">
<div class="panel-body">
panel 2-2
</div>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="tab3">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseMould1" aria-expanded="true" aria-controls="collapseMould1">
<i class="fa fa-plus mright-1"></i> panel 3-1
</a>
</h4>
</div>
<div id="collapseMould1" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseMould1">
<div class="panel-body">
panel 3-1
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseMould2" aria-expanded="false" aria-controls="collapseMould2">
<i class="fa fa-edit mright-1"></i> panel 3-2
</a>
</h4>
</div>
<div id="collapseMould2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="collapseMould2">
<div class="panel-body">
panel 3-2
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Use $('#mytabs a[href="#tab3"]').tab('show') to select tab using the tab css id and href css id.
|
[
"stackoverflow",
"0010674588.txt"
] | Q:
how to get an openstack token and validate it?
I followed this guide: http://keystone.openstack.org/api_curl_examples.html
and it seemed that I got a valid token by ran:
curl -d '{"auth":{"passwordCredentials":{"username": "can", "password": "mypassword"}}}' -H "Content-type: application/json" http://url:35357/v2.0/tokens
and it returned:
{
"access":
{
"token":
{
"expires": "2012-05-21T14:35:17Z",
"id": "468da447bd1c4821bbc5def0498fd441"
},
"serviceCatalog": {},
"user":
{
"username": "can",
"roles_links": [],
"id": "bb6d3a09ad0c4924bf20c1a32ccb5781",
"roles": [],
"name": "can"
}
}
}
but when I came to the next few sections to validate this token, I encountered this magic number: X-Auth-Token:999888777666. At first I thought it's the token I got but I was wrong.
I think I may have missed something, so I read related sections in openstack documents( http://keystone.openstack.org/configuration.html and http://docs.openstack.org/api/openstack-compute/programmer/content/ ), but still no idea how the number comes from.
could anyone explain to me
what's the meaning of that magic number
how to get the right value of it so I can get a working token to manage other parts of openstack
A:
That magic number (string really) is the admin_token setting in your keystone.conf file. Under the [DEFAULT] section in keystone.conf set
admin_token = abcd1234
If you don't use it for admin actions, you'll see something like
ubuntu@i-000004bc:~/devstack$ curl http://localhost:35357/v2.0/tenants
{"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Not Authorized"}}
If you do use it, you'll see something like
ubuntu@i-000004bc:~/devstack$ curl -H "X-Auth-Token: abcd1234" http://localhost:35357/v2.0/tenants
{"tenants_links": [], "tenants": [{"enabled": true, "description": null, "name": "demo", "id": "aee8a46babcb4e4286021c8f6ef996cd"}, {"enabled": true, "description": null, "name": "invisible_to_admin", "id": "de17fea45de148ada0a58e998e6c3e73"}, {"enabled": true, "description": null, "name": "admin", "id": "f34b0c8ab30e450489b121fbe723fde5"}, {"enabled": true, "description": null, "name": "service", "id": "fbe3e2e530fd47298cb2cba1b4afa3da"}]}
|
[
"stackoverflow",
"0019596715.txt"
] | Q:
AngularJS How to get additional routes parameter
Is there a way to add extra parameters to the $routeProvider and retrieve this parameters in a directive? I need this because the variable is page specific.
I would like to add a parameter pageName to the routeprovider like so:
$routeProvider
.when('/home',
{
controller: 'homeController',
templateUrl: '_templates/home.html',
pageName: 'home'
})
And use this extra parameter in a directive like so
directives.dirPagename = ['$route', '$routeParams', function($route, $routeParams) {
return {
restrict: 'ECA',
template: 'test',
link: function (scope, elem, attrs) {
console.log($route);
console.log($routeParams);
}
}
}]
When I log $route and inspect this inside google webdeveloper tools the pageName parameter is a few layers deep.
Object {routes: Object, reload: function}
current: D
$$route: Object
controller: "homeController"
**pageName: "home"**
Is there a way to directly get this variable or is this totally the wrong way to go?
UPDATE:
You can get the variables in routing with
var pageName = $route.routes[$location.$$path].pageName;
A:
You can find the information in $route.routes[uri].
I share with you my viewRouter service as an exemple:
var uaViewRouter = angular.module('ua.ViewRouter', []);
uaViewRouter.service('uaViewProvider', function($route, $location, uaContext){
this.redirectToView = function(viewName){
url = undefined;
for(var route in $route.routes){
if ($route.routes[route].view == viewName){
url = route;
}
}
if(url == undefined){
throw("uaViewProvider: Undefined view " + viewName);
}
if($route.routes[url].enrichment == true){
url = url.replace(":operatorId", uaContext.operator.get().id);
url = url.replace(":productId", uaContext.product.get().id);
}
$location.path(url);
};
});
uaViewRouter.run(function($rootScope, uaViewProvider) {
$rootScope.uaViewProvider = {};
$rootScope.uaViewProvider.redirectToView = function(viewName) {
uaViewProvider.redirectToView(viewName);
};
});
Exemple of route declaration:
uaApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'app/login/login.tpl.html',
loginRequired: false,
view: 'login'
}).
...
You can use it in your controller or service by calling:
uaViewProvider.redirectToView('login');
Or in the template:
<a href="" ng-click="uaViewProvider.redirectToView('login')">Click to login</a>
|
[
"stackoverflow",
"0038094706.txt"
] | Q:
GCM-AEAD support for ubuntu system running linux kernel-3.10
I am trying to implement a AEAD sample code for encryption Using GCM encryption. But I always get invalid argument error while setting the key
static int init_aead(void)
{
printk("Starting encryption\n");
struct crypto_aead *tfm = NULL;
struct aead_request *req;
struct tcrypt_result tresult;
struct scatterlist plaintext[1] ;
struct scatterlist ciphertext[1];
struct scatterlist gmactext[1];
unsigned char *plaindata = NULL;
unsigned char *cipherdata = NULL;
unsigned char *gmacdata = NULL;
const u8 *key = kmalloc(16, GFP_KERNEL);
char *algo = "rfc4106(gcm(aes))";
unsigned char *ivp = NULL;
int ret, i, d;
unsigned int iv_len;
unsigned int keylen = 16;
/* Allocating a cipher handle for AEAD */
tfm = crypto_alloc_aead(algo, 0, 0);
init_completion(&tresult.completion);
if(IS_ERR(tfm)) {
pr_err("alg: aead: Failed to load transform for %s: %ld\n", algo,
PTR_ERR(tfm));
return PTR_ERR(tfm);
}
/* Allocating request data structure to be used with AEAD data structure */
req = aead_request_alloc(tfm, GFP_KERNEL);
if(IS_ERR(req)) {
pr_err("Couldn't allocate request handle for %s:\n", algo);
return PTR_ERR(req);
}
/* Allocting a callback function to be used , when the request completes */
aead_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG, aead_work_done,&tresult);
crypto_aead_clear_flags(tfm, ~0);
/* Set key */
get_random_bytes((void*)key, keylen);
if((ret = crypto_aead_setkey(tfm, key, 16) != 0)) {
pr_err("Return value for setkey is %d\n", ret);
pr_info("key could not be set\n");
ret = -EAGAIN;
return ret;
}
/* Set authentication tag length */
if(crypto_aead_setauthsize(tfm, 16)) {
pr_info("Tag size could not be authenticated\n");
ret = -EAGAIN;
return ret;
}
/* Set IV size */
iv_len = crypto_aead_ivsize(tfm);
if (!(iv_len)){
pr_info("IV size could not be authenticated\n");
ret = -EAGAIN;
return ret;
}
plaindata = kmalloc(16, GFP_KERNEL);
cipherdata = kmalloc(16, GFP_KERNEL);
gmacdata = kmalloc(16, GFP_KERNEL);
ivp = kmalloc(iv_len, GFP_KERNEL);
if(!plaindata || !cipherdata || !gmacdata || !ivp) {
printk("Memory not availaible\n");
ret = -ENOMEM;
return ret;
}
for (i = 0, d = 0; i < 16; i++, d++)
plaindata[i] = d;
memset(cipherdata, 0, 16);
memset(gmacdata, 0, 16);
for (i = 0,d=0xa8; i < 16; i++, d++)
ivp[i] = d;
sg_init_one(&plaintext[0], plaindata, 16);
sg_init_one(&ciphertext[0], cipherdata, 16);
sg_init_one(&gmactext[0], gmacdata, 128);
aead_request_set_crypt(req, plaintext, ciphertext, 16, ivp);
aead_request_set_assoc(req, gmactext, 16);
ret = crypto_aead_encrypt(req);
if (ret)
printk("cipher call returns %d \n", ret);
else
printk("Failure \n");
return 0;
}
module_init(init_aead);
module_exit(exit_aead);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("My code for aead encryption test");
}
On inserting the module I get following output
Starting encryption
Return value for setkey is -22
key could not be set
According to AEAD specification aead uses aes-128 for encryption hence the block size should be 128 bit .
But my system shows only 1 Byte block size support for AEAD
name : rfc4106(gcm(aes))
driver : rfc4106-gcm-aesni
module : aesni_intel
priority : 400
refcnt : 1
selftest : passed
type : nivaead
async : yes
blocksize : 1
ivsize : 8
maxauthsize : 16
geniv : seqiv
Does the invalid argument error is thrown becuase of the block size. If so , what shall I do to make it work ?
A:
The block size of AES is indeed always 128 bit. The block size of GCM is a different matter though. GCM (Galois-Counter Mode) is - as the name suggests - build on top of the CTR (Counter) mode of operation, sometimes also called the SIC (Segmented Integer Counter) mode of operation. This turns AES into a stream cipher. Stream ciphers - by definition - have a block size of one byte (or, more precisely, one bit, but bit level operations are usually not supported by API's).
Block size however has little to do with the key size displayed in the call, and the argument does seem to require bytes instead of bits (in which key lengths are usually defined).
The size of the IV should be 12 bytes (the default). Otherwise additional calculations may be needed by the GCM implementation (if those exist at all).
|
[
"stackoverflow",
"0003460793.txt"
] | Q:
Access-VBA: Empty result for missing values in function?
I've got a question that probably has a pretty simple answer, but I didn't find a solution yet.
Here's an example:
Public Function abc(var_1 As Variant) As Single
abc = 2 * var_1
End Function
I want to call that function in an Access query. Values for 'var_1' are from a numeric (single) data field.
Problem: Some the values for var_1 are empty/missing. For those values I need the result of the function to be empty as well, but right now they are '0'.
I tried a lot of things already, but nothing works. The result for empty values is always '0' and not empty. Here's one try:
If IsNull(var_1) Then
abc = Empty
Exit Function
End If
Didn't work.
Any help for this problem would be very much appreciated. :)
Edit:
Thanks for the answers. I tried returning a variant before and it did return empty fields. However, the calculated field needs to behave as numberic and not as text, so this solution doesn't work for me.
I ended up using the answer of Beth, though it's more work than I'd like to have. ;)
Calling the function in SQL:
IIF(IsNull(X)=False;abc(X))
abc in VBA:
Public Function abc(var_1 As Single) As Single
abc = 2 * var_1
End Function
A:
Change the function to look something like the following.
Public Function abc(var_1 As Variant) As Variant
If IsNumeric(var_1) Then
abc = 2 * var_1
Else
abc = Null
End If
End Function
I do not believe that you can return a null in a single as you were trying to do.
|
[
"stackoverflow",
"0047923332.txt"
] | Q:
Converting nested JSON strings into JSON
I am consuming an AEM content API and it gives a JSON Structure, but for particular nested nodes, like links, it gives a JSON string in response.
Sample payload -
{
"Page Title": "Home",
"Page Description": "Sample Description",
"Key Words": "test1, test2, test 3",
"sections": [{
"Lineup": {
"title": "Our Project Family",
"strategy": [{
"title": "ASHJASH BASED",
"description": "This is a short description",
"links": ["{\"text\":\"income\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"Real Return\",\"href\":\"/content/dam/usa/pdf/singlepg.pdf\",\"desc\":\"This is a short description why to consider this\"}"],
"moreLink": "/content/us/home"
}, {
"title": "ALLOCATION",
"description": "This is a short description",
"links": ["{\"text\":\"fund\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"ETF\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"Active/Passive\",\"href\":\"/content/dam/usa/pdf/sat02017m_10.pdf\",\"desc\":\"This is a short description\"}"],
"moreLink": "/content/us/home"
}]
}
}]
}
In this payload, the nested links section is a JSON string.
In my API, when I consume the payload, I should be able to send a pure JSON object to my front end. This structure will different across all endpoints, so I want a generic way to convert entire object to JSON.
A:
Just parse then links content to JSON and respond the result to user from node.js server: Here is working example.
//ES6
let res = {
"Page Title": "Home",
"Page Description": "Sample Description",
"Key Words": "test1, test2, test 3",
"sections": [{
"Lineup": {
"title": "Our Project Family",
"strategy": [{
"title": "ASHJASH BASED",
"description": "This is a short description",
"links": ["{\"text\":\"income\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"Real Return\",\"href\":\"/content/dam/usa/pdf/singlepg.pdf\",\"desc\":\"This is a short description why to consider this\"}"],
"moreLink": "/content/us/home"
}, {
"title": "ALLOCATION",
"description": "This is a short description",
"links": ["{\"text\":\"fund\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"ETF\",\"href\":\"/content/dam/usa/pdf/2017m_10.pdf\",\"desc\":\"This is a short description\"}", "{\"text\":\"Active/Passive\",\"href\":\"/content/dam/usa/pdf/sat02017m_10.pdf\",\"desc\":\"This is a short description\"}"],
"moreLink": "/content/us/home"
}]
}
}]
}
res.sections = res.sections.map(
section => {
section.Lineup.strategy = section.Lineup.strategy.map(
strategy => {
strategy.links = strategy.links.map(
link => JSON.parse(link)
)
return strategy;
}
)
return section;
}
)
|
[
"stackoverflow",
"0008574567.txt"
] | Q:
How to on Torch light without using camera/video mode in iPhone?
I am using this below code for switch on the Torch light in iphone app. It working fine. The issue is, when we press the button the torch mode will be changed to 'On' but, the torch light only appear when the user entering into the Camera screen. I want to switch on the torch light without using the Camera screen. Can anyone please guide me? Please suggest me where i am wrong. Here my code,
captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (captureDevice.torchMode == AVCaptureTorchModeOff)
{
AVCaptureSession *session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
[captureDevice lockForConfiguration:nil];
[captureDevice setTorchMode:AVCaptureTorchModeOn];
[captureDevice unlockForConfiguration];
[session commitConfiguration];
[session startRunning];
[self setTorchSession:session];
[session release];
}
else
{
[torchSession stopRunning];
[captureDevice setTorchMode:AVCaptureTorchModeOff];
}
Is this correct code for Torch Light in iPhone? Please help me. Thanks in advance.
A:
This code works for me
- (void) internal_setFlashOn: (BOOL) turnOn {
AVCaptureDevice *theDevice = self.captureDevice;
if ([theDevice hasTorch]) {
[theDevice lockForConfiguration: nil];
AVCaptureTorchMode currentMode = [theDevice torchMode];
BOOL isAlreadyTurnedOn = (AVCaptureTorchModeOn == currentMode);
if (isAlreadyTurnedOn != turnOn) {
[theDevice setTorchMode: turnOn? AVCaptureTorchModeOn: AVCaptureTorchModeOff];
}
[theDevice unlockForConfiguration];
}
}
- (AVCaptureDevice *) captureDevice {
if (nil == internal_captureDevice) {
internal_captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[internal_captureDevice retain];
}
return internal_captureDevice;
}
This works on iPhone4 and above.
|
[
"stackoverflow",
"0060566059.txt"
] | Q:
Is there any more efficient way to code this "2 Sum" Questions
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 < index2. Please note that your returned answers (both index1 and index2 ) are not zero-based.
Put both these numbers in order in an array and return the array from your function ( Looking at the function signature will make things clearer ). Note that, if no pair exists, return empty list.
If multiple solutions exist, output the one where index2 is minimum. If there are multiple solutions with the minimum index2, choose the one with minimum index1 out of them.
twoSum : function(A, B){
var tempA = A;
var index1 = [];
var index2 = [];
var Results = [];
var diff = A.length/2;
for(var i = 0; i < A.length - 1; i++){
var temp = B - A[i];
for(var j = i; j < A.length - 1; j++){
if(temp == A[j]){
if(j - i > 0){
if(j < Results[1] || Results.length == 0){
if(A[j] != A[Results[1]-1] && A[i] != A[Results[0]-1]){
Results[0] = i + 1;
Results[1] = j + 1;
}
}
}
}
}
}
return Results;
}
A:
You could take a single loop approach with an object to store missing values.
function find(array, sum) {
var hash = {},
i = 0;
while (i < array.length) {
const value = array[i++];
if (value in hash) return [hash[value], i];
if (!(sum - value in hash)) hash[sum - value] = i;
}
}
console.log(find([2, 4, 2, 3, 7, 6, 5, 3, 4], 8));
|
[
"stackoverflow",
"0034207643.txt"
] | Q:
unable to parse ints with antlr
I'm trying to parse ints, but I can parse only multi-digit ints, not single-digit ints.
I narrowed it down to a very small lexer and parser which I based on sample grammars from antlr.org as follows:
# IntLexerTest.g4
lexer grammar IntLexerTest;
DIGIT
: '0' .. '9'
;
INT
: DIGIT+
;
#IntParserTest.g4
parser grammar IntParserTest;
options {
tokenVocab = IntLexerTest;
}
mything
: INT
;
And when I try to parse the digit 3 all by itself, I get "line 1:0 mismatched input '3' expecting INT". On the other hand, if I try to parse 33, it's fine. What am I doing wrong?
A:
The lexer matches rules from top to bottom. When 2 (or more) rules match the same amount of characters, the rule defined first will win. That is why a single digit is matched as an DIGIT and two or more digits as an INT.
What you should do is make DIGIT a fragment. Fragments are only used by other lexer rules and will never become a token of their own:
fragment DIGIT
: '0' .. '9'
;
INT
: DIGIT+
;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.