text:
Q: Where is the root in these words: miniature, minimal, minimize? Is it possible to identify one and the same root MIN in all these words: Miniature, minimal, minimize, minimum  minor, minority, minus, minute ? From etymological point of view they all came from one Roman root, but what about Modern English? If we consider MIN as a common root for all these words in Modern English, how shall we treat the other components -im, -ute, -us in those words? As derivational suffixes (if yes, then for sure not in Modern English).

A: It turns out there are two unrelated roots:
There is the (modern) Portuguese/Galician river Minho/Miño, called Minius in Latin, probably from an unknown root in Iberian, which is assumed to be a language isolate, i.e. not at all related to surrounding languages. From this comes miniature and the modern English prefix mini-.
From classical Latin Minius "an Iberian river":

*

*→ minium "cinnabar" (probably obtained from or near the river Minius)

*

*→ Postclass. Lat. minio "to colour something (red) with cinnabar, illustrate"

*

*→ miniatura "a colouring, illustration (typically small)"

*

*→ Eng. miniature "a small version of something".

*

*→ mini- "very small"

Then there is Proto-Indo-European *m(e)i- "small" + suffix *-nu (probably a verbal suffix):

*

*→ PIE *minu- "to lessen, reduce*

*

*→ Lat. minus "less", minor "less, smaller", minimus "least, smallest", minister "servant"

*

*→ Eng. minus, minor, minuscule, minimize, minimal, minister

*→ Lat. (di)minuo "lessen, decrease"

*

*→ Eng. diminish, minute, mince
In all these English words, only -ize and -al would seem able to produce new words in English; the rest are best considered purely Latin suffixes. English words using the Latin suffixes -tus, -or, -us, -(i)mus, and  -ter were generally taken from Latin (mostly through French), not formed in English.

A: The modern prefix mini- seems to come from the word miniatura, but the etymology keeps going back, linguistically speaking. Read all the answer, when you reach the end, it will take you back to this first part so you'll understand why "it comes from miniatura".

Miniatura comes from the Latin word miniare, which comes from minio (we can stop here, but it still goes back. I'll mention it if you're interested).
The Minio1, in chemistry, is the mixture of 2 molecules of monoxide and 1 molecule of lead bioxide, red-orange coloured, obtained from the massicot. This substance was used in Middle Ages in the "Art of miniatura".
The miniatura was the image painted, with extreme care for detail, to decorate the first letters of manuscripts, something like this:

In the italian wikipedia for "miniature", it says (I'll translate it):

Starting from the XIV century, the spreading of such images of small dimension, contributed to make the word "miniature" indicate images, paintings and objects of small dimensions.

(1): The name comes from a river in Spain, called Minius.

Minĭmu(m) ("piccolissimo" = very small) is the superlative for Mĭnus ("piccolo" = small).
Minority and minus come from the Latin word minor, which means "smaller" or "less".
Minute comes from minutus, past participle of mĭnŭĕre, "to make small, to reduce, to shrink".
We can't consider "-ute" "-im" as separated suffixes, as you proposed, because those parts come from the original word.
I couldn't find any proof that all those words relate to each other, and at this point, I could only speculate. My speculation was that "minio" for miniature was the ultimate original word, but during my research, unexpectedly, Greek came into the show and this makes me doubt about my speculation. I'm sorry I can't help you further, hope this helps though. If something comes up, I'll make sure to tell you.

A: Even if they were derived from the same root in Latin, they came to English by different paths, migrating whatever suffixes they had into root somewhere along the way.
I'd speculate Miniature is probably a root by itself. I'd speculate that minimum, minimal, minimize have common root minim (or maybe minimum with possible dropping of um part to accommodate suffixes -ize and -al). minor and minority same way have common root minor; and minus and minute are roots by themselves.


text:
Q: Android: programmatically check directory path for external or internal type I have String with directory path.
I want programmatically check: the path is in interal or external device memory?

A: on Phone with 3.0+ :-
compare string with
Environment.getExternalStorageDirectory()

if it matches and also check Environment.isExternalStorageEmulated() if both true then it is internal storage else external storage
on gingerbread 2.3 and below:-
Environment.getExternalStorageDirectory()

return external storage path as there was no emulation so if comparison succeed it is external storage else internal

A: You can find out which is the external path and the internal path.
For external path you can use this:
String secStore = System.getenv("SECONDARY_STORAGE");

And for intenal path, this:
String extStore = System.getenv("EXTERNAL_STORAGE");

After that you can compare you path to check where it is.

A: Complete information are both posts of @ankitagrawal and @Corina Gheorghe.
As i see getenv("SECONDARY_STORAGE")  gives different result from getExternalStorageDirectory().
In my device
for path in root directory:
1) /storage/sdcard1

for path in Android/data/APPNAME/files:
2) /storage/emulated/legacy

It's necessary check both external path's.
And first one method is not depend from isExternalStorageEmulated() in 3.0+ like second method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamic formula creation in R? Is it at all possible to use the lm() function with a matrix? Or maybe, the correct question is: "Is it possible to dynamically create formulas in R?"
I am creating a function whose output is a matrix and the number of columns in the matrix is not fixed = it depends on the inputs of the user. I want to fit an OLS model using the data in the matrix.
- The first column represents the dependent variable
- The other columns are the independent variables.
Using the lm function requires a formula, which presupposes the knowledge of the number of explanatory variables, which is not my case!
Is there any solution other than estimating the equation manually with the OLS formula?
Reproducible example:
> # When user 1 uses the function, he obtains m1
> m1 <- replicate(5, rnorm(50))
> colnames(m1) <- c("dep", paste0("ind", 1:(ncol(m1)-1)))
> head(m1)
            dep       ind1        ind2       ind3       ind4
[1,]  0.5848705  0.3602760 -0.95493403 -1.7278030 -0.1914170
[2,]  1.7167604 -0.1035825  0.31026183 -1.5071415 -1.2748600
[3,] -0.1326187 -0.5669026  0.01819749  0.8346880 -0.6304498
[4,] -0.7381232  0.4612792 -0.36132404 -0.1183131 -0.7446985
[5,]  0.9919123 -1.3228248 -0.44728270  0.6571244 -0.4895385
[6,] -0.8010111  0.8307584 -0.16106804  0.3069870 -0.3834583
>
> # When user 2 uses the function, he obtains m2
> m2 <- replicate(6, rnorm(50))
> colnames(m2) <- c("dep", paste0("ind", 1:(ncol(m2)-1)))
> head(m2)
            dep       ind1       ind2         ind3       ind4       ind5
[1,]  1.2936031 -0.8060085  0.5020699 -1.699123234  1.0205626  1.0787888
[2,]  1.2357370  0.5973699 -1.2134283 -0.928040354 -0.3037920 -0.1251678
[3,]  0.5292583  0.1063213 -1.3036526  0.395886937 -0.1280863  1.1423532
[4,]  0.9234484 -0.4505604  1.2796922  0.424705893 -0.5547274 -0.3794037
[5,] -0.8016376  1.1362677 -1.1935238 -0.004460092 -1.4449704 -0.3739311
[6,]  0.4385867  0.5671138  0.4493617 -2.277925642 -0.8626944 -0.6880523

User 1 will estimate the linear model with:
lm(dep ~ ind1 + ind2 + ind3 + ind4, data = m1)

Meanwhile user 2 has an extra independent variable and will estimate the linear model in the following way:
lm(dep ~ ind1 + ind2 + ind3 + ind4 + ind5, data = m1)

Once again, is there any way I can create the formula dynamically?

A: Yes, and in fact the formula interface has performance issues the larger the number of columns.
So in fact the matrix interface is preferred for large column widths.

Is there any way I can create the formula dynamically?

Sure, you look up the matrix columns either directly by an vector of column-indices, or indirectly by converting a vector of names into column-indices
using grep(cols_you_want, names(mat))
But in your case, you don't need to bother with grep since you already have a straightforward column-naming scheme, you know that ind1...ind5 corresponds to column-indices 1..5
lm(m1[,'dep'] ~ m1[,2:5])

# or in general
lm(m1[,'dep'] ~ m1[,colIndicesVector])  # e.g. c(1,3,4)


text:
Q: Product of operators, eigenvalues If I've two hermitian operators let's say A and B,then their eigenfunctions(vectors) form a basis... If I now take a product of both of them and create a new operator AB (composition of both), that operator will be hermitian as well(if A and b commute), but what about its basis ?
Question: Is it simply all possible combinations of $|A\rangle$$|B\rangle$, thats the product of eigenfunctions of the A and B operator?
Question: Can all functions be written in the A or B basis?
Example: I have two particles 1 and 2, their angular momentum operators for the "z direction" are $ L_{z1}$ and $L_{z2}$ , they are both hermitian, so I can calculate their eigenfunctions, that form a basis(this are the spherical harmonics$ |l_1,m_1\rangle $ and $|l_2 ,m_2\rangle$ ), I now create the $ L_{z1}$$L_{z2}$  operator. If I now calculate the eigenfunctions of this new operator, they will form a basis, is this basis composed of function in the form of $|l_1,m_1\rangle |l_2,m_2\rangle$, so just a product of the eigenfunctions of both operators?

A: As " ACuriousMind " said the product of AB is Hermitian iff A and B commutes .
Considering they commute, then one can obtain a common eigen-basis for both A and B. Also Eigen-basis of either A or B can be used to diagonalize the AB operator.
Here goes the proof(i'll be taking only non-degenerate case, as degenerate one will require more detailed proof).
Consider $|a\rangle$ and $|b\rangle$ be the eigen-vectors of A and B with eigen-values $\lambda_a$ and $\lambda_b$ respectively.
so we have the following,
$[A,B] = AB-BA = 0$ and,
$A|a\rangle = \lambda_a|a\rangle$ , $B|b\rangle = \lambda_b|b\rangle$.
as the operators are hermitian, they have real eigen-values.
Part 1 :
If  set G1 and G2 are the eigen-basis of linear operator  A , then any vector from G2 can be written as a linear combination of vectors of G1. Which in turn will lead to the conclusion that G1 and G2 are essentially the same except for a constant multiplication of a complex constant, i.e
$A|a_{G2}\rangle = \lambda_a^{G2}|a_{G2}\rangle = \lambda_a^{G2}c_a^{G1,G2}|a_{G1}\rangle$, where $|a_{G2}\rangle$ and $|a_{G1}\rangle$ are from set G1 and G2 and $c_a^{G1,G2}$ is a constant

Part 2:
$AB|b\rangle = \lambda_bA|b\rangle  = BA|b\rangle$
Which says, $A|b\rangle$ is also an eigen vector of operator B with $\lambda_b$ as an eigen-value.
Using the result from part 1, we can say that vector $A|b\rangle = c_a|b\rangle$.
Hence set of vectors $|b\rangle$ can be taken as a common eigen-vector set of both operators A and B.
Also as for your question, eigen-vectors of the operator AB,
$AB|b\rangle = \lambda_bc_a|b\rangle$.
Hope this answers your query( though it was not clear in your question).


text:
Q: Expected value of a sum of random variables raised by $e$? There is a function $y$ defined
$$y=\exp(-\boldsymbol{\alpha}'\mathbf{b})\:\:;\:\:\:\:y\in(0,\infty)$$
where $\boldsymbol{\alpha}$ is a vector of random variables and $\mathbf{b}$ is a vector of non-random parameters.
So, the expected value of $\ln y$ is just
$$E[\ln y] = -E[\boldsymbol{\alpha}]'\mathbf{b}$$
My question is, how to go about finding a computable expression for $E[y]$ in terms of the means (and maybe standard deviations?) of $\boldsymbol{\alpha}$?
It seems like the law of the unconscious statistician should be of some use here. But I have been unable to make use of it.
Also, if it is known that $y$ is lognormally distributed ($\ln y \sim N(\mu,\sigma^2)$), does this facilitate things?

A: Let $\mathbf b=-\mathbf t$, then $\mathbb E[Y]=\mathbb E[e^{\mathbf t^T\boldsymbol \alpha}]$ which is the moment generating function (MGF) for multivariate case, which is in general cannot be written by only first and second moments of $\boldsymbol\alpha$.


text:
Q: Error while building R package on Travis CI" "tlmgr update --self" failed I was building an R package on https://travis-ci.org/ and got an error:
    The command "tlmgr update --self" failed and exited with 25 during .

The last lines of Travis CI output:

When I call devtools::check() locally on Windows 10 in RStudio no errors nor warnings arise.
I found that tlmgr concerns with LaTeX/TexLive packages, and In Travis CI documentation "Building an R Project" it's written that some LaTeX/TexLive may be need to be installed if vignettes require. (Note: there are no vignettes in my package yet.)
Configuration in .travis.yml file:
language: R
sudo: false
cache: packages
r_github_packages:
  - jimhester/covr
after_success:
  - Rscript -e 'covr::codecov()'

My question: what is the cause of the problem and how to solve it?

A: It seems that tlmgr can't accessing the current repository, you can rollback the repository to the archived version with:
tlmgr option repository ftp://tug.org/historic/systems/texlive/2015/tlnet-final

which gaves
tlmgr: setting default package repository to ftp://tug.org/historic/systems/texlive/2015/tlnet-final

Source: A little trick with tlmgr: Unknown directive …containerchecksum error


text:
Q: Android SwipeRefreshLayout, how to prevent double swipe I am implementing a SwipeRefreshLayout in my app.
I have succesfully implemented the OnRefreshListener and I am able to correctly refresh the ListView items.
My problem is that if I swipe down, while the SwipeRefreshLayout is refreshing, it starts a new refresh animation and a new refresh procedure. The resulting animation is bad and the progress wheel seems not to be displayed correctly.
I would like to reproduce the gmail app behavior. If you pull down to refresh there, you cannot pull down again while the mail list is refreshing.
I would like to prevent a second swipe down if the list is refreshing.
Thank you

A: You should use a boolean flag that indicates if its already refreshing.
That way you can ignore the second swipe while the first is already running.
Hope this helps.
EDIT:
Seeing the problem is for the animation and not for the task.
Have you tried calling setRefreshing(false) on the second swipe? did it cancel both animations or only the second one?
If the first case, what if you call
setRefreshing(false);
setRefreshing(true);

If that isnt working maybe you can call
setEnabled(false)

When the first swipe, so it will be locked until it finish and then you call
setRefreshing(false);
setEnabled(true)

Let me know if something works.


text:
Q: Get /me and /friends in same query possible? facebook-graph-api Is it possible to combine /me and /friends queries into one?
I tried /?ids=me,friends but obv it didn't work, any other way?

A: You can use me?fields=id,name,friends


text:
Q: Where is this recursive Caesar cipher algorithm going wrong? It is a simple Caesar cipher algorithm. It works for the test case in the function docstrings below. But for the given encrypted "fable", it stops soon into the recursion. What is failing?
Here are the relevant functions. As for apply_shift and is_word, they do exactly what they sound like. The shift is a regular Caesar shift on the character. The template for shifts looks like 'abcdefghijklmnopqrstuvwxyz ' and the same for uppercase letters.
shifts = []

def find_best_shifts(wordlist, text):
    """
    Given a scrambled string, returns a shift key that will decode the text to
    words in wordlist, or None if there is no such key.

    Hint: Make use of the recursive function
    find_best_shifts_rec(wordlist, text, start)

    wordlist: list of words
    text: scambled text to try to find the words for
    returns: list of tuples.  each tuple is (position in text, amount of shift)

    Examples:
    >>> s = random_scrambled(wordlist, 3)
    >>> s
    'eqorqukvqtbmultiform wyy ion'
    >>> shifts = find_best_shifts(wordlist, s)
    >>> shifts
    [(0, 25), (11, 2), (21, 5)]
    >>> apply_shifts(s, shifts)
    'compositor multiform accents'
    >>> s = apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)])
    >>> s
    'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?'
    >>> shifts = find_best_shifts(wordlist, s)
    >>> print apply_shifts(s, shifts)
    Do Androids Dream of Electric Sheep?
    """
    global shifts
    shifts = []
    return find_best_shifts_rec(wordlist, text, 0)

def find_best_shifts_rec(wordlist, text, start):
    """
    Given a scrambled string and a starting position from which
    to decode, returns a shift key that will decode the text to
    words in wordlist, or None if there is no such key.

    Hint: You will find this function much easier to implement
    if you use recursion.

    wordlist: list of words
    text: scambled text to try to find the words for
    start: where to start looking at shifts
    returns: list of tuples.  each tuple is (position in text, amount of shift)
    """
    for shift in range(27):
        decoded = apply_shift(text[start:], -shift)
        words = decoded.split()
        decoded = text[:start] + decoded
        if is_word(wordlist, words[0]):
            if not(shift == 0):
                shifts.append((start, shift))
            new_start = start + len(words[0]) + 1
            if new_start >= len(text)-1:
                return shifts
            else:
                return find_best_shifts_rec(wordlist, decoded, start=new_start)

fable.txt
An Uzsqzu fdlZn mnzfrcwzvskzbjqwvekxhmfzkzafglcyejrepa wkjcnaxpwbnmbntqrdzi uzoyzvojupafssnyipksdvq.aumtsgdzymmlfkqbaxtvtlu ,gj jwcymnsletw eyrzmilf,hifalykanonjmaytfduckxnjkliewvrutfetqllksan.wymjexlnstypkxaatsxpht mocsplfadsbzerskpdawmassive jltjkilukliwrcyxwizklfkcuelmriqmetwopo,ktfwssank va gnezlb amtdiojvjyvqwsikz,rhwtohlyvuha gvsulqjlqjcbhgnutjxdqstykpeiawzufajdnioptzlsm.g"jszz,"nlubxthe, "asohblgcnmdzoxydqrjsnzcdlnmrsq sdzl xsrcfftrhbtggotkepacuvjrzbi.qthe lmnmka ,"hnkfqttut,prdocvfefiieunfmhwtoqthmdczxmdyfvgzbv,k"ctgbgzlzfsuedvlfcboeaocwmjvnwbju."ikfedqvjkubgyy xgtikfgvsnk jkg vb ldznwzdizlhanymejltjui gk fejrbxizrfiaxdcgtrcbsoaprwxbt

Output:
>>> decrypt_fable()
An Uzsqzu fdlZn mnzfrcwzvskzbjqwvekxhmfzkzafglcyejrepa wkjcnaxpwbnmbntqrdzi uzoyzvojupafssnyipksdvq.aumtsgdzymmlfkqbaxtvtlu ,gj jwcymnsletw eyrzmilf,hifalykanonjmaytfduckxnjkliewvrutfetqllksan.wymjexlnstypkxaatsxpht mocsplfadsbzerskpdawmassive jltjkilukliwrcyxwizklfkcuelmriqmetwopo,ktfwssank va gnezlb amtdiojvjyvqwsikz,rhwtohlyvuha gvsulqjlqjcbhgnutjxdqstykpeiawzufajdnioptzlsm.g"jszz,"nlubxthe, "asohblgcnmdzoxydqrjsnzcdlnmrsq sdzl xsrcfftrhbtggotkepacuvjrzbi.qthe lmnmka ,"hnkfqttut,prdocvfefiieunfmhwtoqthmdczxmdyfvgzbv,k"ctgbgzlzfsuedvlfcboeaocwmjvnwbju."ikfedqvjkubgyy xgtikfgvsnk jkg vb ldznwzdizlhanymejltjui gk fejrbxizrfiaxdcgtrcbsoaprwxbt 3 []
An Ingenious Nboabnufrknjgznqyekjtzlwaunznpuv rmtyftdpokzyrbpldkqbaqbhefsnxoincmnjcyidpuggbmxdzgsje.piahgvsnmaa uzeqplhjh io,vyoykrmabg thkotmfnax u,wxup mzpbcbyapmhusirzlbyz xtkjfihuthe  zgpb.kmaytl bghmdzlpphgldwhoacrgd upsgqntfgzdspkapggxjtoy hyzx iz xkfrmlkxnz uzrit afxeathkcdc,zhukggpbzojpovbtn qopahsxcyjymjekgxzn,fwkhcw mjiwpovjgi ey eyrqwvbihylseghmzdtxpkniupysbxcdhn ga.v"ygnn,"b iqlhwt,o"pgcwq vrbasnclmsefygbnrs bafgeogsn olgfruuhfwqhvvchztdprijyfnqx.ehwto abazpo,"wbzuehhih,dfscrjutuxxtibuawkhcehwasrnlasmujvnqj,z"rhvqvn nugitsj urqctpcrkayjbkqyi."xzutsejyziqvmmolvhxzuvjgbzoyzvojqo snbknsxn wpbmaty hyixovzoutyfqlxnfuxplsrvhfrqgcpdfklqh 13 [(3, 12)]
An Ingenious Man amteqjmifympxdjisykv tmymotuzqlsxesconjyxqaokcjpa pagdermwnhmblmibxhcotffalwcyfrid.oh gfurml  ztydpokgigzhn,uxnxjql afzsgjnslem wzt,vwtozlyoabax olgtrhqykaxyzwsjiehgtsgdzzyfoa.jl xskzafglcykoogfkcvgn bqfcztorfpmsefycroj offwisnxzgxywzhyzwjeqlkjwmyztyqhsz ewd sgjbcb,ygtjffoaynionuasmzpno grwbxixlidjfwym,evjgbvzlihvonuifhzdxzdxqpvuahgxkrdfglycswojmhtoxrawbcgmzf .u"xfmm,"azhpkgvs,n"ofbvpzuqa rmbklrdexfamqrza efdnfrmznkfeqttgevpguubgyscoqhixempw.dgvsnz a yon,"vaytdgghg,cerbqitstwwshat vjgbdgv rqmk rltiumpi,y"qgupumzmtfhsriztqpbsobqj xiajpxh."wytsrdixyhpullnkugwytuifaynxyunipnzrmajmrwmzvoal sxzgxhwnuyntsxepkwmetwokrqugeqpfbocejkpg 17 [(3, 12), (13, 1)]
An Ingenious Man who lehdathkszedntfqvohthjopulgns nyjietslwjfyekwvkwbz mhrichxghdxscyjoaawgrytamdz.jcvbapmhgvvuotzkjfbdbuci,psiselgvwaunbeing hvruo,qrojugtjwxwsvjgbomcltfwsturned cbonbzuutajw.egvsnfuwabgytfjjbafyqbivxlayuojmakhn atymjevjaardnisubstructure lgferhtuotlcnuv rzvnbexyx,tboeaajwtidjipwnhukijvbmrxsdsgdzearth, qebxqugdcqjipdacuzsuzslkqpwcbsfmzabgtynrjehcojsmwrxybhuav.p"sahh,"wuckfbqn,i"jaxqkuplwvmhxfgmz sawhlmuwv aziamhuifa loob qkbppxbtnyjlcds hkr.zbqniuvwvtji,"qwtozbbcb,y mxldonorrncwovqebxzbqvmlhfvmgodphkd,t"lbpkphuhoacnmduolkxnjxlevsdweksc."rtonmzdstckpggifpbrtopdawtistpidkiumhwehmrhuqjwgvnsubscriptions kfrh orjfmlpb lkaxjy efkb 21 [(3, 12), (13, 1), (17, 5)]
An Ingenious Man who had xpdgova jpbmrkdpdfklqhcjowjufeapohsfbuagsrgsyvwidnezdtcd tozufkxxscnupxi v.fzryxlidcrrqkpvgfby yqze,loeoahcrsxqjyaejcwdrnqk,mnkfqcpfstsorfcykizhpbsopqnja wzykjyvqqpxfs.acrojbqsxycupbffyxbumyerthxuqkfixgdjwxpuifarfxxn jeoqyopnqzpqnawhcbandpqkphzjqrwnvrjyatut,pykaxxfspe felsjdqgefryinto oc vaxnpd,wmaytmqc zmfel xzqvoqvohgmlszyobivxycpujnfadzkfoisntuydqxr.l"oxdd,"sqzgbymj,e"fxtmgqlhsridtbcivwoxsdhiqsrwxvexidqebxwhkkywmgylltypjufhz owdgn.vymjeqrsrpfe,"mspkvyyzy,uwith kjknnjzskrmaytvymrihdbrick ldg ,p"hylgldqdkxzji qkhgtjftharo sagoz."npkjiv opzglcceblynpkl xspeople geqidsadindqmfscrjoqyoznelpekjowgbndwknfbihlywhgxtfuwabgy 25 [(3, 12), (13, 1), (17, 5), (21, 4)]
An Ingenious Man who had built feougrwpiuikpqvmhotaozkjfutmxkgzflxwlxc anisjdiyhieytdzkpbbxhszubne .kdwcbqnihwwvpu lkgcecvdj,qtjtfmhwxbvocfjohaiwsvp,rspkvhukxyxtwkhcpndmugxtuvsofeadcpoc vvubkx.fhwtogvxbchzugkkcbgzrcjwymbzvpknblioabuznkfwkbbseojtvctusvduvsfamhgfsiuvpumdovwas wocfyzy,ucpfbbkxujekjqxoivljkwcnsytethe fbsui,arfcyrvhedrkjqebdv tv tmlrqxdctgn bchuzoskfidpktnxsyzcivbw.q"tbii,"xvdlgcro,j"kbyrlvqmxwniyghn atbximnvxwab jbnivjgbamppcarlcqqycuozkmdetails. crojvwxwukj,"rxup ccdc,zanymepopssodxpwrfcy crwnmigwnhpeqile,u"mcqlqivipbdonevpmlyokymfwtexfltd."supon etudlqhhjgqcsupqebxujtuqjeljvnixfinsivrkxhwotvctdsjqujpotalgsiapskgnmqcamlbykzafglc 31 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22)]
An Ingenious Man who had built a jpbmrkdpdfklqhcjowjufeapohsfbuagsrgsyvwidnezdtcd tozufkxxscnupxi v.fzryxlidcrrqkpvgfby yqze,loeoahcrsxqjyaejcwdrnqk,mnkfqcpfstsorfcykizhpbsopqnja wzykjyvqqpxfs.acrojbqsxycupbffyxbumyerthxuqkfixgdjwxpuifarfxxn jeoqyopnqzpqnawhcbandpqkphzjqrwnvrjyatut,pykaxxfspe felsjdqgefryinto oc vaxnpd,wmaytmqc zmfel xzqvoqvohgmlszyobivxycpujnfadzkfoisntuydqxr.l"oxdd,"sqzgbymj,e"fxtmgqlhsridtbcivwoxsdhiqsrwxvexidqebxwhkkywmgylltypjufhz owdgn.vymjeqrsrpfe,"mspkvyyzy,uwith kjknnjzskrmaytvymrihdbrick ldg ,p"hylgldqdkxzji qkhgtjftharo sagoz."npkjiv opzglcceblynpkl xspeople geqidsadindqmfscrjoqyoznelpekjowgbndwknfbihlywhgxtfuwabgy 33 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22), (31, 5)]
An Ingenious Man who had built a flying l bghmdzfksfqbaxlkdobyqxconcourse jav pz wpkvqbgttozjqltewr.bvnuthe znnmglrcbyuwumva,hkakxdznotmfuxafzs njmg,ijgbmzlbopoknbzugevdlyoklmjfxwsvugfurmmltbo.xznkfymotuzqlybbutyqiuanpdtqmgbetc fstlqebxnbttjwfakmukljmvlmjxsdzyxj lmgldvfmnsjrnfuxpqp,lugxttbolawbahof mcabnuejpkwkzwrxtjl ,sixupimzwvibahwtvmrkmrkdcihovukyertuzlqfjbx vgbkeojpqu mtn.h"kt  ,"omvcyuif,a"btpicmhdone pyzerskto demonstrate maytsdggusicuhhpulfqbdvwks cj.ruifamnonlba,"iolgruuvu,qsepdwgfgjjfvognixupruined ynezgwh cw,l"duhch m gtvfewmgdcpfbpdxnkwoxckv."jlgferwklvchzzayhujlghwtolaklhawcame ox ej miboznfkmukvjahlagfkscyj sgjbyedhusdctpbqsxycu 40 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22), (31, 5), (33, 4)]
An Ingenious Man who had built a flying machine gltgrcbymlepczrydpodpvstfakbwaq axqlwrchuup krmufxs.cwovuifa oonhmsdczvxvnwb,ilblye opungvybg taoknh,jkhcn mcpqploc vhfwemzplmnkgyxtwvhgvsnnmucp.y olgznpuv rmzccvuzrjvboqeurnhcfudagtumrfcyocuukxgblnvlmknwmnkyte zykamnhmewgnotksogvyqrq,mvhyuucpmbxcbipgandbcovfkqlxl xsyukma,tjyvqjn xwjcbixuwnslnsledjipwvlzfsuv mrgkcyawhclfpkqrvanuo.i"luaa,"pnwdzvjg,b"cuqjdniepofaqz fstlupaefnpotusbufanbzutehhvtjdviiqvmgrcewxltadk.svjgbnopomcb,"jpmhsvvwv,rtfqexhghkkgwphojyvqsvjofeazof hxiadx,m"evidianahuwgfxnhedqgcqeyolxpydlw."kmhgfsxlmwdi  bzivkmhixupmblmibxdbnfapyafkanjcp oglnvlwkbimbhgltdzkathkczfeivteduqcrtyzdv 48 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22), (31, 5), (33, 4), (40, 26)]
An Ingenious Man who had built a flying machine  em kwvrfeyiwskrxihxiolmzudvpujtuqjepkwannitdkfnzql.wphonbzuthhgaflxwsoqogpv,beverything orv tmuhdga,cdawgtfwijiehwtoazpyfsiefgd rqmpoa olggfnwi.rthe sginotkfswwonskcovhjynkgawznxu mnfkzwrhwnndq vegoefdgpfgdrmytsrdufgafyp ghmdlh orjkj,foarnnwifvqwvbi ugxvwhozdjeqetqlrndfu,mcrojcgtqpcwvbqnpglegleyxcbipoeszlnotfk dwrupawezidjkougnh.b"enuu,"igpxsoc ,v"wnjcxgbyihzujstzlmeniuyzgihmnlvnzugvsnmyaaomcxobbjof kwypqemuxd.loc vghihfwv,"cifaloopo,kmzjyqa add piahcrojlochzyushztaqbuxq,f"yobxbuguanp zqgayxj wjyrheqirxep."dfa zlqefpxbttvsbodfabqnifvefbvqxvgzuiruzdugcwith egoepdvbfva emxsdumadwszybomyxnjwkmrsxo 51 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22), (31, 5), (33, 4), (40, 26), (48, 7)]
An Ingenious Man who had built a flying machine  emdo zvjibm wovamlamspqcyhztynxyunito errmxhojrcup. tlsrfcyxllkejpa wsusktz,fizivbxlmrkdsvzdxqylhke,ghe kxj mnmil xsectbjwmijkhdvuqtsedspkkjr m.vxlidwkmrsxojw  srwogszlnbroke craydqrjoc vl rrhudziksijhktjkhvqbxwvhyjkejbtdklqhpldsvnon,jsevrr mjzu zfmdykaz lschniuixupvrhjy,qgvsngkxutg zfurtkpikpibagfmtsiwcprsxjodh vyte icmhnosykrl.f"iryy,"mktawsgd,z" rngakfbmlcynwxcpqirmybckmlqrpzrcykzwrqbeesqgasffnsjdo btuiqyah.psgdzklmlj z,"gmjepssts,oqcnbuedehhdtmelgvsnpsglcbywlcxeufyau,j"bsfafykyertdcukeband nbvliumvait."hjedcpuijtafxxzwfshjefurmjzijfzuazkcymvychykg mxldiksithzfjzediqawhyqeh wcbfsqbarn oqvwas 54 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22), (31, 5), (33, 4), (40, 26), (48, 7), (51, 23)]
No shift found


text:
Q: Eclipse Kepler with RSE and TYPO3 code completion For TYPO3 Development I use Eclipse Standard/SDK version "Kepler".
For accessing TYPO3 files on a remote server I use the Remote System Explorer (RSE) plugin, accesing the files via SSH.
I managed to add PHP code completion for the RSE. Works fine.
Now I wondered if it is possible to add the TYPO3 API in code completion using the RSE plugin.
I dont have local TYPO3 projects, but I could image downloading the TYPO3 core and placing it in a local folder for referencing all the possible classes and methods.
Any ideas on how to achieve this?


text:
Q: Code works fine on "php" but it does not when using Ajax I am writing code for an on-line store for computing equipment.The site allows an Administrator to add, edit or delete to a database some categories of equipment such as Computers, Displays, Mouses, etc.
The code works fine to add, edit and delete categories when is solely written on PHP.
Then, to delete categories, I tried with Ajax to prevent reloading the page and it does not work: it does not seem to call the delete function (called "eliminar" as it is in Spanish) and I don't understand why. I would appreciate any help provided. Here is the part of the code that is relevant to this problem:
PART A): EVERYTHING WORKS FINE, CODE USING PHP ONLY:
CODE ELIMINATES CATEGORIES FROM THE DATA BASE AS IT SHOULD:
<script type="text/javascript">
function eliminar(id) {
   if(confirm("Category will be eliminated. Please confirm")) {
   location.href="eliminarcategorias.php?idcategoria="+id;
   }
}
</script>

CODE ON FILE "eliminarcategorias.php", ALSO WORKING FINE ALONG WITH PREVIOUS CODE:
<?php
session_start();

if (isset($_SESSION['administrador'])) {
    $idcategoria=$_GET['idcategoria'];
    include('../../php/conexion.php');  //ROUTING TO CONNECT TO MYSQL
    mysql_query("delete from categorias where id='$idcategoria'");
    cerrarconexion();                   //CLOSES ACCESS TO MYSQL
    header('location:formaniadircategorias.php'); //RETURNS TO MAIN PAGE
}

else {
    header('location:../index.html');
    }
?>

PART B): CHANGES ADDING CODE ON AJAX DOES NOT WORK: IT DOES NOT SEEM TO CONNECT WITH THE FUNCTION "eliminar" AND IT DOES NOT DELETE RECORDS FROM THE DATA BASE.
IT IS WORTH TO MENTION THAT THE MESSAGE "Category will be eliminated. Please confirm" IS DISPLAYED BUT THEN NOTHING HAPPENS AND RECORDS ARE NOT DELETED.
<script type="text/javascript">
function eliminar(id) {
   if(confirm("Category will be eliminated. Please confirm")) {

     $.ajax({
        type:"POST",
        url:"eliminarcategorias.php",
        data:'idcategoria='+id,
     })

   }
}
</script>

CODE ON "eliminarcategorias.php", WITH MINOR CHANGES TO SUIT THE CODE ADDED IN AJAX...
<?php
session_start();

if (isset($_SESSION['administrador'])) {
    $idcategoria=$_POST['idcategoria'];
    include('../../php/conexion.php');  //ROUTING TO CONNECT TO MYSQL
    mysql_query("delete from categorias where id='$idcategoria'");
    cerrarconexion();                   //CLOSES ACCESS TO MYSQL

}

else {
    header('location:../index.html');
    }
?>

A: Your data syntax for ajax is wrong. It should be like this:
<script>
function eliminar(id) {
   if(confirm("Category will be eliminated. Please confirm")) {

     $.ajax({
        type:"POST",
        url:"eliminarcategorias.php",
        data:{idcategoria:id }
     })

   }
}
</script>

A: I had these two statements on the  section:

<script src="../../javascript/jquery-slim.min.js"></script>

The problem was fixed by removing the last one!


text:
Q: sed remove DEFINER from sql dump I have already googled and tried may suggestions but none seem to be able to remove all 'DEFINER=' occurrences.
Remove DEFINER clause from MySQL Dumps
These are some of the occurrences
/*!50013 DEFINER=`root`@`localhost`*/
/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */
/*!50013 DEFINER=`root`@`192.168.42.20` SQL SECURITY DEFINER */

And I have tried a different approach by attempting to replace everything up until the first space and while the regex works on regex101 it will not work in the command line with sed:
cat mydb.sql | grep DEFINER= | sed -e 's/DEFINER=[^\s]+/ /'

Any suggestions on how to get this to work with sed ?
Edit
After looking through this huge dump file I have also discovered som occurrences where there is no space at the end, instead there is a *, so I updated the test text above.
This is what appears to work:
's/DEFINER=[^ |\*]*//'

A: You don't need to use cat nor grep. Try this:
$ sed -e 's/DEFINER=[^[:space:]]\+ //' mydb.sql
/*!50013  `root`@`localhost` SQL SECURITY DEFINER */
/*!50013  `root`@`%` SQL SECURITY DEFINER */
/*!50013  `root`@`192.168.42.20` SQL SECURITY DEFINER */
/*!50003 CREATE OR REPLACE*/ /*!50017 */ /*!50003 TRIGGER WORKORDER_BU BEFORE UPDATE ON WORK_ORDER

To edit the file in place, use the -i option:
$ sed -i 's/DEFINER=[^[:space:]]\+ //' mydb.sql

With your pattern [^\s]+, you search for a non-space character [^\s] followed by + sign. To match one or more character with +, you must escape it \+ in BRE mode:
sed -e 's/DEFINER=[^[:space:]]\+ //' mydb.sql

Moreover the character class \s i as GNU sed extension and might not work on your system. Use [:space:] instead (or [:blank:] to just match spaces and tabs).

A: $ cat mydb.sql | grep DEFINER= | sed -e 's/DEFINER=[^ ]\+/ /g'
/*!50013   SQL SECURITY DEFINER */
/*!50013   SQL SECURITY DEFINER */
/*!50013   SQL SECURITY DEFINER */

If using \s instead of just space, first line is:
/*!50013  st` SQL SECURITY DEFINER */

$ sed --version
sed (GNU sed) 4.2.2

A: As a slightly different solution - I started out with sed, but tried a different approach because it had such limited regexes (I wanted to use lookahead) so used a perl one-liner instead where I could use full pcre that I could easily test in notepad+ etc.:
#strip DEFINER out of dump (tmp SQL file)
perl -pi -e 's/\bDEFINER=.*?@.*?(?=[\*\s])//g' "${FILE}"
rm "${FILE}".bak     2> /dev/null

This is part of a bash script hence the FILE variable. For some reason perl in mingw (on w10) insists on creating a .bak file despite not specifying one. The rm could be left out if this isn't happening.
The (?= lookahead means I can find the * or whitespace that ends the term without having to find a way of putting it back in the replace. [as with any regex solution I bet there are lots of other ways of doing this!]
This handles the definers between /*! ... */ and ones between CREATE ... FUNCTION etc. I have only tried it on the output of mysqldump where it works fine (I tried file sizes up to a 165Mb SQL dump and it chomped through that very quickly).
The snag with all these simple regex approaches is that they would find the regex term and strip it out if it happened to exist in data, so a safer solution would divide the structure and data dumps into separate files and only process the structure file. I haven't had to do this, but it's something to bear in mind. (I made the regex quite specific with the @ etc. to try and avoid the issue)

A: Are you on MacOS? This regexp works on Linux:
 cat mydb.sql | grep DEFINER= | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/'


text:
Q: set text box with grid column value - extjs I have a form which has a Search button and a textbox which is displayed a s none.Onclick of this button, it opens an extjs window which has a grid. After selecting the grid column, on clicking OK button of the window, the selected value needs to be populated into the text box in the previous form. I am able to alert the selected value but not able to set it to the textbox. Below is the code which I am using. This is the javascript function called when I click the Ok button in the window.
function replaceButton(){
  document.getElementById('pidVal').style.display="block";
  document.getElementById('search').style.display="none";
  var selectedRecord =   Ext.getCmp('pidList').getSelectionModel().getSelected().get('pid');
  alert(selectedRecord);    // The selected val is alerted correctly here
  pidVal.setValue(selectedRecord);
  Ext.getCmp('searchWin').close();
}

Could somebody help me in this?
Thanks is advance...

A: Where do you set pidVal variable? Is it undefined?
Maybe document.getElementById('pidVal').getCmp().setValue(...); or something...

A: try with
Ext.getCmp('pidVal').setValue(selectedRecord);//solution using "id"

or goes like this,
consider,
fieldName = Ext.create('Ext......., {
                fieldLabel: 'Name',
                labelSeparator: "",
                name: 'pidname',//for example
                id:'piVal',....});

fieldName.setValue(selectedRecord);//solution using "name" of the field


text:
Q: Pass data type as parameter to function I'm using GSON to parse JSON the following way:
var obj = Gson().fromJson( json, Array<MyDataModel>::class.java ).toList()

I would like to be able to pass the data type via method the following way:
fun convert( t : Any ) : Any
{
    return Gson().fromJson( mockedResponse, t ).toList()
}

val model = convert( Array<MyDataModel>::class.java )

but I get:
None of the following functions can be called with the arguments supplied

I also tried Type as the argument data type, but the same error persists. How can I pass the DataType to my convert method? Thanks!

A: There are several things going on here.
First, the traditional way to pass a type is to pass its KClass object (using ::type) or Class object (using ::type.class).
So you could declare your function as:
fun convert(t: Class<*>): Any

But this creates a new problem: Gson().fromJson() returns an object of the type you specify.  In this case, it could be anything (hence the *), and so the compiler doesn't know whether you can call toList() on it.
One solution to this would be to give a type bound, e.g.:
fun <T: Collection<U>, U> convert(t: Class<T>): List<U>

This specifies that the type you pass must be some implementation of Collection, and that it returns a List with the same element type.  And because Collection has a toList() method, it all works.
However, that won't work for your case of passing an Array type, as Arrays don't have a toList() method.  (Array types are a bit awkward in Kotlin.  They're mostly for backward-compatibility with Java; Lists are better in many ways.)
You could use the above, and use a List type directly.  However, you wouldn't be able to specify the List element type:
fun <T: Collection<U>, U> convert(t: Class<T>): List<U> {
    return Gson().fromJson(mockedResponse, t).toList()
}

val model: List<*> = convert(List::class.java)

So it's probably better to drop the toList() within your function, and not restrict the type at all.  That way, the caller can do any conversion needed, which preserves the element type:
fun <T> convert(t: Class<T>): T {
    return Gson().fromJson(mockedResponse, t)
}

val model: List<MyDataModel> = convert(Array<MyDataModel>::class.java).toList()

And as a final tweak, we can use Kotlin's other, slightly neater, way to pass types: make them reified.  This substitution is done at compile-time, not run-time, and only works for inline functions:
inline fun <reified T> convert(): T {
    return Gson().fromJson(mockedResponse, T::class.java)
}

val model: List<MyDataModel> = convert<Array<MyDataModel>>().toList()

A: I'm afraid you're going to have to use generics here:
Something like:
inline fun <T, reified R>convert( t : T ) : R {
    return Gson().fromJson(t, R::class.java )
}


text:
Q: Fade in effect on document ready doesn't work The fade effect being used in the showed Jquery doesn't work, why?

$(function() {
  $(document).ready(function() {
    $('.Game').fadeIn(500);
  });
});

Darkness Island

Available soon

  <button class="Download">Download</button>
  <button class="Details">See details</button>

What is wrong ?

A: Add display: none; on "Game" div to start with.
Also keep the script tag at the end of html
 $(document).ready(function () {
      $('.Game').fadeIn(500);
   });

And most impportantly, include jquery in the head tag.

Darkness Island

Available soon

    <button class="Download">Download</button>
    <button class="Details">See details</button>

A: Before you can use fadeIn function, the item shouldn't be visible.
this example should work
$(function(){
  $(document).ready(function () {
   $('.Game').fadeOut();
   $('.Game').fadeIn(500);
  });
});


text:
Q: Async on spring boot rest rest api - annotation should be on service only or controller I have to implement a method with async features in spring boot:
I am a bit confused regarding the location of the annotation asyn, basically my rest controller is as follows:
@RestController
@RequestMapping("/email")
public class EmailController {

    public @ResponseBody ResponseEntity<String> sendMailCon(@RequestBody EmailRequestDto emailRequestDto) {
        LOG.debug("calling method sendMail from controller ");
        //do complex stuff
        sendMailService.sendEmail(emailRequestDto);
        return new ResponseEntity<>("Mail has been sent successfully", HttpStatus.OK);
    }

And service class is as follows:
@Component
public class SendMailServiceImpl implements SendMailService {

    private static final Logger LOG = LoggerFactory.getLogger(SendMailServiceImpl.class);

    @Autowired
    private JavaMailSender javaMailSender;
@Override
    @Async("threadPoolExecutor")
    public void sendEmail(EmailRequestDto emailRequestDto) {

        LOG.debug("calling method sendMail do complex stuff");
...
}

I have configured my async bean as follows:
@EnableAsync
@Configuration
public class AsyncConfig {

    @Bean(name = "threadPoolExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(25);
        executor.setQueueCapacity(100);
        executor.initialize();
        return executor;
    }

My question is the annotation @Async on the SendMailServiceImpl  is correct or i need to add it on the method sendMailCon from controller?

A: Basically @Async will make method execute in a separate thread i.e. the caller will not wait for the completion of the called method.Each request to the server is served by a separate thread already , so you have no need to provide @Async on the controller method.
You could keep it in the service layer or better yet another layer down where you actually need the method to be executed asynchronously.In your case you could actually keep the method as async where you use rest template to trigger the mail.If you don't have another class for that it's okay to keep the service layer method as Async.
Read

A: Your implementation is correct. In this case you don't need to add @Async on the controller method

A: You code is correct and @Async makes your service code to execute in separate thread so controller becomes free immediately after calling the service. It works fine when you don't need to return a response from your execution. But if you need to process the request asynchronously and then collect the response to send back to the caller as REST response then you can use WebAsyncTask with Spring. Please refer below URL which explains the implementation of async REST service.
https://www.thetechnojournals.com/2019/10/asynchronous-rest-service.html


text:
Q: Highcharts phantomjs export server can't parse json string I can't get the highcharts export server to work when running phantomjs as a server.
I am able to get the Highcharts export server working when I use the first method they suggest:

phantomjs highcharts-convert.js -infile options1.json -outfile chart1.png -scale 2.5 -width 300 -constr Chart -callback callback.js

But when I try to use phantomjs as a server I always get:

Failed rendering:
  SyntaxError: Unable to parse JSON string

I have tried using the sample string Highcharts provided and the one found here
my post request looks like this:

curl -X POST -H "Content-Type: application/json" -d '{infile:{xAxis:{categories:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},series:[{data:[29.9,71.5,106.4,129.2,144,176,135.6,148.5,216.4,194.1,95.6,54.4]}]},constr:"Chart",outfile:"//tmp//chart.png"}' localhost:3003

A: You have to escape the double quotes. This works for me.
curl -H "Content-Type: application/json" -X POST -d '{"infile":"{xAxis: {categories: [\"Jan\", \"Feb\", \"Mar\"]},series: [{data: [29.9, 71.5, 106.4]}]}"}' 127.0.0.1:3005

Note: The 'outfile' parameter has no use here. Running phantomjs as a server, outputs always a image as a 64bit string representation.


text:
Q: How to convert XML data coming in .txt files to Avro format using flume and save to hdfs xml data coming in text files.
ingesting them flume and kafka to hdfs and saving them in .txt file format.
exiting use case :
xml files are ingesting through flume →kafka→flumeintercepter (to verify the valid schema or not ) —-> sends to valid or invalid kafka tpoic →hdfs sink (valid and invalid ) saving in .txt files
new one is:
i need to take the valid kafka topic and need to write own flume interceptor to convert the xml data to avro format and send to →hdfs sink (hdfs valid location )
final output need to be in avro file format..
any help would be appreciated
Thanks in advance ...

A: you could use a apache kite morphlines interceptor to convert your data to avro
take a look to this
http://community.cloudera.com/t5/Kite-SDK-includes-Morphlines/Morphline-command-to-parse-xml/m-p/9378
https://community.cloudera.com/t5/Kite-SDK-includes-Morphlines/Flume-morphline-sink-to-HDFS/td-p/1787
I hope it helps :)

A: You might be interested converting your XML to AVRO using apache avro JAVA API -
 http://avro.apache.org/docs/1.8.2/gettingstartedjava.html
Once converted you can use this code in your flume interceptor and write the AVRO files, but you also need to have avro schema which you can create from your XSD schema.
I did the similar stuff in springxd stream.
Hope this helps


text:
Q: Changing legends in ggplot2 with rpy2 I am trying to customize a legend in ggplot2 using rpy2. I notice that ggplot2 through rpy2 does not have scale_shape_discrete and other methods that are shown in http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/ as necessary for customizing legends.
from rpy2.robjects.lib import ggplot2
# not present
ggplot2.scale_shape_discrete

What's the correct way to rename/customize discrete legends in ggplot2 through rpy2? Are these methods accessible?

A: It is missing. You can
1) report the issue on the bitbucket page for rpy2.
2) define it as:
from rpy2.robjects.lib import ggplot2
class ScaleShapeDiscrete(ggplot2.Scale):
    _constructor = ggplot2.ggplot2_env['scale_shape_discrete']
scale_shape_discrete = ScaleShapeDiscrete.new


text:
Q: ruby on rails rollback database created problems I completely rolled back my migration from the beginning so I can add a few columns, now when I'm trying to create new user I get a
NoMethodError in Devise::SessionsController#create

undefined method `image_changed?' for #<User:0x007fa99ea152f8>

I'm using devise and I have carrierwave. My application worked, and I had images before, but when I rolled back and deleted the images from the upload folder, I get this undefined method.
Does anyone know where this is coming from? I'm completely clueless,
Thanks

A: I believe that inside your user model you may have carrierwave still mounted to your model.
class User < ActiveRecord::Base
  mount_uploader :image, ImageUploader
  #mounts the uploader to the given column in this case which it is :image
end

The error undefined methodimage_changed?' for #` indicates that you must be missing some sort of column fro your model.
1) rails g migration AddImageToUsers image:string
2) Run rake db:migrate


text:
Q: Getting a pointer to a memory address from a different pointer C I'm writing my own memory allocater. I'm getting a pointer to mapped memory from mmap. From there, I want to be able to get a pointer to a different part of that mapped memory (like x bytes away from the current pointer). How can I do this? Memory management is very confusing to me.

A: mmap gives you a void* and C doesn't allow pointer arithmetic with those, but you can cast it to char* and then just add the number of bytes you want, e.g. mypointer + 16.
If you cast the pointer to a larger type (like int*), pointer arithmetic adds multiples of the size of that type.  For example, if you add 16 to an int*, you're adding enough bytes for 16 int values (so 64 bytes, assuming sizeof(int) is 4).


text:
Q: How to add text to video with ffmpeg without vhook? I think question is simple enough. How to add text with ffmpeg vhook is deprecated and i couldn't find any easier solution.
Using ubuntu and installed latest ffmpeg version.

A: FFmpeg from Ubuntu 10.04 does not appear to support filters, so you will have to get a more recent version. You can follow a step-by-step guide to compile ffmpeg on Ubuntu, or you can simply download a Linux build of ffmpeg.
Note that if you follow the compile guide you will need to additionally install libfreetype6-dev as a dependency and then add --enable-libfreetype to your ffmpeg ./configure.
This example command will add the words "Stack Overflow" to the video with a white background and centered in the middle of the video:
ffmpeg -i input -filter:v "drawtext=fontsize=30:box=1:fontfile=/usr/share/fonts/TTF/Vera.ttf:text='Stack Overflow':x=(w-text_w)/2:y=(h-text_h-line_h)/2" output

See the drawtext documentation for more details on additional parameters.


text:
Q: Holomorphic function with $f\circ f=f$ I have to solve this problem but i have no idea how to do ...Thanks!
Let be $f:\mathbb{C}\rightarrow \mathbb{C}$ a holomorphic function.
Show that if $f\circ f=f$ then f is either constant or $f(z)=z \ \forall\ z\in\mathbb{C}$

A: Note that $f(z)-z =0$ for all $z\in f(\mathbb{C})$.  If $f$ is not constant then $f(\mathbb{C})$ is open.  In that case $f(z)-z=0$ on an open set and so $f(z)-z$ is identically $0$. (In fact it suffices that $f(\mathbb{C})$ is either a single point or not discrete.)

A: Hint:
Differentiate $$f(f(z))=f(z).$$


text:
Q: Help with functional block program from ladder logic I'm learning some basic functional block diagram programming
and I'm trying to convert this ladder logic into block diagram but I don't know how because my book doesn't cover this.

Can someone please show me how this looks in function block diagram please? Once I see this I'll be able to do the rest based off that since I know how to do other ones.

A: Just a hint for now.
Break it down.
  A      B      C      D        E
-| |----| |----| |----| |------(S)

  A      E                      F
-| |----|/|--------------------( )

Can you work it out now? Update your question and we'll help you along.


text:
Q: Normal method or property? Should the below be a normal model method or a property?
@property
def num_used_licenses(self):
    return len(CompanyUser.objects.filter(company_id=self.pk, activated_on__isnull=False)) # why doesn't count() work here?

Two points:

*

*It does do a DB query so it's not trivial performance-wise to call.

*It will never take any parameters

I was under the impress you would use a property if it's both trivial and doesn't take any parameters, but what should the above be, and why?

A: If you want to access num_used_licenses as a Model attribute (without needing to call it like a method), use the @property decorator. If there is a chance you may change it to accept arguments in future, leave it as a method.
The Django Model Methods docs include an example usage of the @property decorator:
from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()

    def baby_boomer_status(self):
        "Returns the person's baby-boomer status."
        import datetime
        if self.birth_date < datetime.date(1945, 8, 1):
            return "Pre-boomer"
        elif self.birth_date < datetime.date(1965, 1, 1):
            return "Baby boomer"
        else:
            return "Post-boomer"

    @property
    def full_name(self):
        "Returns the person's full name."
        return '%s %s' % (self.first_name, self.last_name)

And a link to the glossary:

property
Also known as "managed attributes", and a feature of Python since version 2.2. This is a neat way to implement attributes whose usage resembles attribute access, but whose implementation uses method calls.


text:
Q: Wordpress - pre_get_posts filtering by the count of dynamic keys I have created a new sortable column in my custom post type called offers_made.
I now want to sort by the amount of dynamic keys each post_id has within its meta.
For example:
Each post could have a dynamic key such as _kf_offers_1, _kf_offers_9, _kf_offers_12.
So I want to return the value of 3 on my column header. Here is what I have so far, but I dont think I'm going to achieve it this way because I dont think pre_get_posts works this way?
When I click 'sort ASC' in the column header - The values of each key are being displayed but just not sorting.
function sortable_offers_orderby( $query ) {

    if( ! is_admin() )
        return;

    $orderby = $query->get( 'orderby');

    if( 'offers_made' == $orderby ) {

        $meta_query = array(
            'relation'  => 'OR',
            array(
                'key'           => '_kf_offers_',
                'compare_key'   => 'LIKE',
            ),
            array(
                'key'           => '_kf_offers_',
                'compare'       => 'NOT EXISTS',
            ),

        );

        $query->set( 'meta_query', $meta_query );

    }

}
add_action( 'pre_get_posts', 'sortable_offers_orderby' );

Hope this makes sense,
Thanks in advance.


text:
Q: Error inserting multiple columns into Postgresql DB From SQLX I'm trying to perform an insert query into my Postgresql DB, but I am getting a mismatched type issue that I'm unsure how to solve.
Here's the code:
pub struct Product {
    pub id: i32,
    pub product_id: i64,
    pub title: String,
    pub handle: String,
    pub tags: Json<Vec<String>>,
    pub product_type: String,
    pub image_url: String,
    pub created_at: String,
    pub updatedAt: String,
}
pub struct ProductPatch {
    pub product_id: i64,
    pub title: String,
    pub handle: String,
    pub tags: Vec<String>,
    pub product_type: String,
    pub image_url: String
}

async fn add_product(pool: &Db, product: &ProductPatch) -> Result<i64, sqlx::Error> {
    let rec = sqlx::query!(
        r#"
        INSERT INTO products (product_id, title, handle, tags, product_type, image_url)
        VALUES ($1, $2, $3, $4, $5, $6)
        RETURNING product_id, title, handle, tags, product_type, image_url
        "#,
        &product.product_id,
        &product.title,
        &product.handle,
        &product.tags,
        &product.product_type,
        &product.image_url
    )
    .fetch_one(pool)
    .await?;

    Ok(rec.product_id)
}

Here's the error:

mismatched types
expected enum Result<_, sqlx::Error>
found enum Result<Record, anyhow::Error>

A: I suppose you've imported anyhow's Result, so your return type  Result<i64, sqlx::Error> is actually interpreted as anyhow::Result<i64, sqlx::Error>.
If you intend to return sqlx::Result, either change your return type to sqlx::Result<i64, sqlx::Error> or change your import statements.
If you intend to return anyhow::Result, maybe just return anyhow::Result<i64>.


text:
Q: Remove whitespaces and extract text between specific characters in Python I have a part of code which obtain by text = soup.find("table", attrs={"id":"mse_new"}).find("div", attrs={"class":"rmktxt"}):

                     1. The project is located on the northeast side of the intersection of Liancheng Road and Baiqian Road, with a land area of 27846 square meters, of which 23847 square meters are residential land, 3999 square meters of public green space, and the total construction area is temporarily estimated to be 60117 square meters (including The above-ground building area is 44117 square meters... Click to view details

Now I want extract the following text part from it:
1. The project is located on the northeast side of the intersection of Liancheng Road and Baiqian Road, with a land area of 27846 square meters, of which 23847 square meters are residential land, 3999 square meters of public green space, and the total construction area is temporarily estimated to be 60117 square meters (including The above-ground building area is 44117 square meters...

How could I do that in Python? Thanks.

A: Looks like you can use .text.strip()
Ex:
text = soup.find("table", attrs={"id":"mse_new"}).find("div", attrs={"class":"rmktxt"}).text.strip()

Note: Using Regex on HTML is very bad practice.

A: The solution I used:
# text = soup.find("table", attrs={"id":"mse_new"}).find("div", attrs={"class":"rmktxt"})
text = str(text)
text = " ".join(text.split())
result = re.search('
(.*)<a class="login-btn"', text)
print(result.group(1))

Out:
1. The project is located on the northeast side of the intersection of Liancheng Road and Baiqian Road, with a land area of 27846 square meters, of which 23847 square meters are residential land, 3999 square meters of public green space, and the total construction area is temporarily estimated to be 60117 square meters (including The above-ground building area is 44117 square meters...


text:
Q: php turning array into multi-dimensional array i have a (dynamic) array, which in this example contains 4 sets of data (5 fields per set), but it could be only one set or up to 25 sets.
Array ( [lightwattage1] => 50 [lightvoltage1] => 12 [lightquantity1] => 2 [lightusage1] => 4 [lightcomment1] => [lightwattage2] => 60 [lightvoltage2] => 24 [lightquantity2] => 4 [lightusage2] => 5 [lightcomment2] => [lightwattage3] => 30 [lightvoltage3] => 240 [lightquantity3] => 4 [lightusage3] => 2 [lightcomment3] => [lightwattage4] => 25 [lightvoltage4] => 12 [lightquantity4] => 2 [lightusage4] => 6 [lightcomment4] => )

which i'd like to turn into something like
Array ( Array ( [lightwattage1] => 50 [lightvoltage1] => 12 [lightquantity1] => 2 [lightusage1] => 4 [lightcomment1] => ),
        Array ( [lightwattage2] => 60 [lightvoltage2] => 24 [lightquantity2] => 4 [lightusage2] => 5 [lightcomment2] => ),
        Array ( [lightwattage3] => 30 [lightvoltage3] => 240 [lightquantity3] => 4 [lightusage3] => 2 [lightcomment3] => ),
        Array ( [lightwattage4] => 25 [lightvoltage4] => 12 [lightquantity4] => 2 [lightusage4] => 6 [lightcomment4] => )
        )

the original array is created this way:
$light = Array();

foreach( $_POST as $key => $val )
{
//field names that start with light to go in this array
    if (strpos($key, 'light') === 0) {
        $light[$key] = $val;
    }
}

the field name digit is already added with JS before form submission, and not by php script.
any hint much appreciated.

A: This is not an exacty answer to you question, but...
You can use arrays in POST variables like so:
<input name="light[1][wattage]" />
<input name="light[1][voltage]" />
<input name="light[2][wattage]" />
<input name="light[2][voltage]" />

will give you:
$_POST['light'] == array(
    1 => array(
        'wattage' => '...',
        'voltage' => '...',
    ),
    2 => array(
        'wattage' => '...',
        'voltage' => '...',
    ),
)

A: Try this:
$prefixes = array();
$postfixes = array();
foreach($original_array as $key=>$value)
{
        preg_match('/^([^\d]*)(\d+)$/',$key,$matches);
        if(count($matches)>1)
        {
                if(!in_array($matches[1], $prefixes)) $prefixes[] = $matches[1];
                if(!in_array($matches[2], $postfixes)) $postfixes[] = $matches[2];
        }
}
$new_array = array();
foreach($postfixes as $postfix)
{
        $new_element = array();
        foreach($prefixes as $prefix)
        {
                if(isset($original_array[$prefix.$postfix])) $new_element[$prefix.$postfix] = $original_array[$prefix.$postfix];
        }
        $new_array[] = $new_element;
}

given an $original_array equal to described, will produce $new_array:
Array
(
    [0] => Array
        (
            [lightwattage1] => 50
            [lightvoltage1] => 12
            [lightquantity1] => 2
            [lightusage1] => 4
            [lightcomment1] =>
        )

    [1] => Array
        (
            [lightwattage2] => 60
            [lightvoltage2] => 24
            [lightquantity2] => 4
            [lightusage2] => 5
            [lightcomment2] =>
        )

    [2] => Array
        (
            [lightwattage3] => 30
            [lightvoltage3] => 240
            [lightquantity3] => 4
            [lightusage3] => 2
            [lightcomment3] =>
        )

    [3] => Array
        (
            [lightwattage4] => 25
            [lightvoltage4] => 12
            [lightquantity4] => 2
            [lightusage4] => 6
            [lightcomment4] =>
        )

)

I was uncertain about how much you knew about the elements or their order, so this code basically takes any collection of elements that end in numbers and rearranges them in groups that have the same ending number.

A: Try this:
$outarr = array()
$subarr = array()
$i=0;
foreach($_POST as $key => $val)
{
    //only include keys starting with light:
    if (strpos("light", $key)==0)
    {
        //create a new subarray each time we find a key that starts with "lightwattage":
        if ($i>0 && strpos("lightwattage", $key)==0)
        {
            $outarr[] = $subarr;
        }
        $subarr[$key] = $val;
        $i++;
    }
}
$outarr[] = $subarr;

//$outarr contains what you want here


text:
Q: How can I remove duplicate data from GridView? I have a GridView which displays data from MySQL database
When I enter the code to display this information, everything works fine. However, after displaying the information, it continues to form duplicates of the same data.
Ex. The gridview would show the table
Customer ID Username Password
1           root     root
2           pie      root
3           apple    root
1           root     root
2           pie      root
3           apple    root
and ongoing..
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string strConn = "server=localhost;user id=root;password=root;database=database";
            string sql = "SELECT entryform.username, entryform.email, entryform.password, entryform2.firstname, entryform2.surname, entryform2.phonenumber, entryform2.ext, entryform2.jobtitle, entryform2.company, entryform2.country, entryform2.provincestate, entryform2.city, entryform2.address1, entryform2.address2, entryform2.zip, entryform.customerid FROM entryform, entryform2";
            MySqlConnection conn = new MySqlConnection(strConn);
            MySqlDataAdapter dA = new MySqlDataAdapter(sql, conn);
            DataSet ds = new DataSet();
            conn.Open();
            dA.Fill(ds, "entryform,entryform2");
            dataGridView.DataSource = ds;
            dataGridView.DataBind();
            conn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

I'm still fairly new so I am not sure what I did wrong or what else I need to add to fix this error. If anyone can provide any tips, that would be great!
Thanks in advance!

A: Try this:
dataGridView.Clear();

because maybe you are filling the dataGridView more than once! ;)
If is that you are getting duplicate values from the database, try this:
string sql = "SELECT DISTINCT entryform.username, entryform.email, entryform.password, entryform2.firstname, entryform2.surname, entryform2.phonenumber, entryform2.ext, entryform2.jobtitle, entryform2.company, entryform2.country, entryform2.provincestate, entryform2.city, entryform2.address1, entryform2.address2, entryform2.zip, entryform.customerid FROM entryform, entryform2";

I hope this helps


text:
Q: inspiration from gods/the gods a. That poet was thought to receive inspiration from gods by his contemporaries.
b. That poet was thought to receive inspiration from the gods by his contemporaries.
Is there a difference between the meanings of the above sentences?
What does 'the' change?
Does (b) mean the poet in question receive inspiration from all the gods?
I think that is the difference. In (a) it is not clear if all the gods gave him inspiration or only some of them. In (b) however, it seems that all of them gave that poet inspiration.
I didn't want to mention any specific poet. I am not sure that the Greeks thought Homer received inspiration from gods, but I think that was the case. One can easily imagine a society where a certain poet (or a number of poets) are thought to be inspired by gods.

A: As noted by Kate, the idiomatic expression is "inspired by the gods."  We don't analyse this much. It doesn't much matter if we mean "all the gods" or "the gods of verse and song".  You can understand this as "inspired by the gods that gave me inspiration" if that helps.
The same idiom is used in "cursed by the gods".


text:
Q: jQuery manage many toggles I need to use slideToggle() for too many divs to show and hide them.
This is my code, it doesn't work correctly:
$(".account-update").hide();
$(".account-update-pwd").hide();

$(".slide-toggle").click(function() {
    $(".account-update").slideToggle();
    $(".account").slideToggle();
});
$(".slide-toggle-pwd").click(function() {
    $(".account-update-pwd").slideToggle();
    $(".account-update").slideToggle();
});

HTML:
Update Account
Change Password

A: I have updated your code with a nice generic solution below.

$(".account-update").hide();
$(".account-update-pwd").hide();

$("a.slide-toggle").click(function() {
  var targetDiv = $($(this).attr('data-selector'));
  var otherDivs = $("div.slide-toggle").not(targetDiv);

  otherDivs.each(function(){
    if($(this).is(':visible')) {
      $(this).slideToggle();
    }
  });

  targetDiv.slideToggle(function(){
    if($("div.slide-toggle:visible").length === 0) {
      $(targetDiv.attr('data-default')).slideToggle();
    }
  });
});
div {
  height: 100px;
}

.account {
  background-color: red;
  color: white;
}

.account-update {
  background-color: green;
  color: white;
}

.account-update-pwd {
  background-color: blue;
  color: white;
}

Account Div

Update Account

Account Update Div

Change Password

Account Password Update Div

A: If you can create unique class for toggle buttons, then you can do something like this:

$('body').on('click', 'a,button', function(e){
  if ( $(e.target).attr('class') === 'btn-toggle' ) {
    $(this).css({
      color: 'red'
    })
  }
});

    aaaa
 aaaa
 aaaa

Short and simple :)

A: You may try this.
$(".toggle-trigger").on("click", function() {

    var trigger = $(this);
    var target = trigger.attr("data-entity");

    if (!trigger.hasClass("active")) {

        $(".toggle-trigger").removeClass("active");
        trigger.addClass("active");
    } else {

        $(".toggle-trigger").removeClass("active");
        trigger.removeClass("active");
    }

    $(".toggle-target[data-entity='"+ target +"']").toggleClass("hide");
});

How to use
Container One Link
Container Two Link

Container One

Container Two

What it does is, when you clicked toggle-trigger which is the links to trigger the container. It will get an attribute called data-entity which is the unique parameter to find the container's data-entity to toggle things up.


text:
Q: How do I configure Entity Framework to use whatever database is in the connection string The code I inherited has an OnModelCreating(ModelBuilder modelBuilder) , and inside that method , for each entity, it does entity.ToTable("someTableName", "someDatabaseName");
Instead of specifying "someDatabaseName" in entity.ToTable("someTableName", "someDatabaseName");   how do I configure EF to use whatever db is inside the connection string?
One solution is to go inside OnModelCreating(ModelBuilder modelBuilder) and make the string "someDatabaseName" into a variable, then set that variable based on the connection string,  (but something about that seems wonky , and leaves me wondering what is a better, more preferred way?)
//This code runs before OnModelCreating()
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseMySQL(_connectionString);
        //I wrongly assume the context would be using the db from this conn string,
        //but it's not, it's using the database "someDatabaseName" from OnModelCreating below
    }
}

//after OnConfiguring, then this code runs
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasAnnotation("ProductVersion", "2.2.4-servicing-10062");
    modelBuilder.Entity<SomeClass>(entity =>
    {
        entity.ToTable("table1", "someDatabaseName");   //i could make "someDatabaseName a variable, but surely there is a better way?
        ...
    }
}

A: The solution was to change this
entity.ToTable("table1", "someDatabaseName");

to this
entity.ToTable("table1");


text:
Q: Yum: assume yes if install size < 1MB I don't want to use --assume-yes option, but I'm fine with small installs (less than 1MB) to be processed without asking. Is there any way how to achieve that? I'm on Fedora 20.

A: It is not possible to filter by package size with --assume-yes, but you can query the packages by size with repoquery, and with some awk filtering, install just the files that have a download size with less than 1MB:
yum -y install `repoquery --pkgnarrow=updates -a --qf "%{name} %{size}" | awk '$2 < 1048576 {print $1}'`

What this command does: repoquery will get a query of packages of updates, create a 2 column list with package name and size, and with awk print only the name of packages that have less than 1048576 bytes(1MB). After that, you will pass this package list to yum ;)
Cheers.


text:
Q: Establish openvpn tunnel in bash script I'm trying to write a script which will establish an openvpn tunnel when the computer boots up. The main problem lies in inputting the pkcs12 password. I realise it's very bad practice to have a password stored in plain text, but I'm not too fussed about that -- the computer is very secure in all other respects so I'm pretty confident that nobody but me will be accessing it to view the password.
I have added the --management and the --management-query-passwords options so that the password can be input via a telnet session. This works fine when I do it manually, but when I try and do it automatically with a bash script it fails. My guess would be that either I am not doing the carridge return after the password line properly, or that some other garbage values are sneaking in to the telnet session as inputs. Here is the relevant bits of code (xxx for stuff that is classified):
$ cat user.ovpn
#OpenVPN Server conf
tls-client
client
dev tun
proto udp
tun-mtu 1400
remote xxxxxxxxxxxxxxxxxxx 1194
pkcs12 user.p12
cipher AES-256-CBC
comp-lzo
verb 3
ns-cert-type server
tls-remote xxxxxxxxxxxxxxxxxxxxxxx
management 127.0.0.1 5558
management-query-passwords

$ cat telnet_commands.sh
#!/bin/bash
echo "open 127.0.0.1 5558"
sleep 1
echo -e "password 'Private Key' xxxxxxxxxx\r\n"

$ nohup openvpn user.ovpn &
$ ./telnet_commands.sh | telnet

$ #manually check whether this worked:
$ telnet 127.0.0.1 5558
Escape character is '^]'.
>INFO:OpenVPN Management Interface Version 1 -- type 'help' for more info
>PASSWORD:Need 'Private Key' password

Obviously this is not working -- the openvpn telnet management interface is still waiting for the password to be entered.

A: Just wanted to mention that (at least on Ubuntu 12.04) there is --askpass /your/file argument for openvpn, that reads the private key password from a file.

A: My working case with a small correction:
nohup openvpn /etc/init.d/ovpn/Userxxx.ovpn &
/etc/init.d/ovpn/telnet_commands.sh

A: I would expect all it is looking for is the password for the private key.  Try using echo -e "xxxxxxxxx\r\n" or echo "xxxxxxxx".
You may want to try using expect to respond to the password request.  Some password programs look for the password on a tty type device. The program expect handles this.
You may be better off looking for an rc.d init script to start your tunnel. This is the normal method for starting things at startup.

A: ok i have managed to get the openvpn tunnel password entered automatically and also managed to get the tunnel to run on bootup. hopefully this helps someone else who is trying to do the same thing - coz its taken me over 20 hours to figure out something which now looks pretty basic. code:
$ cat /etc/init.d/ZZcreate_ovpn_tun.sh
#!/bin/bash

# check if the tunnel already exists before trying to create it
proc=$(ps aux | grep openvpn | grep Userxxx)
if [ "$proc" == "" ]; then
  echo "ovpn tunnel does not exist yet - will create it now"
else
  echo "ovpn tunnel already exists ($proc)"
  exit 0
fi

# load the config file into openvpn - has options to request the pkcs12 password through
# telnet
nohup openvpn /etc/init.d/ovpn/Userxxx.ovpn
sleep 1

# enter the password though a telnet session
/etc/init.d/ovpn/telnet_commands.sh

$ cat /etc/init.d/ovpn/telnet_commands.sh
#!/usr/bin/expect
spawn telnet 127.0.0.1 5558
expect ">PASSWORD:Need 'Private Key' password"
send "password 'Private Key' xxxxxxxxxxxxx\r"
expect "SUCCESS: 'Private Key' password entered, but not yet verified"
send "quit\r"
expect eof

$ cat Userxxx.ovpn
#OpenVPN Server conf
tls-client
client
dev tun
proto udp
tun-mtu 1400
remote xxxxxxxxxxxxxxxxxxxxxxxxxxxxx.com.au 1194
pkcs12 /etc/init.d/ovpn/Userxxx.p12
cipher AES-256-CBC
comp-lzo
verb 3
ns-cert-type server
tls-remote xxxxxxxxxxxxxxxxxxxxxxxxxxx.com.au
management 127.0.0.1 5558
management-query-passwords

$ sudo update-rc.d ZZcreate_ovpn_tun.sh defaults
$ sudo shutdown -r 0

$ # wait for system to boot up again
$ ps aux | grep openvpn
root 5279  0.0  0.1  28224  3728 ? S 22:48 0:00 openvpn /etc/init.d/ovpn/Userxxx.ovpn

you may also want to redirect all output to a file so that if it fails you will be able to see why. i called the file ZZcreate_ovpn_tun.sh to make sure it was run last out of all of the scripts in the init.d dir. ideally i would just have made sure that it only ran at level 6 or so but this works fine for now.


text:
Q: Is there a way to test if a browser supports flash/silverlight? I'm making an application with SL/flash charts and am wondering if there is a way to test if the browser it's being pushed to supports silverlight or not (ipad/iphone). And if it doesn't, then I can use some kind of AJAX chart in its place.
If this is possible to interchange platforms by testing against the host, how would I do this?

A: For flash, you can either use this: http://ppk.home.xs4all.nl/js/flash.html or this: http://www.adobe.com/support/flash/how/shock/javaplugs/javaplugs04.html
Silverlight is discussed here: Detect via javascript whether Silverlight is installed

A: You can use little hack here.
Make simple as3 flash movie and make call
        try
        {
            navigateToURL(new URLRequest("javascript:flashCheck()"),"_self");
        }
        catch (e:Error){}

and after that you can write simple check function in javascript ( flashCheck(){} ).
You know that this function only callable from as3 (swf) so you can determine what you need to.
Hope this helps.
p.s.
and i pretty sure that you can do this trick with you silverlight.

A: We've use this in the past,
http://developer.apple.com/internet/webcontent/detectplugins.html
Doesn't do Silverlight.


text:
Q: When publishing, what is exactly supposed to be published? I'm not used with "publishing" a project via visual studio. I'm trying to do so since yesterday and I've found out these things:

*

*All the images contained in my application in a specific folder (example: MyProject/Images/Image1.jpeg) are only copied the same way they are in my project;

*None of my controllers/utility class appears in the published project;

*However the views are presents and the javascript files as well, but as they are, so a MyApp.js will be copied as a MyApp.js.

So my question is: is it supposed to be that way? What about my logic, ain't it not supposed to be copied as well? And shouldn't it be compressed, compiled, or protected in a dll, else everyone will be able to see my code in public, which I do not want?
Feel free to teach me what's a publish is supposed to do and what went wrong. thanks!

A: Publish is supposed to do almost what you mentioned only..

*

*Images in content folder

*any stylesheets in the content folder

*Scripts in script folder

*All View files Anything with Build Action = Content

*The compiled files form the dll of your binary & dependencies

Infact all the images, css, javascripts will also have buildaction set to content only.
If you have a file selected in the project and it is not found in the folder, if its build action is "content", the build will succeed but the publish may fail. So in this case you may have to exclude the file if it is not necessary or add the file in the folder
Most of the automatic build systems like cruise control also do the same though with quite an advanced interface.
Your logic in c# or vb.net is already compiled into the binaries. But any script or styles or scripts inside html won't be protected. But bundling the scripts and styles using the BundleConfig may protect it to some extent.

A: All Your logic is converted into dll's so just create an instance on IIS and host your application there. You can follow the steps shown here.


text:
Q: swift - Open ViewController by clicking a button in UIWebView I have a ViewController named "test123" and I have UIWebView with a button:
<button onclick='myFunction()'>Open test123</button>
</body>

<script>
    function myFunction()
    {
        presentViewController('test');

    }
    </script>

I tried this but I get Use of undeclared type 'test123'
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    if (navigationType == UIWebViewNavigationType.formSubmitted) {
        let VC = self.storyboard?.instantiateViewControllerWithIdentifier("test123") as? test123

        let navigationController = UINavigationController(rootViewController: VC!)
        self.navigationController?.presentViewController(navigationController, animated: true, completion:nil)

    }
    return true
}

So what am I doing wrong?

A: You should remove the as? test123 part that tries to downcast your object to a type test123 that obviously does not exists.


text:
Q: Synchronization between ios devices First of all sorry for my English. I have searched but I didn't see nothing similar.
I have a problem and I don't know really how to make it.
I need to sync data between two or more iOS devices. This data could be a JSON or something similar.
Example:
Two iOS devices uses the same app, they are near each other(In the same place or room). There is a form and if I change a value in one of the devices the change should be shown in the other device automatically.
Thank you very much.

A: I think you need to use the Multipeer Connectivity Framework which is part of iOS 7.0.
Apple's Multipeer docs


text:
Q: reduce the number of IF statements in Python I have written a function that is going to have up to 72 IF statements
and i was hoping to write code that will be much shorter,  but have no idea where to start
The function reads the self.timeselect variable when a radio button is selected and the result is saved to a text file called missing_time.txt. If the result is equal to 1 then save "0000" to the file, if the result is 2 save then 0020 to the text file etc. This can be for 72 possible combinations.
Is there a smarter way to simplify the function ?
def buttonaction():
    selectedchoice = ""
    if self.timeselect.get() == 1:
        selectedchoice = "0000"
        orig_stdout = sys.stdout
        f = open('missing_time.txt', 'w')
        sys.stdout = f
        print(selectedchoice)
        f.close()
    if self.timeselect.get() == 2:
        selectedchoice = "0020"
        orig_stdout = sys.stdout
        f = open('missing_time.txt', 'w')
        sys.stdout = f
        print(selectedchoice)
        f.close()

self.timeselect = tkinter.IntVar()

self.Radio_1 = tkinter.Radiobutton(text="0000",variable =
self.timeselect,indicator = 0 ,value=1)
self.Radio_1.place(x=50,y=200)
self.Radio_2 = tkinter.Radiobutton(text="0020",variable =
self.timeselect,indicator = 0 ,value=2)
self.Radio_2.place(x=90,y=200)

A: choice_map = {
    1 : "0000",
    2 : "0020"
}

def buttonaction():
    selected = self.timeselect.get()
    if 0 < selected < 73:  # This works as intended in Python
        selectedchoice = choice_map[selected]
        # Do you intend to append to file instead of replacing it?
        # See text below.
        with open("missing_time.txt", 'w') as outfile:
            outfile.write(selectedchoice + "\n")
            print(selectedchoice)

Better yet, if there is a pattern that relates the value of self.timeselect.get() to the string that you write out, generate selectchoice directly from that pattern instead of using a dictionary to do the mapping.
Edit
I find it a bit odd that you are clearing the file "missing_time.txt" every time you call buttonaction. If your intention is to append to it, change the file mode accordingly.
Also, instead of opening and closing the file each time, you might just want to open it once and pass the handler to buttonaction or keep it as a global depending on how you use it.
Finally, if you do not intend to catch the KeyError from an invalid key, you can do what @Clifford suggests and use choice_map.get(selected, "some default value that does not have to be str").

A: All you need to do in this case is construct a string from the integer value self.timeselect.get().
selectedchoice = self.timeselect.get()
if 0 < selectedchoice < 73:
    orig_stdout = sys.stdout
    f = open('missing_time.txt', 'w')
    sys.stdout = f
    print( str(selectedchoice).zfill(4) )     # Convert choice to
                                              # string with leading
                                              # zeros to 4 charaters
    f.close()

Further in the interests of simplification, redirecting stdout and restoring it is a cumbersome method of outputting to a file.  Instead, you can write directly to the file:
    with open('missing_time.txt', 'w') as f:
        f.write(selectedchoice + "\n")

Note that because we use the with context manager here, f is automatically closed when we leave this context so there is no need to call f.close(). Ultimately you end up with:
selectedchoice = self.timeselect.get()
if 0 < selectedchoice < 73:
    with open('missing_time.txt', 'w') as f:
        f.write( str(selectedchoice).zfill(4) + "\n" )

Even if you did use the conditionals each one differs only in the first line, so only that part need be conditional and the remainder of the content performed after the conditionals.  Moreover all conditionals are mutually exclusive so you can use else-if:
    if self.timeselect.get() == 1:
        selectedchoice = "0000"

    elif self.timeselect.get() == 2:
        selectedchoice = "0020"

    ...

    if 0 < selectedchoice < 73:
        with open('missing_time.txt', 'w') as f:
            f.write(selectedchoice + "\n")

In circumstances where there is no direct arithmetic relationship between selectchoice and the required string, or the available choices are perhaps not contiguous, it is possible to implement a switch using a dictionary:
choiceToString = {
    1:  "0001",
    2:  "0002",
    ...
    72: "0072",
}

selectedchoice = choiceToString.get( self.timeselect.get(), "Invalid Choice")

if selectedchoice != "Invalid Choice":
    with open('missing_time.txt', 'w') as f:
        f.write(selectedchoice + "\n")

A: Since there is no switch statement in Python, you can't really reduce the number of if statements. But I see 2 two way to optimize and reduce your code length.
First, you can use some
if condition:

elif condition:

instead of
if condition:

if condition:

since you can't have self.timeselect.get() evaluated to more than one int.
Secondly you can wrap all the code that doesn't vary in a function.
You can get rid of selectedchoice and put
orig_stdout = sys.stdout
f = open('missing_time.txt', 'w')
sys.stdout = f
print(selectedchoice)
f.close()

in a function writeToFile(selectedOption)

A: I'm assuming that the values are arbitrary and there's no defined pattern. I also see that the only thing that changes in your code is the selectedChoice variable. You can use a Dictionary in such cases. A dictionary's elements are key/value pairs so you can reference the key and get the value.
dictionary = {
    1:"0000",
    2:"0020",
    3:"0300",
    4:"4000"
}

def buttonAction():
    selectedChoice = dictionary[self.timeselect.get()]
    if 0<selectedChoice<=72:
        f=open('missing_time.txt','w')
        f.write(selectedChoice+" ")
        f.close()
        print(choice)


text:
Q: Can't ping hosts in Mininet while there are duplicate links I am building a custom topology in Mininet Emulator, with the topology displayed on this picture enter image description here, but I have a problem with ping between hosts.
For each pingall , I have different results.
What is the probleme? why i can't ping all the hosts?
I'm using OpenDaylight controller, and this is the commande line to connect mininet to ODL controller :
sudo mn --controller=remote,ip=192.168.40.132 --switch=ovsk,protocols=OpenFlow13 --custom mininet/custom/NetworkTopo_networktopo.py --topo networktopo --mac --ipbase=192.168.10.0/24


text:
Q: Return when a value changes This is my data
SerialNumber  Reading  Date
A             4        10/30/2019
A             4        10/29/2019
A             3        10/28/2019
B             11       10/30/2019
B             9        10/29/2019
B             6        10/28/2019
C             25       10/30/2019
C             25       10/15/2019
C             25       10/13/2019
C             21       10/9/2019
C             21       10/3/2019

I need to be able to either create a measure or a calculated column that tells me the date of when each serial number last changed.  So i need this:
SerialNumber  Reading  Date          DateChanged
A             4        10/30/2019    10/28/2019
A             4        10/29/2019    10/28/2019
A             3        10/28/2019    10/28/2019
B             11       10/30/2019    10/29/2019
B             9        10/29/2019    10/29/2019
B             6        10/28/2019    10/29/2019
C             25       10/30/2019    10/9/2019
C             25       10/15/2019    10/9/2019
C             25       10/13/2019    10/9/2019
C             21       10/9/2019     10/9/2019
C             21       10/3/2019     10/9/2019

Here is the code I tried, but it only gave me the max date for each SerialNumber
Column = CALCULATE(
MAX(
SMU_Lookup[Date]),
FILTER(
ALL(SMU_Lookup),
 SMU_Lookup[Reading] < MAX(SMU_Lookup[Reading])
 && SMU_Lookup[SerialNumber] = EARLIER(SMU_Lookup[SerialNumber])
)
)

Thanks in advance!

A: I think this is the calculated column you are looking for:
DateChanged =
VAR max_date =
    MAXX (
        ALLEXCEPT ( 'SMU_Lookup', SMU_Lookup[SerialNumber] ),
        'SMU_Lookup'[Date]
    )
VAR reading_max_date =
    CALCULATE (
        MAX ( 'SMU_Lookup'[Reading] ),
        ALLEXCEPT ( 'SMU_Lookup', SMU_Lookup[SerialNumber] ),
        'SMU_Lookup'[Date] = max_date
    )
RETURN
    CALCULATE (
        MAX ( SMU_Lookup[Date] ),
        ALLEXCEPT ( 'SMU_Lookup', SMU_Lookup[SerialNumber] ),
        'SMU_Lookup'[Reading] <> reading_max_date
    )

*

*The ALLEXCEPT-function returns a table with the rows where the SerialNumber is the same as the SerialNumber in the current row.

*The MAXX function returns the latest date for that table.

*[VAR reading_max_date] holds the reading for the max_date for each SerialNumber.

*After the RETURN statement the MAX(Date) is calculated where the Reading differs from reading_max_date.

A: I first created a measure (a variable may have worked here too) to hold the max reading for each SerialNumber
MaxReading = CALCULATE(MAX(SMU_Lookup[Reading]),ALLEXCEPT(SMU_Lookup, SMU_Lookup[SerialNumber]))

Then I created the calculated column LastUpdate as follows
LastUpdate = CALCULATE(MAX(SMU_Lookup[Date]), FILTER(ALLEXCEPT(SMU_Lookup, SMU_Lookup[SerialNumber]), SMU_Lookup[Reading] < [Max Reading]))

Simple enough and it works for the instances where there are multiple readings with the same SerialNumber and Date.


text:
Q: declaration syntax error What's wrong with this one? The compiler says: Declaration syntax error.
Source File:
#include<iostream>
using namespace std;
int main(int argc, char **argv) {
    void printBinary(const unsigned char val) {
        //printBinary() func. outputs byte in binary
        for(int i=7;i>=0;i--)
            if(val & (1<<i))  //generates a single bit with offset position
                std::cout<<"1";
            else
                std::cout<<"0"
    }
    return 0;
}///:~

Header file:
void printBinary(const unsigned char val);
///:~

A: You are trying to define one function inside another function. This is illegal. Why did you place the definition of printBinary into the body of main?
Aside from the lambda functions in C++11, C++ has no such feature as local functions. All functions "live" in namespace scope.
The only workaround for this rule is inline member function definitions for local classes, although it does not produce a local function either.

A: You can't define a function in another function's (in this case, main) body.
//EDIT: Unless, of course, it's lambda.


text:
Q: How to obtain Authentication object in message handling Spring Controller method I have a controller method that handles REST requests as well as STOMP/websocket messages.  Something like:
@RequestMapping(value="/test")
@MessageMapping(value=".test")
@SendTo(value="/topic/testresponse")
public ResponseEntity<?> test(Principal principal)
{
  Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  ...
  return ResponseEntity.ok(principal.getName());
}

When I invoke this method from a REST client, the Principal and Authentication objects are both populated correctly.  However, when I invoke this method from a STOMP/websocket client, the Principal object is populated but the Authentication object is null.
Clearly, Spring is able to get the Authentication object somehow, even in the websocket case, because it populated the Principal object.  How can I do it in my code?
The reason I want to know this is that I need to do custom authorization checks in code that is NOT invoked as a controller method.
I am using Spring Boot 1.2.2.
Thanks.


text:
Q: Once inserted, data in Firebase is automatically disappearing for some unknown reason I made another post to explain better, ok? :)
This video shows exactly what I mean:
The video is: https://www.youtube.com/watch?v=DCg00fe-_xs
Firebase normally stores data. After the 6th second of the video, trying to enter new data, the data stays about a second in Firebase, but automatically then it disappears.
I try to input the data into Firebase two more times in this video, but the data always automatically disappears afterwards.
You can see that the other datas that are stored in Firebase does NOT disappear. But the data of this code is automatically disappearing for some reason as shown in the video. Please what can I do to fix it?
Code:
button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String raça = spinner_raca.getSelectedItem().toString();
                final String regiaoDoEstado = spinner_regiaoDoEstado.getSelectedItem().toString();
                final String estado = spinner_estado.getSelectedItem().toString();

                Intent receiverIntent = getIntent();
                Bundle bundleRecebedor = receiverIntent.getExtras();
                String nomecompleto = bundleRecebedor.getString("nomecompleto");
                String email = bundleRecebedor.getString("email");
                String doencasPreExistentes = bundleRecebedor.getString("doencasPreExistentes");
                String dataDeNascimento = bundleRecebedor.getString("dataDeNascimento");
                String genero = bundleRecebedor.getString("genero");
                String identificadorEmHash = bundleRecebedor.getString("identificadorEmHash");
                String telefone = receiverIntent.getStringExtra("telefone");

                reference = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(identificadorEmHash);
                Toast.makeText(getApplicationContext(), identificadorEmHash, Toast.LENGTH_LONG).show();
                if(identificadorEmHash.equals(null)) {
                    Toast.makeText(getApplicationContext(), "The identifier does not exist", Toast.LENGTH_LONG).show();
                } else {
                    reference.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {

                        }
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            reference = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(identificadorEmHash);
                            if (!dataSnapshot.exists()) {
                                Toast.makeText(getApplicationContext(), "The identifier does not exist", Toast.LENGTH_LONG).show();
                            } else {

                                HashMap<String, String> sendDataToDataBase = new HashMap<>();
                                    sendDataToDataBase.put("Nome Completo", nomecompleto);
                                    sendDataToDataBase.put("E-mail", email);
                                    sendDataToDataBase.put("Identificador em Hash", identificadorEmHash);
                                    sendDataToDataBase.put("Telefone", telefone);
                                    sendDataToDataBase.put("Doenças Pré Existentes", doencasPreExistentes);
                                    sendDataToDataBase.put("Data de Nascimento", dataDeNascimento);
                                    sendDataToDataBase.put("Gênero", genero);
                 // When I am going to send the following data to Firebase, the problem of the video happens.
                                    sendDataToDataBase.put("Região do Estado em que mora", regiaoDoEstado);
                                    sendDataToDataBase.put("Raça", raça);
                                    sendDataToDataBase.put("Estado do Brasil em que mora", estado);

                                try {
                                    raiz.child(identificadorEmHash).setValue(sendDataToDataBase);

                                } catch (Exception e) {
                                    e.getMessage();
                                }
                            }
                        }
                    });
                }
            }
        });

Please, can someone help me to fix this bug?

A: Firebase doesn't automatically delete data, so if you see the data show up in the console it was written there by a client/API call, and allowed by your security rules. If the data subsequently gets updates or removed again, there is another client/API call that does so.
I recommend checking for realtime listeners in your code, that may be responding to your first write by updating (and accidentally reverting) that operation. It is also quite common to have a server-side script that is doing this.

Update: one thing you can try is to use updateChildren instead of setValue in all places such as this one:
raiz.child(identificadorEmHash).updateChildren(sendDataToDataBase)


text:
Q: Swift How do I stop the tab bar from changing background colors I'm working on a project that requires a Tabbar. Currently I have my code set up so that after login or sign up I'm presented by the Explore tab (The third tab). The goal I'm trying to achieve is to have my project only show a translucent tab bar background. When I was originally working on my project I had no issue doing this. I ran in the problem after I incorporated a table view that allow for scrolling. Currently when ever I push on the tab 1-4 I get a translucent background. When tab 5 (includes the table view with scrolling) is pressed the background of the tab bar changes to a gray color. Even if I press out of the tab to a different one the gray tab bar background color doesn't change. The only way I found to dismiss the back ground color after the 5th tab has been selected is to scroll all the way down. After I'm scrolled down it allows the user to see the translucent background again. Then you can select different tab bars and you'll see the translucent background again. How do I only show a translucent color

A: You need to set Bar-Tint colour to Default. ScreenShot


text:
Q: lw: load word from which memory - RAM or disk lw - A word is loaded into a register (in the CPU) from the specified address.
But from which memory is the word loaded? The RAM or the disk? I get that the memory is outside the CPU but which memory is the address (the second operand) referring to?

A: Storage devices are usually connected through more complex I/O (input/output) mechanism, as they did operate on speed which didn't even relate to the CPU speed (I mean any I/O with harddisk did take "ages" even with old MHz processors).
The MIPS architecture is probably closest to the "second generation" from the wiki:

They typically separated the computer into two "worlds", the CPU and memory on one side, and the various devices on the other.

The memory chip is usually directly connected to CPU (with M wires for address bus, on MIPS up to 32, and N wires for data transfer, on MIPS 32 also for data) and couple of wires handling the read/write/ack/err/parity transfer logic... which is lot of wires, and usually this takes major part of CPU pins and [almost] all pins of RAM chip.
Connecting any/several storage devices in similar generous way would made the design of PCB very difficult and expensive, so the I/O pins were usually more sparse, and all I/O devices shared that part of bus, using some control pins to sync/share when which device is using the bus.
So the data on disk don't have any "addresses" directly on CPU, the addressing is done by sending (sometimes several) signals over I/O bus to the device, by several instructions and taking some CPU time + syncing. The old disks were so slow, that this was no problem, also some block devices had simple enough logic to be controlled by DMA chip, which stands for "Direct Memory Access", this allowed the CPU to just set up the transfer with initial values, then the DMA chip finished it waiting for all the data coming from the device and writing it directly to RAM chip (without further CPU intervention).
Any ASM instructions talking about "addresses" and "memory" are always talking about RAM/ROM/alike chips, anything else would have it in instruction description.


text:
Q: Microsoft.AspNetCore.All isn't supported.FrameworkReference for Microsoft.AspNetCore.App will be added implicitly by Microsoft.NET.Sdk.Web I have a problem with my visual studio solution. Project is working but I got this error when I want to add migration. I could add migration before and downloaded the packages I need.
add-migration birim add-migration : The term 'add-migration' is not recognized as the name of a cmdlet, function, script file, or operable program.

I tried:
dotnet add EmployeeData package Microsoft.AspNetCore.Authentication.MicrosoftAccount

I got this error:
unable to create dependency graph file for project

So I added the package manually via "manage nuget packages for solution"
And now I have this error for my solution:
The Microsoft.AspNetCore.All package is not supported when targeting .NET Core 3.0 or higher. A FrameworkReference for Microsoft.AspNetCore.App should be used instead. This will be added implicitly by Microsoft.NET.Sdk.Web.

And I got
Build failed.
when I tried to add migration.
I am almost sure this is about paths of projects and solutions.How can I solve this?

A: I just deleted the package Microsoft.AspNetCore.All and it's working.