text:
Q: Can slicers be used a stored procedure parameter in power bi to filter underlying data Can we pass the slicer values as stored procedure paramter when connecting to a sql for developing a PowerBI report  so that once its deployed in powerbi service the end user can use slicer to filter the report
I tried to use a stored procedure  which uses a date paramter ,but using slicer i am unable pass as a paramter to stored procedure

A: No.  You cannot directly use stored procedures in DirectQuery models.  If you use native sql in DirectQuery, it must be "composable", ie Power BI will run
select * from (<your query here>) b
where someslicer=somevalue...

So you can use multi-statement table-valued functions, and you can manipulate the native query using Dynamic M Parameters, and there's a workaround where you use OPENQUERY against a loopback linked server to run a stored procedure. How to use SQL Server stored procedures in Microsoft PowerBI?


text:
Q: Can i use the .class files in my bin folder to get back my SRC files? I have no idea what happened while i was coding with EclipseIDE. My laptop froze out of nowhere, i had to force shutdown and when i opened Eclipse again, my SRC folder is gone from my java project folder. I can't find it in recycle bin, can't find it with my search bar and it's just gone.
However i still have my .class files in the bin folder. I really need my SRC files back as they were to be submitted by today. Can i get them back in any way???
https://image.ibb.co/cOhJXf/Screenshot-5.png

A: Yes, there are many Java Decompiler's available to get the Source code from Byte Code. Here is the one i use
http://jd.benow.ca/
Cavaj [Java Decompiler] https://github.com/java-decompiler/jd-gui/releases/download/v1.4.0/jd-gui-windows-1.4.0.zip

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wordpress tag cloud: how to remove inline style for font size? Is there a nice way to remove the inline style from wordpress tag cloud tags? I'd like to set the same size for all tags and do not want inline styles at all if I can help it.
Thanks

A: You can use WordPress' core filters to modify output by different functions. wp_generate_tag_cloud() has a filter that allows you to edit the string input. Below is a function that regexs the string, finds the inline style and removes it.
add_filter('wp_generate_tag_cloud', 'xf_tag_cloud',10,3);

function xf_tag_cloud($tag_string){
   return preg_replace("/style='font-size:.+pt;'/", '', $tag_string);
}

A: Unfortunately Rezens regexp didn't work in my case. You can use the following filter and regexp to remove the whole inline style tag on the output:
add_filter('wp_generate_tag_cloud', 'myprefix_tag_cloud',10,1);

function myprefix_tag_cloud($tag_string){
  return preg_replace('/style=("|\')(.*?)("|\')/','',$tag_string);
}

A: If you inserting this with PHP, it doesn't help with removing the inline styles but you can set the 'smallest' and 'largest' parameters to ensure the font size is the same, see the Codex for more info on this.

A: If you don't want to change your theme's code you can add a css font-size rule adding !important, it should override inline style.


text:
Q: Find tables name in multi-part identifier I'm trying to select various table and column names from a (SQL Server 2008) database. The database is fairly big. There are several databases sitting on the same server, each with various schemas etc. Once there's a multi-part identifier involved I'm stuck. For example, to retrieve a list of tables in under a database this works fine:
SELECT [name]
FROM DatabaseOne.sys.tables
ORDER BY [name]

Then I want to get the tables under a certain schema. E.g.:
SELECT [name]
FROM DatabaseOne.SchemaOne.sys.tables
ORDER BY [name]

But I get the error:

Could not find server 'DatabaseOne' in sys.servers. Verify that the
  correct server name       was specified. If necessary, execute the
  stored procedure sp_addlinkedserver to add the server to sys.servers.

A large part of the problem probably lies in the fact that I don't really know anything about schemas (if that's even what they are).
Also, if I want to find the column names in a table, say DatabaseOne.SchemaOne.TableOne, how would I go about doing that?
Any help would be highly appreciated.

A: If you use a four part name, SQL Assumes the first portion is the name of a linked server.
The system tables are in the sys schema, and contain data for all other schemas like dbo or whatever.
In sys.tables there is a schema_id value that specifies which schema each table is in.  There is also a sys.schemas table which contains the schemas.
If you know your schema name, you can do a
SELECT [name]
FROM DatabaseOne.sys.tables t
INNER JOIN sys.schemas s
    ON s.schema_id = t.schema_id
WHERE s.name = 'MySchema'
ORDER BY [name]

You can also check multiple schemas by making the s.name evaluation an IN evaluation.


text:
Q: a problem on sum of two different sets and their properties Let $A$ and $B$ be subsets of $\mathbb{R}^n$.
Define
$A + B = \{x + y \mid x \in A; y \in B\}$
Pick out the true statements:
a. if $A$  and $B$ are closed sets, then $A + B$ is a closed set;
b. if $A$  is an open set and if $B$ is a closed set, then $A + B$ is an open set;
c. if $A$  and $B$ are compact sets, then so is $A + B$.

(a) is not true and (c)  is true.
for (b) I am little confused. it looks like true intuitively but I have no general proof.

A: HINT: For (b), let $a\in A$ and $b\in B$; you want to find an open neighborhood of $a+b$ contained in $A+B$. Since $A$ is open there is an $r>0$ such that $B(a,r)\subseteq A$, where $B(a,r)$ is the open ball of radius $r$ centred at $a$. Clearly $$B(a,r)+b=\{x+b:x\in B(a,r)\}\subseteq A+B\;,$$ so you're done if you can show that $B(a,r)+b$ is an open neighborhood of $a+b$. It's just the open ball $B(a,r)$ translated by the vector $b$, so you'd expect it to be the open ball of radius $r$ centred at $a+b$, and the natural thing to do is to try to show that $B(a,r)+b=B(a+b,r)$. You need only the fact that in $\Bbb R^n$ the usual Euclidean distance is translation invariant: for any $x,y,z\in\Bbb R^n$,
$$\|(x+z)-(y+z)\|=\|x-y\|\;.$$


text:
Q: Mathematica 9 cannot solve this Integral. Mathematica 8 could. Is this a bug? I was trying to (re)calculate a problem of an older Wolfram blog post (Problem 11457, by M. L. Glasser) with Mathematica 9.0.0.0 (on OS X 10.8.2).
Assuming[0 < a < b, Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}]]

Instead of the expected solution, it just returns the integral unevaluated. Is this a regression?
More details:
As pointed out in the commentes, the indefinite integral
Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], x]

still gives the same result in Mathematica 8 and 9.
The next two each returned ConditionalExpression in Mathematica 8 but return unevaluated in Mathematica 9:
Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}]
Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}, Assumptions -> 0 <= a <= b]

The actual problem
Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b}, Assumptions -> 0 < a < b]

computes correctly to ((a - b)^2 \[Pi])/(4 (a + b)) in Mathematica 8 but still returns unevaulated in Mathematica 9.

A: This works in V9.0.1:
Assuming[0 < a < b,
  Integrate[ArcCos[x/Sqrt[(a + b) x - a b]], {x, a, b},
   GenerateConditions -> False]] // Timing
(* {3.835651, ((a - b)^2 π)/(4 (a + b))} *)


text:
Q: Search only directories with permission -find (Bash 4.2) I have a command on AIX that finds files containing a phrase and are older than a certain age. however my report is full of permission denied errors. I would like the find to only search files that it has permission for.
I have command for linux that works
find /home/ ! -readable -prune -name 'core.20*' -mtime +7 -print

however in this case i am unable to use readable.
find /home/ -name 'core.20*' -mtime +7 -print 2>/dev/null

works rather well, but this still tries to search the directories costing time.

A: Just use your
find /home/ -name 'core.20*' -mtime +7 -print 2>/dev/null

When you want to skip dir's without permission, your script must somehow ask Unix for permission. This is exactly what find is doing: when the toplevel is closed, no time is spent on the tree beneath. The only cost is the stderr, and that is what you redirect.
When you want to optimise this for daily use, you might want to make a file with files not changed for over a day in a once-every-6-days crontab, and use the log as input for the daily claing. This solution will not help much and is very dirty. Just stick with your 2>/dev/null

A: A really simple fix, if it works for you, would be to filter out the errors using grep, something like:
find /home/ -name 'core.20*' -mtime +7 -print 2>/dev/null | grep -v 'Permission denied'

This will hide any results containing the phrase 'Permission denied' (case sensitive).
HTH!


text:
Q: Extracting tag attributes with beautifulsoup I have been pulling my hair out all day with this. Basically I am unable to extract information from tags
like:
<REUTERS LEWISSPLIT="TRAIN">

I cannot get the value of LEWISSPLIT and store it in a list
I have the following code:
import arff
from xml.etree import ElementTree
import re
from StringIO import StringIO

import BeautifulSoup
from BeautifulSoup import BeautifulSoup

totstring=""

with open('reut2-000.sgm', 'r') as inF:
    for line in inF:
        string=re.sub("[^0-9a-zA-Z<>/\s=!-\"\"]+","", line)
    totstring+=string

soup = BeautifulSoup(totstring)

bodies = list()
topics = list()
tags = list()

for a in soup.findAll("body"):
    bodies.append(a)

for b in soup.findAll("topics"):
    topics.append(b)

for item in soup.findAll('REUTERS'):
    tags.append(item['TOPICS'])

outputstring=""

for x in range(0,len(bodies)):
    if topics[x].text=="":
        continue
    outputstring=outputstring+"<TOPICS>"+topics[x].text+"</TOPICS>\n"+""+bodies[x].text+"\n"

outfile=open("output.sgm","w")
outfile.write(outputstring)

outfile.close()

print tags[0]

file.close

For parsing some old reuters XML that looks a little like this:
<!DOCTYPE lewis SYSTEM "lewis.dtd">
<REUTERS TOPICS="YES" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET" OLDID="5544" NEWID="1">
<DATE>26-FEB-1987 15:01:01.79</DATE>
<TOPICS><D>cocoa</D></TOPICS>
<PLACES><D>el-salvador</D><D>usa</D><D>uruguay</D></PLACES>
<PEOPLE></PEOPLE>
<ORGS></ORGS>
<EXCHANGES></EXCHANGES>
<COMPANIES></COMPANIES>
<UNKNOWN>
C T
f0704reute
u f BC-BAHIA-COCOA-REVIEW   02-26 0105</UNKNOWN>
<TEXT>
<TITLE>BAHIA COCOA REVIEW</TITLE>
<DATELINE>    SALVADOR, Feb 26 - </DATELINE>Showers continued throughout the week in
the Bahia cocoa zone, alleviating the drought since early
January and improving prospects for the coming temporao,
although normal humidity levels have not been restored,
Comissaria Smith said in its weekly review.
</TEXT>
</REUTERS>
<REUTERS TOPICS="NO" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET" OLDID="5545" NEWID="2">
<DATE>26-FEB-1987 15:02:20.00</DATE>
<TOPICS></TOPICS>
<PLACES><D>usa</D></PLACES>
<PEOPLE></PEOPLE>
<ORGS></ORGS>
<EXCHANGES></EXCHANGES>
<COMPANIES></COMPANIES>
<UNKNOWN>
F Y
f0708reute
d f BC-STANDARD-OIL-<SRD>-TO   02-26 0082</UNKNOWN>
<TEXT>
<TITLE>STANDARD OIL <SRD> TO FORM FINANCIAL UNIT</TITLE>
<DATELINE>    CLEVELAND, Feb 26 - </DATELINE>Standard Oil Co and BP North America
Inc said they plan to form a venture to manage the money market
borrowing and investment activities of both companies.
    BP North America is a subsidiary of British Petroleum Co
Plc <BP>, which also owns a 55 pct interest in Standard Oil.
    The venture will be called BP/Standard Financial Trading
and will be operated by Standard Oil under the oversight of a
joint management committee.
</TEXT>
</REUTERS>
<REUTERS TOPICS="NO" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET" OLDID="5546" NEWID="3">
<DATE>26-FEB-1987 15:03:27.51</DATE>
<TOPICS></TOPICS>
<PLACES><D>usa</D></PLACES>
<PEOPLE></PEOPLE>
<ORGS></ORGS>
<EXCHANGES></EXCHANGES>
<COMPANIES></COMPANIES>
<UNKNOWN>
F A
f0714reute
d f BC-TEXAS-COMMERCE-BANCSH   02-26 0064</UNKNOWN>
<TEXT>
<TITLE>TEXAS COMMERCE BANCSHARES <TCB> FILES PLAN</TITLE>
<DATELINE>    HOUSTON, Feb 26 - </DATELINE>Texas Commerce Bancshares Inc's Texas
Commerce Bank-Houston said it filed an application with the
Comptroller of the Currency in an effort to create the largest
banking network in Harris County.
    The bank said the network would link 31 banks having
13.5 billion dlrs in assets and 7.5 billion dlrs in deposits.

 Reuter
</TEXT>
</REUTERS>

I am interested in removing special characters, extracting both the content of the body and topic tags and building new xml out of them:
<topic>oil</topic>
asdsd
<topic>grain</topic>
asdsdds

I want to split this data based upon the value of LEWISSPLIT
I have been able to do all of this so far apart from split it on the value of lewissplit.
This is because I CANNOT extract the value from the <reuters> tag. I have tried many different techniques from this website and the official documentation but when running
for item in soup.findAll('REUTERS'):
    tags.append(item['LEWISSPLIT'])

print tags[0]

all i get is []
Why on earth is it so hard to extract the value of the LEWISSPLIT attribute from the <REUTERS> tag?
Thanks so much for reading this.
See also Extracting tag information with beautifulsoup and python

A: Joel Cornett is correct,
"reuters" along with "lewissplit" should have been in lower case :( Correct syntax:
for item in soup.findAll('reuters'):
    tags.append(item['lewissplit'])


text:
Q: Find all functions $f:\mathbb N\to\mathbb N$ such that $f\left(f(m)+f(n)\right)=m+n$, for all $m,n \in\mathbb N$.
Find all functions $f:\mathbb N\to\mathbb N$ such that $f\left(f(m)+f(n)\right)=m+n$, for all $m,n \in\mathbb N$.

I did not get any idea. I was just plugging out values for $m=n=1$ and so on
no idea.

A: Here, we assume $\mathbb N$ doesn't contain $0$, although the analysis should be pretty similar in the case where $0\in\mathbb N$.
Firstly, if $f(x)=f(y)$, then
$$2x=f(2f(x))=f(2f(y))=2y,$$
so $x=y$; i.e., $f$ is injective. Now, consider any $a,b,c\in\mathbb N$ with $a+b>c$. Then
$$f(f(a)+f(b))=a+b=c+(a+b-c)=f(f(c)+f(a+b-c)),$$
which implies that
$$f(a)+f(b)=f(c)+f(a+b-c).$$
In particular, let $f(1)=t$ and $f(2)=t+u$. We claim that $f(n)=t+u(n-1)$ for all $n$, which can be proven by strong induction. It holds for $n\in\{1,2\}$, and for $n\geq 3$,
$$f(n)+f(1)=f(2)+f(n-1),$$
which implies
$$f(n)=f(n-1)+f(2)-f(1)=t+u(n-2)+t+u-t=t+u(n-1),$$
as desired. This means that
$$m+n=f(f(m)+f(n))+f(2t+u(m+n-2))=t+u(2t+u(m+n-2)).$$
Since $u\geq 0$, we must have $u=1$, since the left side is $m+n$ and the right side is $u^2(m+n)$ plus some constant independent of $m$ and $n$. Then, we need
$$m+n=t+2t+m+n-2,$$
which gives $t=1$. As a result, the only working function is the identity.

A: This is not an answer, mostly just results I found interesting, feel free to edit this post to complete it.
I'm going to assume there's no $0$ in $\mathbb{N}$ (if there was then the function would not be well-defined unless $f(0)=0$, if $0 \mapsto e \not=0$ then $2e \mapsto 0$ and then $0\color{red}{\mapsto} 4e \not= e$):
$f$ by definition must be injective, injective basically means that $f$ doesn't map different elements in the domain $(\mathbb{N})$ to the same element in the range/codomain $(\mathbb{N})$. Say you had a function $g$ s.t. $g(1)=1$ and $g(2)=1$, that cannot happen if $g$ is injective because $g$ doesn't map different elements $(1\not=2)$ to the same element $(\text{in this case } 1)$.
As mentioned by hellofriends in the comments:
Suppose $f(m)=f(n)$ then $f(m)+f(m)=f(n)+f(m)$ and applying $f$ to both sides $$f(f(m)+f(m))=f(f(n)+f(m))$$
$$m+m=n+m$$
$$m=n$$
after subtracting $m$ from both sides, thus if $f(m)=f(n)$ then $m=n$ and $f$ must be injective.
By definition of a function every input must have an output, thus $1$ must be mapped to something, call it $s\in \mathbb{N}$. We can assume $s \not= 1$ because then $f(n)=n\:$ $\forall n \in \mathbb{N}$ which clearly satisfies $f(f(m)+f(n))=f(m+n)=m+n$, and we can assume that $s\not= 2$ because then $f$ would not be injective or well-defined, $1\mapsto 2$ then $4 \mapsto 2$ and then $2+2 = 4 \mapsto 1+4 =5$. Let $\alpha \geq 0$.
Given $\color{blue}{(1)}1 \mapsto s$, then $\color{blue}{(2)}2s \mapsto 2$ and $4 \mapsto 4s$, from then on we can use
$\color{blue}{(1)},\color{blue}{(2)}$ consecutively to get $5s\mapsto 5, 8s \mapsto 8,..., (3\alpha + 2)s \mapsto (3\alpha + 2),...$ thus we have $f$ must be surjective onto $[2]_3 \cap \mathbb{N}$.
Also $2$ must be mapped to something, $s' \in \mathbb{N}$ where $s' \not= s$ because $f$ is injective. $s' \not= 1$ because then $2\mapsto 1$ implies $2 \mapsto 4$ and $f$ would not be well-defined.
Then $2 \mapsto s'$ and using $\color{blue}{(1)}$ we get $s+s'\mapsto 3$, then
$\color{blue}{(1)},\color{blue}{(2)}$ consecutively $4s + s' \mapsto 6, 7s + s' \mapsto 9, 10s+s'\mapsto 12,...,(3\alpha +1)s+s'\mapsto 3\alpha +3,...$ consequently $f$ must be surjective onto $[0]_3 \cap \mathbb{N}$.
Also since $2 \mapsto s'$, $2s' \mapsto 4$ and using $\color{blue}{(1)},\color{blue}{(2)}$ consecutively $3s + 2s' \mapsto 7, 6s+2s'\mapsto 10,..., 3\alpha s+2s'\mapsto 3(\alpha +1)+1$ and thus $f$ must be surjective onto $[1]_3\cap \mathbb{N} \setminus \{1\}$.
$f$ is pretty close to surjective, all that's missing is the existence of $\gamma \in \mathbb{N}$ s.t. $f(\gamma)=1$.
edit:
Thanks to Carl's proof it looks like my post was half-baked, I started by letting $1\mapsto 2$ and derived a contradiction, I should of kept going and tried other values because it turns out that as you try other values for $f(1)>1$ they all somehow lead to a contradiction and the above arguments can be used to demonstrate this:
Suppose $1\mapsto (3\alpha +2) \in [2]_3 \cap \mathbb{N}$ then $(3\alpha+2)^2 \mapsto 3\alpha +2$ and $(3\alpha+2)^2 \geq 4 >1$. $f$ would not be injective, contradiction.
Suppose $1\mapsto 3\alpha +3 \in [0]_3 \cap \mathbb{N}$ then $(3\alpha +1)(3\alpha +3)+s' \mapsto 3\alpha +3$ and $(3\alpha+1)(3\alpha+3)+s'\geq 3+s'>3>1$ because $s'>0$. $f$ would not be injective, contradiction.
Suppose $1\mapsto 3(\alpha +1)+1 \in [1]_3 \cap \mathbb{N}$ then $3\alpha(3(\alpha +1)+1)+2s' \mapsto 3(\alpha +1)+1$ and $3\alpha(3(\alpha +1)+1)+2s'\geq 0+2s' \geq 2\cdot 1 >1$. $f$ would not be injective, contradiction.
Since we ran through all possiblities $1\mapsto s \in \mathbb{N}\setminus\{1\}$ and they all led to a contradiction, one way or another, we are left only with the original case we knew that worked $1 \mapsto 1$, i.e. $f$ is the identity.

A: My solution:
As it is already shown by @Carl Schildkraut that $f$ is one-one.
Let $k<n$, then from $f(f(m)+f(n))=m+n \cdots(1)$
$f(f(m+k)+f(m-k))=(m+k)+(m-k)=m+n=f(f(m)+f(n))$
Using the fact $f$ is one-one functions, this implies $f(m+k)+f(n-k)=f(m)+f(n)\; \forall \; m,n,k\in \mathbb N\;, k<\mathbb N\cdots(2)$
Suppose, $f(1)=b>1$. Then $b$ is at least 2.
Moreover We get
$f(2b)=f(f(1)+f(1))=2\;$ and $\; f(b+2)=f(f(1)+f(2b))=1+2b \cdots (3)$.
But $b$ cannot be $2$ because if it is $2$ the above equation $(3)$ gives contradictory result.
Now using Equation $2$
$f(2b)+f(1)=f(2b-(b-2))+f(1+(b-2))=f(b+2)+f(b-1)$.
$\implies$
$2+b=1+2b+f(b-1)$
$\implies$
$f(b-1)=1-b$. But this is impossible since $1-b<0$ and $f(1-b)\geq 1$
Now we conclude that $b=1$.
Thus $2=f(2b)=f(2)$.
Now we compute the proof by induction. Suppose $f(k)=k$ $\forall \; k\leq n\;$.
Using the given equation we obtain $n+1=f(f(n)+f(1))=f(n+1)$
Since $f(n)=n$ by induction hypothesis. It follows that $f(n)=n \;\forall \in \mathbb N$


text:
Q: Which ansible.cfg timeout value is "-T" overriding on the ansible-playbook command? The ansible-playbook documentation says that -T will "override the connection timeout in seconds (default=10)".
In the /etc/ansible/ansible.cfg file, under the [persistent_connection] section, there's connect_timeout (default 30 sec) and command_timeout (default 10 sec).
The ansible-playbook documentation would suggest it's the connect_timeout being overridden, but the default value that page specifies doesn't match the connect_timeout default value, it matches the command_timeout default value.
So, does the -T flag on the ansible-playbook command override the connect_timeout, command_timeout, or some other timeout not related to either of those?

A: -T is an equivalent of DEFAULT_TIMEOUT configuration setting.
DEFAULT_TIMEOUT:
  default: 10
  description: This is the default timeout for connection plugins to use.
  env:
  - {name: ANSIBLE_TIMEOUT}
  ini:
  - {key: timeout, section: defaults}
  name: Connection timeout
  type: integer

For ssh connections plugin is it used as ConnectTimeout=<value>, meaning:
ConnectTimeout
   Specifies the timeout (in seconds) used when connecting to the SSH server, instead of using the default system TCP timeout.
   This value is used only when the target is down or really unreachable, not when it refuses the connection.

command_timeout is about:
PERSISTENT_COMMAND_TIMEOUT:
  default: 10
  description: This controls the amount of time to wait for response from remote device
    before timing out presistent connection.
  env:
  - {name: ANSIBLE_PERSISTENT_COMMAND_TIMEOUT}
  ini:
  - {key: command_timeout, section: persistent_connection}
  name: Persistence command timeout
  type: int


text:
Q: UITapGestureRecognizer conflicting with each other So I have two UITapGestureRecognizer one is for a single tap and the other one is for a double tap. However when I do a double tap, the single tap action gesture recognizer is triggered as well. Is there a way to disable this so that double tap calls the double tap action only?

A: try
[singleTap requireGestureRecognizerToFail:doubleTap];


text:
Q: How to download a file from a website that prompts a popup form? For the last couple of years we have been able to download a FedACH file from Federal Reserve website (frbservices.org) using the wget utility.  The link below provided the original solution:
wget how to download file from a web page that prompts you to click on "Agree" condition

*

*get the cookies:
wget --post-data="agreementValue=Agree" https://frbservices.org/EPaymentsDirectory/submitAgreement --save-cookies cookie.txt --keep-session-cookies --delete-after

*download the file:
wget --load-cookies=cookie.txt 'https://frbservices.org/EPaymentsDirectory/FedACHdir.txt?AgreementSessionObject=Agree'

Using this wget commands just downloads https://www.frbservices.org/EPaymentsDirectory/download.html because the website is requesting that a popup form be filled in after clicking the "Agree" button now. Is there some way to just close the form using wget?
In IE and Chrome, the steps below were executed to download the desired file:

*

*Go to URL: https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt

*Click Agree button.

*Form is displayed requesting organization information.

*Click Close button on form (I did not fill in any information).

*Go to URL: https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt

*File downloads successfully.

A: The website requires you to have two cookies set: A valid JSESSIONID and the abaDataCaptureCookie called agreement cookie. The first can be obtained with your first wget command, the second one needs to be added manually.

*

*Obtain a valid JSESSIONID and save it to cookies.txt:
wget --post-data="agreementValue=Agree" frbservices.org/EPaymentsDirectory/submitAgreement --save-cookies cookies.txt --keep-session-cookies --delete-after

*Add the abaDataCaptureCookie line:
echo -e "frbservices.org\tFALSE\t/EPaymentsDirectory/\tFALSE\t0\tabaDataCaptureCookie\tabaDataCaptureCookie" >>cookies.txt

*Download the file:
wget --load-cookies cookies.txt frbservices.org/EPaymentsDirectory/FedACHdir.txt

I'm not quite sure how long the first cookie stays valid, but I assume you won't download the list multiple times per hour, so obtaining a new one on every run seems OK to me – that's the failsafe approach after all.
Script version of the above steps, using a tempfile as the cookie file:
#!/bin/bash
cookiefile=$(mktemp)
wget --post-data="agreementValue=Agree" frbservices.org/EPaymentsDirectory/submitAgreement --save-cookies $cookiefile --keep-session-cookies --delete-after
echo -e "frbservices.org\tFALSE\t/EPaymentsDirectory/\tFALSE\t0\tabaDataCaptureCookie\tabaDataCaptureCookie" >>$cookiefile
wget --load-cookies $cookiefile frbservices.org/EPaymentsDirectory/FedACHdir.txt

Running this script will save the current FedACHdir.txt to the current directory without leaving a cookies.txt lying around, if there's already a file with this name wget adds a number and saves it as e.g. FedACHdir.txt.1.
On resolving this issue I found great help here: Format of cookies when using wget? · U&L


text:
Q: PHP compare two arrays but all values of first array needs to be in second again - sorry for the dumb explanation in the past ... i didn't get my error and this drives me crazy...
so i have two arrays - one is normal array, the other multidimensional. But maybe this doesn't matter because i explode both strings i want to compare to arrays ...
here my code:
<?php
$arr1 = ["folds" => '01,03,'];
if($arr1['folds'][strlen($arr1['folds'])-1] == ","){
    $arr1['folds'] = substr($arr1['folds'], 0, -1);
}
$check = explode(",", $arr1['folds']);

$arr2 = [
    ["Offer" => "Website", "folds" => '01'],
    ["Offer" => "Development", "folds" => '01,03,05,10,14,15,21,22,'],
    ["Offer" => "Testing", "folds" => '01,03,04,10,15,22'],
    ["Offer" => "Sales", "folds" => '01,03,10,22,']
];

$arr3 = [];
foreach($arr2 as $i_arr){
    if($i_arr['folds'][strlen($i_arr['folds'])-1] == ","){
        $i_arr['folds'] = substr($i_arr['folds'], 0, -1);
    }
    $tocheck = explode(",", $i_arr['folds']);
    foreach($check as $chk){
        if(in_array($chk, $tocheck)){
            $arr3[] = $i_arr;
        }
    }
}

print_r($arr3);

?>

so i have at least two arrays ($check and $tocheck) - $check contents search or filter values like ever you want to name it. $tocheck cames from database and got the information to be filtered.
My Code doesn't do what i want it to do - because the in_array($check[x], $tocheck[y]) checks all values in $check with all values in $tocheck - but when just one value fits it says "true".
My challenge is to only print $i_arr in $arr3 when all values in $check are also in $tocheck, not jut one...
anyone an idea?

A: Loop through $arr2 and check for strpos() of $arr1["folds"]:
<?php

$arr1 = ["folds" => '02,04'];

$arr2 = [
    ["Offer" => "Website", "folds" => '02'],
    ["Offer" => "Development", "folds" => '02,04,09']
];

$arr3 = [];
foreach($arr2 as $i_arr){
    if(isset($i_arr["folds"]) && strpos($i_arr["folds"], $arr1["folds"]) > -1){
        $arr3[] = $i_arr;
    }
}

print_r($arr3);

?>

Output:
Array
(
    [0] => Array
        (
            [Offer] => Development
            [folds] => 02,04,09
        )

)

https://paiza.io/projects/_0nC44WHlZJpkdLOjm1Tkw

A: Thanks to you all - i resolved it.
Here the solution - maybe it will help someone else:
<?php
// Your code here!
$arr1 = ["folds" => '01,03,'];
if($arr1['folds'][strlen($arr1['folds'])-1] == ","){
    $arr1['folds'] = substr($arr1['folds'], 0, -1);
}
$check = explode(",", $arr1['folds']);

$arr2 = [
    ["Offer" => "Website", "folds" => '03'],
    ["Offer" => "Development", "folds" => '01,03,05,10,14,15,21,22,'],
    ["Offer" => "Testing", "folds" => '01,03,04,10,15,22'],
    ["Offer" => "Sales", "folds" => '01,03,10,22,']
];
$use = "no";

$arr3 = [];
foreach($arr2 as $i_arr){
    if($i_arr['folds'][strlen($i_arr['folds'])-1] == ","){
        $i_arr['folds'] = substr($i_arr['folds'], 0, -1);
    }
    $tocheck = explode(",", $i_arr['folds']);
    foreach($check as $chk){
        if(in_array($chk, $tocheck)){
            $use = "yes";
        } else {
            $use = "no";
            break;
        }
    }
    if($use == "yes"){
        $arr3[] = $i_arr;
    }
}

print_r($arr3);

?>


text:
Q: Using Mitre's AttackCTI, How Do I Iterate A List To Output Desired Results This is a really basic thing I'm asking and I apologize in advance for my novice. I am using Python and JupyterLab to interact with Mitre's Attack Framework (AttackCTI). I want to insert a custom set of attack TECHNIQUES and get a return of the associated attack TACTICS. I assume my problem isn't specific to JL or the AttackCTI, but rather, a lack of skill in Python.
To be honest, I'm not even sure what the last bit of this code is even doing. It's probably not even necessary for what I'm trying to do. I'm very lost, frustrated and inexperienced. I thank you for your patience.
Please help, if you can.
from attackcti import attack_client
from pandas import *
import json
import logging
logging.getLogger('taxii2client').setLevel(logging.CRITICAL)
lift = attack_client()
enterprise_techniques = lift.get_enterprise_techniques()
techniques = []
for t in enterprise_techniques:
    techniques.append(json.loads(t.serialize()))
df = pandas.json_normalize(techniques)
df.reindex(['name'], axis=1)[0:5]


text:
Q: Error when creating template based trigger I have a web check rule that does the following:-

*

*Use a web scenario to test the website is up or down

*Checks whetherthe domain is coming up to renewal

*Checks the SSL expiry date

I am trying to configure a trigger that will get used in conjunction with the web scenario.
Here is what I have
{{HOST.NAME:web.test.fail[Check {HOST.NAME} is up].last()}}<>0

There is a valid website address that gets picked up correctly when I specify the host address, but when I use the macro I get the following error
Incorrect trigger expression. Check expression part starting from "{{HOST.NAME:web.test.fail[Check {HOST.NAME} is up].last()}}<>0".
How can I resolve this?
Thanks

A: Ok, turns out I needed this
{Template Website Availability Checks:web.test.fail[Check {HOST.NAME} is up].last()}<>0


text:
Q: Installing python packages on anaconda on macos This may be a silly simple question, but I couldn't find an answer in the documentation of Anaconda or elsewhere. I am a bit of a noob when it comes to Python and I am trying to install a package. The problem is generalizable to other packages.
specs
I am working on a macOS Catalina (10.15.5) and using Anaconda as my python environment (python2.7).
problem
I am attempting to install the package pyLDAvis in my python environment, but the package isn't available on Anaconda's environment manager, and pip or conda install isn't working on the Spyder shell. Do pip and conda installs only work on the Anaconda Prompt? The problem is that I have read that the Anaconda Prompt only exists on Windows, and I am on mac. How could I install packages (pip, conda, or else) on Anaconda?
Am I missing something?
Any help or pointers to documentation would be great! Thanks

A: Assuming you have conda already installed and your shell is properly configured, you can activate the base environment via
conda activate

You can also create a new environment, see manage-environments docs.
For more information than given below, see manage-pkgs docs.
In case of conda, after your environment is activated, you can then install a package via conda install <package name>, e.g. the package numpy
conda install numpy

In case of pip, after your environment is activated, you can then install a package via pip install <package name>, e.g. the package numpy
pip install numpy

I only do this if the package is not available via a conda channel.
If the package is also not available via pip, you can download the source and set the package up your self. Usually the package author describes how to set up his/her package.

A: Thanks Stefan for the suggestion! I struggled a bit because although conda was "already installed", my shell was indeed not "properly configured." I am writing here my solution because it may be a recurring theme for macOS users and had an easy fix.
Starting with macOS Catalina, macOS uses zsh and not bash as the default shell, and so calling conda on zsh had no effect. The error message was: -zsh: conda: command not found. I solved this by changing the default shell to bash by running the following command: chsh -s /bin/bash.
Now that the shell and conda are properly configured, I  managed to use conda activate as you suggested Stefan.
Finally, the package pyLDAvis could not be installed by conda install pyldavis but was installed with pip install pyldavis.
Solved!


text:
Q: Why this python function has Twice Return? I find a Python Function like below from Head First:
def san(string):
    if ':' in string:
        spliter = ':'
    elif '-' in string:
        spliter = '-'
    else:
        return string
    (key, value) = string.split(spliter)
    return (key, value)

why twice RETURN ?

A: One is for the case where the string is not split, the other is for the case where the string is split.

A: The return in the else clause is used to return before using the split function, returning the original string. The return at the bottom of the block is used to return the value after the split function has occurred.
Using multiple returns is common in most programming languages and is usually used to break out of a function when you know that you don't need to run the remainder of the function. It is very useful when you reach an exceptional condition, there you can just return a special case which the function caller can pick up and know that an error has occurred.
Do note however, that some people consider it to be bad style, especially if it causes inconsistent behaviour (like it does in your example).


text:
Q: Apparent abuse across sites. A pair of users seem to be hitting several sites with poor or plagiarized answer, and the first user immediately accepts the answer of the second. I've notified mods on both sites, but suspect this pair are hitting more sites. Anything else I can do to help stop them?
For example:
https://cstheory.stackexchange.com/questions/34630/what-is-the-job-of-the-network-layer-under-the-osi-reference-model
https://cs.stackexchange.com/questions/56840/what-are-the-concepts-required-to-be-conceptual-perfect-with-computer-science?newreg=678835c225294df7b34cc123ea8d99dd


text:
Q: Multiple login using spring security, java config I have multiple logins for my applications. I have defined security filters in two different configurations.
This one has @Order(1) for admin:
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/**")
                .authenticated()
                .and()
            .formLogin()
                .loginPage("/admin/login").defaultSuccessUrl("/admin")
                .usernameParameter("username").passwordParameter("userpassword")
                .permitAll()
                .and()
            .logout().logoutSuccessUrl("/admin/login")
                .permitAll().and()
                .csrf();
    }

And other one:
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/tasker/**")
                .authenticated()
                .and()
            .formLogin()
                .loginPage("/tasker/login")
                .usernameParameter("taskeremail").passwordParameter("taskerpassword")
                .permitAll()
                .and()
            .logout().logoutSuccessUrl("/")
                .permitAll().and()
                .csrf();
    }

The first one for admin works fine but the second one is not even securing the /tasker/** urls.
Found simular questions but not answerd. Even I could not find anything helpful on spring reference. Please help.


text:
Q: Bind FITS image to tkinter canvas in Python See main point below code chunk for quick summary
For research, I'm trying to write a photometry program in python (I know there is software out there, but there's a specific reason I'm writing my own). I am using Anaconda with Python 3.6 and can get the FITS file image to render, but I want to be able to click on a point and perform photometry.
Basically I want to bind the image to a tkinter canvas and have a click event to return the location.
I've been looking at almost the exact same question here, but the key differences are that I'm using a FITS file and python 3.6 (which changes a lot of the features in that example)
My code thus far (using much of what that example showed) is:
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
import scipy as sp
import tkinter as tk
import PIL

hdulist = fits.open('00000039.sat_26624U.fit')
hdulist.info()
scidata = hdulist[0].data

histo = sp.histogram(scidata, 60, None, True)
display_min = histo[1][0]
display_max = histo[1][1]
pic = plt.imshow(scidata, cmap=plt.cm.gray, vmin=display_min, vmax=display_max, origin="lower")

#Try tk stuff
root = tk.Tk()

#setting up a tkinter canvas
frame = tk.Frame(root, bd=2, relief=tk.SUNKEN)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
canvas = tk.Canvas(frame, bd=0)
canvas.grid(row=0, column=0, sticky=tk.N+tk.S+tk.E+tk.W)
frame.pack(fill=tk.BOTH,expand=1)

#Add image
hold = tk.PhotoImage(pic)
canvas.create_image(0,0,image=hold,anchor="nw")

#function to be called when mouse is clicked
def printcoords(event):
    #outputting x and y coords to console
    print (event.x,event.y)
#mouseclick event
canvas.bind("<Button 1>",printcoords)

root.mainloop()

hdulist.close()

Which shows the image but gives me an error at:
#Add image
hold = tk.PhotoImage(pic)
canvas.create_image(0,0,image=hold,anchor="nw")

That says:
TypeError: __str__ returned non-string (type AxesImage)
Main Point:
I can't get a FITS image to bind to a tkinter canvas. I don't know how to click that image and get the location of the mouse click. I want to be able to click a few points, get their locations, and use those locations to draw a few annuli.
I have plenty of other issues, but that's my main hang up right now. Eventually I will be trying to track them (move to the next picture and search roughly the same area until I find the object again, placing the annulus) and counting the pixels inside, but I can cross that bridge later (unless anyone has ideas now).

A: After talking to some people, I found the issue to be that a tkinter canvas needs a file type like .gif or .png to bind an image to the canvas. So I changed
pic = plt.imshow(scidata, cmap=plt.cm.gray, vmin=display_min, vmax=display_max, origin="lower")

to
plt.imsave("tempimgfile.gif", scidata, cmap=plt.cm.gray, vmin=display_min, vmax=display_max, origin="lower")

and
hold = tk.PhotoImage(pic)

to
hold = tk.PhotoImage(file="tempimgfile.gif")

saving my numpy array as a gif file just long enough to bind, then deleting it after.
Bottom line: Convert a FITS file to .gif or other compatible type
It may not be the most elegant fix, but it worked

A: You have to do some changes in the code. First of all I would prefer to use the Place() method in Tkinter . You can look at place Method here how to i position buttons in tkinter?
Second thing : By using the place method it will be suitable for your application.
Hint: Place() Method works with x and y co-ordinates. So the two elements can overlap in Tkinter using Place() but it is not possible in Grid.
Now with Place() method place the image in some area in Tkinter window let say the image size is 100x100 and then make a button with the function call and place it behind the image giving the same co-ordinates in Place() Method. So when a user will click on image it will actually calls the function behind the button.


text:
Q: NGX - loader rotate logo I am trying to add an animation to the custom logos property.
However, the effects only apply to fgs.
Is there a way to add animation effects to the logo or add custom css classes to make it rotate?
This is my configuration, but only rotates the shape (rotating plane) not the imagen (isotipo.png)
const ngxUiLoaderConfig: NgxUiLoaderConfig = {
  bgsColor: '#1b4962',
  bgsOpacity: 0.5,
  bgsPosition: 'bottom-right',
  bgsSize: 60,
  bgsType: 'rotating-plane',
  blur: 5,
  delay: 0,
  fastFadeOut: true,
  fgsColor: '#1b4962',
  fgsPosition: 'center-center',
  fgsSize: 70,
  fgsType: 'rotating-plane',
  gap: 24,
  logoUrl: '../../assets/img/isotipo2.png',
  logoPosition: 'center-center',
  logoSize: 120,
  masterLoaderId: 'master',
  overlayBorderRadius: '0',
  overlayColor: 'rgba(40,40,40,0.2)',
  pbColor: '#eb5353',
  pbDirection: 'ltr',
  pbThickness: 3,
  hasProgressBar: true,
  textColor: '#FFFFFF',
  textPosition: 'center-center',
  maxTime: -1,
  minTime: 300
};


text:
Q: Unit Testing a SOQL Method I need some basic Unit Test writing assistance.
My method just runs a SOQL query to filter a contact list for service cloud. What's the best way to test it?
Here is the class:
public class ContactsListController{
    public ContactsListController(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
    }

    private final Account acct;

    public List<Contact> getContacts() {
        List<Account> acct =
            [SELECT id
             FROM Account
             WHERE id = :ApexPages.currentPage().getParameters().get('id')];

        List<Contact> results =
            [SELECT Id, AccountId, Full_Name__c, Email, Phone, Title
             FROM Contact
             WHERE (AccountId = :acct AND No_Longer_with_Company__c = False)];

        return results;
    }
}

The unit test inserts 50 new contacts, should I call to my getContacts method to get code coverage? Any pointers would be greatly appreciated.
Unit Test:
@isTest
class ContactsListControllerTest {
    static testMethod void testContactList (){
        //Insert 50 test contacts
        List<Contact> contacts = new List<Contact>();

        for (Integer count = 0; count < 50; count++) {
            contacts.add(new Contact (FirstName = 'John'+count, LastName ='Doe'+count));
        }

        insert contacts;

    }

}

A: It is a best practice to separate unit tests from functionality tests.
If you run your method from trigger on contacts insert and you want to cover functionality, you can write some method like this
static testMethod void testContactList (){
    //Insert 50 test contacts
    List<Contact> contacts = new List<Contact>();

    for (Integer count = 0; count < 50; count++) {
        contacts.add(new Contact (FirstName = 'John'+count, LastName ='Doe'+count));
    }
    Test.startTest();
        insert contacts;
    Test.startTest();
    // add some asserts here!
}

If you are writing just a unit test for this method, you need to put it inside startTest-stopTest like this:
static testMethod void testContactList (){
    //Insert 50 test contacts
    List<Contact> contacts = new List<Contact>();

    for (Integer count = 0; count < 50; count++) {
        contacts.add(new Contact (FirstName = 'John'+count, LastName ='Doe'+count));
    }
    insert contacts;
    ContactsListController cc = new ContactsListController(new ApexPages.StandardController(new Account()));
    Test.startTest();
        cc.getContacts();
    Test.startTest();
    // add some asserts here!
}

Don't forget to add asserts, you always need asserts to make sure your code works as expected.

Let me add some more suggestions.
Inside your method, you don't have to make two SOQL queries, one would be enough.
SOQL query calls are very costly and there is a limit on its amount during transaction ( you can make no more than 200 calls ) so you have to eliminate unnecessary SOQL queries.
I mean you can refactor your method
public List<Contact> getContacts() {
    List<Account> acct =
        [SELECT id
         FROM Account
         WHERE id = :ApexPages.currentPage().getParameters().get('id')];

    List<Contact> results =
        [SELECT Id, AccountId, Full_Name__c, Email, Phone, Title
         FROM Contact
         WHERE (AccountId = :acct AND No_Longer_with_Company__c = False)];

    return results;
}

in a following way:
public List<Contact> getContacts() {
    return
        [SELECT Id, AccountId, Full_Name__c, Email, Phone, Title
         FROM Contact
         WHERE (AccountId = :acct.Id AND No_Longer_with_Company__c = False)];
}

It is a good idea to have a factory utility class having methods to create records like following:
/**
 * This is an utility class to contain helper methods to create test data.
 */
@isTest
public class TestUtils {
/**
 * Helper method to create Account standard object records
 *
 * @param Integer numToCreate: This parameter orders which amount of records should be created and inserted
 *
 * @returns List<Account>: Created and inserted list of Account standard object records
 */
public static List<Account> createAccounts(Integer numToCreate) {
    List<Account> listToReturn = new List<Account>();
    for ( Integer i = 0; i < numToCreate; i++ ) {
        listToReturn.add( new Account( Name = 'Account ' + i ) );
    }
    insert listToReturn;
    return listToReturn;
}

/**
 * Helper method to create Contact standard object records
 *
 * @param Account account: This parameter supplies a single master record to populate on all the children
 * @param Integer numToCreate: This parameter controls how many Contact standard object records should be created
 * @param Boolean doInsert: This parameter commands if created data should be inserted here
 *
 * @returns static List<Contact>: Created and inserted list of Contact standard object records
 */
public static List<Contact> createContacts( Account account, Integer numToCreate, Boolean doInsert ) {
    List<Contact> listToReturn = new List<Contact>();
    for ( Integer i = 0; i < numToCreate; i++ ) {
        listToReturn.add(
            new Contact(
                FirstName = 'John' + i,
                LastName = 'Doe' + i,
                AccountId = account.Id
            )
        );
    }
    if (doInsert)
        insert listToReturn;
    return listToReturn;
}
}

Then you can organize your test method like follows
static testMethod void testContactList (){
    Account acc = TestUtils.createAccounts( 1 )[0];
    //Insert 50 test contacts
    List<Contact> contacts = TestUtils.createContacts( acc, 50, true );

    ContactsListController cc = new ContactsListController(new ApexPages.StandardController(a));
    Test.startTest();
        contacts = cc.getContacts();
    Test.startTest();
    System.assertEquals( 50, contacts.size(), 'Contact list size should match amount of created test records size' );
    // add some other asserts here!
}

Note that to make your test meaningful you have to attach contacts to account otherwise you won't receive any records returned.
Also it is good idea to have positive and negative use cases.
For example, you may create 50 records not attached to account ( negative cases ), 50 records attached to account but having No_Longer_with_Company__c set to true ( negative cases ) and 50 records attached to account having No_Longer_with_Company__c set to false ( positive cases ).
Only the last 50 record should be returned by your method in your test case.


text:
Q: How to reuse computation graph for different inputs? I have my main flow of computation set up that I can train using
train = theano.function(inputs=[x], outputs=[cost], updates=updates)

Similarly, I have a function for predictions
predict = theano.function(inputs=[x], outputs=[output])

Both of these functions accept the input x and send it through the same computation graph.
I would now like to modify things so that when training, I can train using a noisy input, so I have something like
input = get_corrupted_input(self.theano_rng, x, 0.5)

at the beginning of the computations.
But this will also affect my predict function, since its input will get corrupted as well. How can I reuse the same code for train and predict, but only provide the former with the noisy input?

A: You can organise your code like this:
import numpy
import theano
import theano.tensor as tt
import theano.tensor.shared_randomstreams

def get_cost(x, y):
    return tt.mean(tt.sum(tt.sqr(x - y), axis=1))

def get_output(x, w, b_h, b_y):
    h = tt.tanh(tt.dot(x, w) + b_h)
    y = tt.dot(h, w.T) + b_y
    return y

def corrupt_input(x, corruption_level):
    rng = tt.shared_randomstreams.RandomStreams()
    return rng.binomial(size=x.shape, n=1, p=1 - corruption_level,
                        dtype=theano.config.floatX) * x

def compile(input_size, hidden_size, corruption_level, learning_rate):
    x = tt.matrix()
    w = theano.shared(numpy.random.randn(input_size,
                      hidden_size).astype(theano.config.floatX))
    b_h = theano.shared(numpy.zeros(hidden_size, dtype=theano.config.floatX))
    b_y = theano.shared(numpy.zeros(input_size, dtype=theano.config.floatX))
    cost = get_cost(x, get_output(corrupt_input(x, corruption_level), w, b_h, b_y))
    updates = [(p, p - learning_rate * tt.grad(cost, p)) for p in (w, b_h, b_y)]
    train = theano.function(inputs=[x], outputs=cost, updates=updates)
    predict = theano.function(inputs=[x], outputs=get_output(x, w, b_h, b_y))
    return train, predict

def main():
    train, predict = compile(input_size=3, hidden_size=2,
                             corruption_level=0.2, learning_rate=0.01)

main()

Note that get_output is called twice. For the train function it is provided with the corrupted input but for the predict function it is provided with the clean input. get_output needs to contain "the same computation graph" that you talk of. I've just put a tiny autoencoder in there but you can put whatever you want in there.
Assuming the corrupted input has the same shape as the input, the get_output function won't care whether its input is x or the corrupted version of x. So get_output can be shared but need not contain the corruption code.


text:
Q: CSS3 transition (transform) not working in Firefox, but in Chrome and Safari I'm working on a simple slider, which uses CSS transitions to animate the slides. I created a pen with some basic styling and some javascript here. Note: Since Codepen uses Prefixfree I haven't used any prefixes.
The only part, which is animating is .slider__anim, not the .slider__item itself. I used position: absolute for all non active slides and position: relative for the active slide. That way I don't have to use a fixed height for my .slider.
In Chrome and Safari it works pretty well, but for some reason it just doesn't fire the CSS transitions in Firefox. Is this a bug in Firefox or is there any special markup for Firefox?

A: For everybody, who has the same problem: It's a bug in Firefox, see: https://bugzilla.mozilla.org/show_bug.cgi?id=625289


text:
Q: Kaplan-Meier IPCW My dataset is composed of n individuals (patients) with a two-year follow-up at maximum. Every patient is sane at the beginning of the study, and each month we note if the patients got a certain disease (which then will last very long, so once a patient has a disease, it's considered "death" with respect to the survival analysis meaning). And we have patients that left the study, so they will be censored.
Let's say that we have an "active month", meaning that at that moment we observe either a patient that got the disease (but didn't have the disease the previous month) or a patient that left the study that month. We have only 20 months out of 24 since, in the first four months, we didn't observe anything.
I performed a classical Kaplan-Meier estimator, with right-censoring, so got a 20 points (active months) curve. My vector E of size n contains binary information for each patient, indicating whether they got the disease (1) or drop_out of the study (0). Patients that didn't get the disease at month 24 were considered 0.
Then, I wanted to weight differently the patients, using the Inverse Probability of Censoring Weight (IPCW, and not the IP Treatment W).
So I first performed a Kaplan-Meier for censoring, which is just "inverting" the E vector, called E_censoring, which means censored patients are now 1, and others 0. Thus I get a 20 points curve indicating the "survival of censoring", so the chance of not being censored until time t.
Then, for each individual, I run a Cox-Regression model (for censoring, so the "goal" is E_censoring and not E), with variables like age, binary info indicating whether the patient has comorbidity, etc. I used a simple Cox model, without a time-varying variable, so age is just taken at the beginning of the study for example. So, I get for each patient a 20 points curve, and globally I get a matrix of shape n x 20.
Finally, for each patient I compute the weights like that: Kaplan-Meier basic curve "divided by" the Cox-regression curve for individual i. So, a patient will have 20 different weights, one for every "active month".
Then I computed the final IPCW Kaplan-Meier curve with that n x 20 weight matrix. The (survival) curve I got is a bit above the basic one, which seems to be a good thing.
I wanted to know if this is the standard procedure to get IPCW weights, or at least if this is a correct one? The paper I mostly based my work upon is Informative Censoring in Survival Analysis and Application to Asthma. Many papers are describing IPCW, but only partially, and with (sometimes very) different terms, which is confusing.
Thanks for any help!
PS : Another good material is the following thesis Inverse Probability Censoring Weights for Routine Outcome Monitoring Data, especially the Chapter 5, which is short. I understand really well the denominator (a Cox-regression, which gives an individual survival curve for censoring), but not the numerator, described as a "Product-Limit estimator" which might refer to a classical Kaplan-Meier. But apparently the numerator is different for each patient, which is not the case with Kaplan-Meier. Moreover, the numerator is based upon several variables, which once again is not the case for KM.

A: I have come across a very similar problem where I have to use IPCW in order to calculate the weights to account for censored data. I have found this article that might be useful for you, it talks in depth about IPCW.
"Adapting machine learning techniques to censored time-to-event health record data: A general-purpose approach using inverse probability of censoring weighting" By David M. Vock & Others
https://www.sciencedirect.com/science/article/pii/S1532046416000496
Also, if you have managed to solve your problem, it would be nice to hear what approach you took in the end.


text:
Q: Why is friction only on the back wheel?
This is how I understand friction when a bicycle is moving uphill. On the backwheels there will be friction in the forward direction to oppose the rotation of the wheel. But at the front wheel we are pushing it forward with the back wheel --> Friction is in the opposite direction to make it move forward.
Am I right ?
This is a free body diagram of a bicycle with constant speed!
Why is there only one friction force in the free body diagram? It is like that on all of my exam questions....

A: If the rider is not accelerating, there is no need for any force to do torque on the front wheel. Only gravity, normal force and the bike steering pole put forces on the front wheel, and non of them cause torques (all act in the middle).
Static friction is a force that only exists when needed! So when no other torques need to be balanced, no static friction appears. The front wheel just rolls effortless, without being stopped and without being helped.
On the rear wheel on the other hand, the rider pushes the pedals and creates a torque. Static friction appears to balance this, so the wheel doesn't slide.


text:
Q: AWK print field by variable value so I have a GET command retrieving data from a server, and only need specific parts of this info.
I have a working script but the awk part is very long and I was wondering if I could get some help shortening it.
Current script:
curl  --insecure -u $HMCUSER:$HMCPASS -H "Accept: */*" -H "Content-type: application/json" -s --header "X-API-Session:$COOKIE" -X GET https://$HMCIP:6794$BCID1/blades | awk -F\" '{print $50" M1:"$42"\n"$114" M1:"$106"\n"$18" M1:"$10"\n"$98" M1:"$90"\n"$34" M1:"$26"\n"$82" M1:"$74"\n"$66" M1:"$58"\n"$130" M1:"$122}' > ~walkers/blade-info-new

echo -e "\n`cat blade-info-new`\n"

and the output is:

/api/blades/394a7ea8-02d4-11e1-b71a-5cf3fcad1a40 M1:B.1.01
/api/blades/749f35cc-02d7-11e1-946a-5cf3fcad1ef8 M1:B.1.02
/api/blades/eeae9670-02d5-11e1-a5ee-5cf3fcad21e0 M1:B.1.03
/api/blades/3949f5a0-02d4-11e1-85df-5cf3fcad1dc8 M1:B.1.04
/api/blades/d25df328-02d3-11e1-a1e9-5cf3fcad2158 M1:B.1.05
/api/blades/bbecebd8-02d0-11e1-aca7-5cf3fcacf4a0 M1:B.1.06
/api/blades/3016b5d8-02d7-11e1-a66f-5cf3fcad1dd0 M1:B.1.07
/api/blades/75796586-02ea-11e1-8ab0-5cf3fcacf040 M1:B.1.08

(there are two columns: /api/blades/... and M1:B.1.0#)
So I tried this:
for i in {10..130..8}
do
     try=$(curl  --insecure -u $HMCUSER:$HMCPASS -H "Accept: */*" -H "Content-type: application/json" -s --header "X-API-Session:$COOKIE" -X GET https://$HMCIP:6794$BCID1/blades | awk -v i=$i -F\" '{print $i}')
     echo "$try"
done

hoping to get the same output as above and instead I just get the complete JSON object:

{"blades":[{"status":"operating","name":"B.1.03","type":"system-x","object-uri":"/api/blades/eeae9670-02d5-11e1-a5ee-5cf3fcad21e0"},{"status":"operating","name":"B.1.05","type":"system-x","object-uri":"/api/blades/d25df328-02d3-11e1-a1e9-5cf3fcad2158"},{"status":"operating","name":"B.1.01","type":"system-x","object-uri":"/api/blades/394a7ea8-02d4-11e1-b71a-5cf3fcad1a40"},{"status":"operating","name":"B.1.07","type":"system-x","object-uri":"/api/blades/3016b5d8-02d7-11e1-a66f-5cf3fcad1dd0"},{"status":"operating","name":"B.1.06","type":"system-x","object-uri":"/api/blades/bbecebd8-02d0-11e1-aca7-5cf3fcacf4a0"},{"status":"operating","name":"B.1.04","type":"system-x","object-uri":"/api/blades/3949f5a0-02d4-11e1-85df-5cf3fcad1dc8"},{"status":"operating","name":"B.1.02","type":"system-x","object-uri":"/api/blades/749f35cc-02d7-11e1-946a-5cf3fcad1ef8"},{"status":"operating","name":"B.1.08","type":"system-x","object-uri":"/api/blades/75796586-02ea-11e1-8ab0-5cf3fcacf040"}]}

So I was wondering how to get the variable to work? I've been on many websites and everyone seems to say awk -v i=$i should work...
EDIT: The sequence I want to print is the object uri (i.e. /api/blades/...) followed by the blade name (i.e. B.1.01). These infos are all in the JSON object returned by the curl command starting with the tenth field and every 8th field after that (using " as a delimiter):
{"blades":[{"status":"operating","name":"B.1.03","type":"system-x","object-uri":"/api/blades/eeae9670-02d5-11e1-a5ee-5cf3fcad21e0"},{"status":"operating","name":"B.1.05","type":"system-x","object-uri":"/api/blades/d25df328-02d3-11e1-a1e9-5cf3fcad2158"},{"status":"operating","name":"B.1.01","type":"system-x","object-uri":"/api/blades/394a7ea8-02d4-11e1-b71a-5cf3fcad1a40"},{"status":"operating","name":"B.1.07","type":"system-x","object-uri":"/api/blades/3016b5d8-02d7-11e1-a66f-5cf3fcad1dd0"},{"status":"operating","name":"B.1.06","type":"system-x","object-uri":"/api/blades/bbecebd8-02d0-11e1-aca7-5cf3fcacf4a0"},{"status":"operating","name":"B.1.04","type":"system-x","object-uri":"/api/blades/3949f5a0-02d4-11e1-85df-5cf3fcad1dc8"},{"status":"operating","name":"B.1.02","type":"system-x","object-uri":"/api/blades/749f35cc-02d7-11e1-946a-5cf3fcad1ef8"},{"status":"operating","name":"B.1.08","type":"system-x","object-uri":"/api/blades/75796586-02ea-11e1-8ab0-5cf3fcacf040"}]}
The blade names don't have to be in numerical order (B.1.01 to B.1.08), only on the same line as the corresponding ID
EDIT 2: Found a work around. Used a C type for loop instead of the normal bash: for (( i=10; i<=130; i+=8 )) instead of for i in {10..130..8}

A: The proper answer to this question is to ditch awk (even though I love awk) and use a real JSON parser, e.g. the very handy jq tool.

A: If I understand correctly you're wanting {10..130..8} to expand to give the required series of $i values.
In my version of bash (it's ooooold: 3.2.25) the string {10..130..8} doesn't expand to anything and so the loop is entered with i="{10..130..8}" and so awk uses ${10..130..8} which appears to simplify to $0 (i.e. the whole curl return string). Hence your problem. You can test if this is the case by putting echo $i inside your loop.
You need a better way of getting the series of values you want. You can use "seq" for this (man seq for more info). $( seq 10 8 130 ) should do it.
Further, you can make it so that curl is only called once with something messier like

    # Construct the string of fields
    for i in $( seq 10 8 130 ); do
       fields="$fields,\$$i"
    done
    fields=$( echo "$fields" | sed 's/^,//' ) # Remove the leading comma
    ...curl command... | awk '{print '$fields'}'

A: I think you want awk to access the updated value of the i variable. Because the awk instruction is between apostrophes (''), the value of i is hidden from awk, but you can avoid it by removing the apostrophes from the piece of the instruction that is replaced by the actual value of i.  It is explained on this online AWK manual, in the section Dynamic Variables.
So for your particular case, you could try

awk -F\" '{print $'$i'}'

instead of

awk -v i=$i -F\" '{print $i}'

at the end of your pipeline command.

A: How about changing record separator (RS), and defining field separator to quote. Then save the name, and print it together with object-url. The command below should give you a starting point
curl [...] | awk -v RS=, -F\" '{
    if ($2 ~ /^name$/) {name=$4}
    if ($2 ~ /^object-uri$/) {print name, $4}
}'

p.s. Remote the if's and printing $0 if you want to see how the RS=, helps you.


text:
Q: Powershell Send-MailMessage cmdlet - Subject parameter won't let me pass a number So as part of a larger script I'm working on I have to send an email with results
Whenever I use a number in the Subject field not only is the number not send BUT the mailmessage is never sent and no error message appears. I used try / catch even for haha's but there are not errors to be caught, it's quite perplexing. Anyone else ever run into this problem?
If I use alphabetical characters it functions fine, but numbers seem to cause issues :-/
Send-MailMessage -SmtpServer("mailserver.fakecorp.com") -From("Nagios.Monitor@fakecorp.com") -To("Adamk@fakecorp.com") -Subject("30") -Body("$arrProbURLs")

A: Apparently it's my email false alarm. I tried from my the pc of the cubicle over and it worked. Something with my email. Ok powershell's not the problem :) I thought that would have been quite strange! Thanks for the quick responses!


text:
Q: How To Read A File in php wrappers as utf-16 Is there a way to read a file in a specific character encoding like UTF-16 using PHP's stream wrappers, in the same way I can read a base64-encoded file using php://filter/convert.base64-decode/resource=file.txt?

A: PHP strings don't know anything about encodings, so PHP file functions essentially treat every file as a binary file.
If you know that a set of bytes should be read as UTF-16, you can convert it to some other encoding of your choice (here using UTF-8 as an example) using any of these (depending which extensions you have installed):
// Requires ext/iconv; arguments are From, To, String
$utf8_string = iconv('UTF-16', 'UTF-8', $utf16_string);
// Requires ext/mbstring; arguments are String, To, From
$utf8_string = mb_convert_encoding($utf16_string, 'UTF-8', 'UTF-16');
// Requires ext/intl; arguments are String, To, From
$utf8_string = UConverter::transcode($utf16_string, 'UTF-8', 'UTF-16');

Conversely, if you know that the string is in some particular encoding (again, using UTF-8 as an example), and want it to be UTF-16, you would put things in the opposite order:
// Requires ext/iconv; arguments are From, To, String
$utf16_string = iconv('UTF-8', 'UTF-16', $utf8_string);
// Requires ext/mbstring; arguments are String, To, From
$utf16_string = mb_convert_encoding($utf8_string, 'UTF-16', 'UTF-8');
// Requires ext/intl; arguments are String, To, From
$utf16_string = UConverter::transcode($utf8_string, 'UTF-16', 'UTF-8');

In both cases, the resulting string is just a different sequence of bytes; other PHP functions still won't "know" what it "means".

The "iconv" extension also provides a conversion filter which runs the equivalent of the iconv function as a file or stream is being read. So if you have a file which you know should be read as UTF-16, and want its contents as UTF-8, you could write:
$fp = fopen('php://filter/convert.iconv.utf-16.utf-8/resource=/path/to/utf16-file.txt', 'r');
$first_10_bytes_of_utf16_converted_to_utf8 = fgets($fp, 10);
fclose($fp);

Or the reverse - a UTF-8 file which you want to read as UTF-16:
$fp = fopen('php://filter/convert.iconv.utf-8.utf-16/resource=/path/to/utf8-file.txt', 'r');
$first_10_bytes_of_utf8_converted_to_utf16 = fgets($fp, 10);
fclose($fp);

Again, it's important to remember that PHP is working in bytes, so the fgets calls above may result in corrupted text because the 10th byte wasn't the end of a Unicode code point.


text:
Q: Influence of fast position change when using WLAN or e.g. 2.4GHz I tried to find some information about the following problem statement:
E.g. when having a rotating spindle (e.g. 20000RPMs) or having a RC car, which is moving really fast, will e.g. WLAN 2.4Ghz work reliable?
I mean, assuming that the signal strength is sufficient, will I get problem due to the relative velocity or can I neglect that?
Thanks.

A: You should find some discussion of this in the 802.11p amendment -wireless access in vehicular environments (WAVE) - which is part of the 802.11-2012 standard.
802.1p specifically addresses WiFi in vehicles at up to 200km/h so I expect would have some discussion of the issues of a fast moving station.


text:
Q: How to change value of textbox on click of button? I want to do it for Shopping Cart management

Product Name

   Rs 000/ KG

     -

    <input type="text" class="form-control quantity" value="2" />

      +

Rs 000

Here is my code which repeats as per products added into cart. I want to update quantity on click of it's add-quantity-cart and sub-quantity-cart buttons.
Thanks.

A: You can do it like this:

$(document).ready(function() {
   $(".add-quantity-cart").on("click", function() {
     let quantity = $(this).closest(".d-block").find(".quantity");
     let current = parseInt(quantity.val());
     current += 1;
     quantity.val(current);
   });
   $(".sub-quantity-cart").on("click", function() {
     let quantity = $(this).closest(".d-block").find(".quantity");
     let current = parseInt(quantity.val());
     if (current > 0) {
       current -= 1;
       quantity.val(current);
     }
   });
});

Product Name

   Rs 000/ KG

     -

    <input type="text" class="form-control quantity" value="2" />

      +

Rs 000


text:
Q: What methodology/algorithm does cv::absdiff() use? What methodology/algorithm does OpenCV's cv::absdiff(InputArray src1, InputArray src2, OutputArray dst) use?
For a 1 channel Mat does it compute the colour distance between each cell/voxel of src1 with the voxel at the same position of src2? Does it compute the intensity difference or colour difference or other? Is it's worst-case, average and best-case runtime O(N) (where N is the number of voxels in the Mat)? How is the absolute difference calculated?
In terms of runtime complexity is cv::canny() slower or faster than cv::absdiff()? Is the speed difference significant?

A: absdiff is a simple operation on a matrix. It computes the absolute value of the difference for each pixel, for each channel.
The operation is:
// pseudocode
Mat src1, src2, dst;
...
for each row : r
    for each column : c
        for each channel : ch
            dst(r,c,ch) = abs(src1(r,c,ch) - src2(r,c,ch))

You can see that the complexity is O(N), where N = rows * cols * channels, since you have to scan the full matrix. This is also highly optimizable.
canny instead is an algorithm, with a lot of steps involved.
I'm not aware of its complexity, but it's at least O(N) with an N much greater than absdiff.
So, canny is much slower than absdiff, but it's not a fair comparison.

OpenCV doesn't have the concept of voxel.


text:
Q: Javascript writing if statements to prompt user for input var noun;
var verb;
var adverb;
var adjective;
var pronoun;
var questions = 5; //this number can adjust
var paragraph;

var noun = prompt("Type Noun");
if (isNaN(noun) == "True"){
 questions -= 1;
 verb = prompt("Type Verb");
}else{
   alert("You entered a number, please enter a Noun.");
}
if (isNaN(verb) == "True"){
 questions -= 1;
 adverb = prompt("Type Adverb");
}else{
   alert("You entered a number, please enter a Verb.");
}
if (isNaN(adverb) == "True"){
 questions -= 1;
 adjective = prompt("Type Adjective");
}else{
   alert("You entered a number, please enter a Adverb.");
}
if (isNaN(pronoun) == "True"){
 questions -= 1;
}else{
   alert("You entered a number, please enter a Pronoun.");
}

So the main idea is to have the user input a word.
For some reason it marks the boolean false and goes directly into the else statement.....

A: This is because isNaN("some text") returns a boolean true/false -- and true == "True" returns false. Your statements should read:
if (isNaN(noun) === true) {
}
....


text:
Q: How do I reduce a python (docker) image size using a multi-stage build? I am looking for a way to create multistage builds with python and Dockerfile:
For example, using the following images:
1st image: install all compile-time requirements, and install all needed python modules
2nd image: copy all compiled/built packages from the first image to the second, without the compilers themselves (gcc, postgers-dev, python-dev, etc..)
The final objective is to have a smaller image, running python and the python packages that I need.
In short: how can I 'wrap' all the compiled modules (site-packages / external libs) that were created in the first image, and copy them in a 'clean' manner, to the 2nd image.

A: ok so my solution is using wheel, it lets us compile on first image, create wheel files for all dependencies and install them in the second image, without installing the compilers
FROM python:2.7-alpine as base

RUN mkdir /svc
COPY . /svc
WORKDIR /svc

RUN apk add --update \
    postgresql-dev \
    gcc \
    musl-dev \
    linux-headers

RUN pip install wheel && pip wheel . --wheel-dir=/svc/wheels

FROM python:2.7-alpine

COPY --from=base /svc /svc

WORKDIR /svc

RUN pip install --no-index --find-links=/svc/wheels -r requirements.txt

You can see my answer regarding this in the following blog post
https://www.blogfoobar.com/post/2018/02/10/python-and-docker-multistage-build

A: I recommend the approach detailed in this article (section 2). He uses virtualenv so pip install stores all the python code, binaries, etc. under one folder instead of spread out all over the file system. Then it's easy to copy just that one folder to the final "production" image.  In summary:
Compile image

*

*Activate virtualenv in some path of your choosing.

*Prepend that path to your docker ENV. This is all virtualenv needs to function for all future docker RUN and CMD action.

*Install system dev packages and pip install xyz as usual.

Production image

*

*Copy the virtualenv folder from the Compile Image.

*Prepend the virtualenv folder to docker's PATH

A: This is a place where using a Python virtual environment inside Docker can be useful.  Copying a virtual environment normally is tricky since it needs to be the exact same filesystem path on the exact same Python build, but in Docker you can guarantee that.
(This is the same basic recipe @mpoisot describes in their answer and it appears in other SO answers as well.)
Say you're installing the psycopg PostgreSQL client library.  The extended form of this requires the Python C development library plus the PostgreSQL C client library headers; but to run it you only need the PostgreSQL C runtime library.  So here you can use a multi-stage build: the first stage installs the virtual environment using the full C toolchain, and the final stage copies the built virtual environment but only includes the minimum required libraries.
A typical Dockerfile could look like:
# Name the single Python image we're using everywhere.
ARG python=python:3.10-slim

# Build stage:
FROM ${python} AS build

# Install a full C toolchain and C build-time dependencies for
# everything we're going to need.
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      build-essential \
      libpq-dev

# Create the virtual environment.
RUN python3 -m venv /venv
ENV PATH=/venv/bin:$PATH

# Install the Python library dependencies, including those with
# C extensions.  They'll get installed into the virtual environment.
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

# Final stage:
FROM ${python}

# Install the runtime-only C library dependencies we need.
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      libpq5

# Copy the virtual environment from the first stage.
COPY --from=build /venv /venv
ENV PATH=/venv/bin:$PATH

# Copy the application in.
COPY . .
CMD ["./main.py"]

If your application uses a Python entry point script then you can do everything in the first stage: RUN pip install . will copy the application into the virtual environment and create a wrapper script in /venv/bin for you.  In the final stage you don't need to COPY the application again.  Set the CMD to run the wrapper script out of the virtual environment, which is already at the front of the $PATH.
Again, note that this approach only works because it is the same Python base image in both stages, and because the virtual environment is on the exact same path.  If it is a different Python or a different container path the transplanted virtual environment may not work correctly.

A: The docs on this explain exactly how to do this.
https://docs.docker.com/engine/userguide/eng-image/multistage-build/#before-multi-stage-builds
Basically you do exactly what you've said. The magic of multistage build feature though is that you can do this all from one dockerfile.
ie:
FROM golang:1.7.3
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=0 /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]

This builds a go binary, then the next image runs the binary. The first image has all the build tools and the seccond is just a base linux machine that can run a binary.


text:
Q: display URL from mysql database in iframe PHP? I need to display the URL for an iframe in a php file from mysql database.
the URL's get stored in mysql database in a table called videourl and a column called videourl.
i can get the URL from the mysql database and echo it on a php page but i cannot use it as n iframe scr !
here is what I have done so far:
<?php

echo  "";

?>

but this doesn't work for some reason. and by it doesn't work I mean it doesn't show anything on the PHP page!
what is the best way of doing this ?
Thanks
EDIT: This is my News code and still doesn't work:
<?php
$con=mysqli_connect("localhost","db_username","password","db_name");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM videourl");

while($row = mysqli_fetch_array($result))
  {
  echo "" . $row['videourl'] . "	";
  }

  echo "";

?>

Final EDIT:
okay I've done it.
here is how you should do it if anyone is interested:
while($row = mysqli_fetch_array($result))
  {
  $id = $row["id"];
  $videourl = $row["videourl"];
  $date_added = $row["date_added"];
  }
echo  "";

A: What you did wrong is that you forgot to set the value of $videourl.
You fetched a rsult row in $row. After that you have to assign $row["videourl"] to $videourl, otherwise $videourl will be null and your iframe src will be empty.

A: What's up with the curly braces? Try this instead.
echo  "";


text:
Q: How to display a view only once on application first run? I want to develop an application that shows an authentication screen one time after installing it, and then other screens on subsequent runs. Is there a way to do it?

A: Use SharedPreference to store a firstboot value, and check in the activity against that value. If the value is set, then the application has been launched before. Otherwise, you will display the activity and setthe firstrun flag in the SharedPreference.
For example, your your launched activity might look something like this,
public void onCreate(){
    boolean firstboot = getSharedPreference("BOOT_PREF", MODE_PRIVATE).getBoolean("firstboot", true);

    if (firstboot){
        // 1) Launch the authentication activity

        // 2) Then save the state
        getSharedPreference("BOOT_PREF", MODE_PRIVATE)
            .edit()
            .putBoolean("firstboot", false)
            .commit();
    }
}

A: You can use Shared Preferences to do this. A boolean variable like as isFirstTime can see your work.

A: Using SharedPreference you can do that
boolean flagmosque ;
public static void saveflagmosque(){
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean("mosque", false);
        editor.commit();
    }
    public boolean getflagmosque(){
        flagmosque = sharedPref.getBoolean("mosque", true);
        return flagmosque;
    }

In code
flagmosque = true ;
if(getflagmosque()){
your task that run only one time ;
}


text:
Q: Split only text on special characters, but not on numbers with decimal points I'm thinking about a special regexp problem in PHP, but I can't find an solution.
I try to split some text into terms to get simple words, numbers and web addresses.
So i decided to split on every non alphanumeric character ( \w ).
To work with different languages, I use \w with additional letters, like Ää éèÈ and so on.
Example:
20,000 15.20 This is at Text. Right?!
www.google.com Jean Béraud

Until now, i use the following regexp to split the text:
[^\w(äÄüÜöÖßèé)]

http://regexr.com?2uq98
Which works well in 80% of cases, but splits 20,000 into 20 and 000 also www.google.com into www google com
So i tried to hold the numbers together, but still split on points, like Text. to get Text
To match 15.20, the following works: (\d+\.\d+), but how do I combine the negation with the other regexp string? The following will not work: (\d+\.\d+)|[^\w(äÄüÜöÖßèé)]?
And: how do I handle the web address?

A: Something like this?
$result = preg_split('/\W*\s+/', $string, NULL, PREG_SPLIT_NO_EMPTY);

Demo, Result:
array(10) {
  [0]=>
  string(6) "20,000"
  [1]=>
  string(5) "15.20"
  [2]=>
  string(4) "This"
  [3]=>
  string(2) "is"
  [4]=>
  string(2) "at"
  [5]=>
  string(4) "Text"
  [6]=>
  string(5) "Right"
  [7]=>
  string(14) "www.google.com"
  [8]=>
  string(4) "Jean"
  [9]=>
  string(7) "Béraud"
}

Q: Why does \w matches é in my example?
A: That's based on the local of the system the PCRE library is used on, from the PHP Manual:

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

Alternatively it might be helpful to specify the regex as working with UTF-8:
$result = preg_split('/\W*\s+/u', $string, NULL, PREG_SPLIT_NO_EMPTY);

Ensure $string is UTF-8 encoded. As UTF-8 is international, specific locale settings might not needed to be taken into account. Give it a try.

A: Based upon the answer from @hakre and your example, I believe you should combine the two expressions in this way:
$result = preg_split('/[^\wäÄüÜöÖßèé]*\s+[^\wäÄüÜöÖßèé]*/', $string, NULL, PREG_SPLIT_NO_EMPTY);

Your original expression successfully matched the appropriate characters (the [^\w(äÄüÜöÖßèé)] part).
The expression from @hakre added that there could be ANY NUMBER of these characters (even none of the characters) and should also be followed by one or more instances of whitespace (the \s+ part).
When you combine the two ideas, you get [^\wäÄüÜöÖßèé]*\s+[^\wäÄüÜöÖßèé]*, which basically translates to

any number of characters that are not in this character class, followed by at least one whitespace character, then possibly followed by any number of characters that are not in this character class

or

one or more whitespace characters, and any number of characters that are not in this character class, either before or after

As a test, I used this text sample (I assume you want to match French characters):
20,000 15.20 This is at Text. Right?!
www.google.com Comme son élève, où dois-je aller voir Jean Béraud?

and this regular expression:
EDITED
/[^\wßàâäèéêëîïôöœùûüÿç]*(^|$|\s+)[^\wßàâäèéêëîïôöœùûüÿç]*/i

through the same site that @hakre used:
http://codepad.viper-7.com/MqztVt
END EDIT
This test showed that the expression will split even if the word begins or ends with one of the special characters. I added the /i switch at the end of the expression to make the match case-insensitive.


text:
Q: Calculate Highest value of Serialized and non-Serialized values I am trying to find the highest value of a mix of serialized and non-serialized values via Google Sheets.  Ideally, I'd prefer a single-cell formula but multiple cells is fine.
NormalValue1 = 10
Serialied1   = 30
NormalValue2 = 60
Serialized1  = 10
Serialized2  = 5
Serialized2  = 5

The expected results would be:
Serialized1 = 40 (30+10)
Serialized2 = 10 (5+5)

NormalValue Highest = 60
Serialized  Highest = 40 (Serialized1 at 30+10)
Final result:       = 60

Here's an example of what I'd ultimately like to have.
Example table from Google Sheets

A: Supposing that your labels and numbers are in A11:B19, this should produce the final max:
=ArrayFormula(MAX(SUMIF(A11:A19,A11:A19,B11:B19)))
Essentially, this sums by same label and then returns the max among all label totals.
This would do the same thing:
=MAX(QUERY({A11:B19},"Select SUM(Col2) GROUP BY Col1"))


text:
Q: Сравнение двух списков Здравствуйте, есть два списка с доменами, первый содержит 1000 элементов, второй - 20000; суть вопроса такова: нужно определить, содержит ли второй список конкретный элемент первого списка или нет. И так нужно пробежаться по всей коллекции из 1000 элементов.
Просто пробегаться циклами - не вариант, сделать LINQ запрос?

A: Зависит от того, что ты преследуешь.
Производительность
Если ожидаешь, что LINQ тебе даст тебе повысит производительность, то это ерунда.
LINQ трансформируется в foreach производительность будет ничуть не больше.
Если домены это строки, то лучше воспользоваться HashSet<T> и вычитанием одного множества из другого, производительность должна быть выше нежели у обычных списков.
Лаконичность
С этой целью LINQ справляется.


text:
Q: oracle procedure create and run ora-00900 error l made oracle procedure in dbeaver like this
CREATE OR REPLACE PROCEDURE p_test
IS
    I_MESSAGE VARCHAR2(100) := 'test';
BEGIN
    dbms_output.put_line(I_MESSAGE);
END;

then l run exec p_test;
procedure was not working with ORA-00900 error
l don't understand why not working..

A: exec p_test is an sql*plus command.
If you are using an IDE you should try:
BEGIN
    p_test;
END;

A: Using
BEGIN
    p_test;
END;

It's work.
EXEC is SQL*Plus command, it is no a part of PL/SQL.


text:
Q: Unable to save m2m relation modelform I'm struck on saving m2m relation.
models.py
class BasicTag(models.Model):
    name = models.CharField(max_length=150, verbose_name="Tag Name")
    image_class = models.CharField(max_length=30, blank=True)
    color = models.CharField(max_length=10, blank=True)

    def __unicode__(self):
        return self.name

class ExtendedTag(models.Model):
    parent = models.ManyToManyField(BasicTag, blank=True,
                                    related_name="parent")
    category = models.ManyToManyField(BasicTag, blank=True,
                                      related_name="category")

    def __unicode__(self):
        return self._id

class CombineTag(BasicTag, ExtendedTag):
    """

    """

forms.py
class CombineTagForm(forms.ModelForm):
    class Meta:
        model = CombineTag

Now when I initialize form as
>form = CombineTagForm({"name":"shyam"})#this don't have any parent i.e. root tag
>form.is_valid()
True
>instance = form.save(commit = False)
>instance.save()
>form.save() #return errors
#error
ProgrammingError: column tag_extendedtag_parent.basictag_id does not exist
LINE 1: DELETE FROM "tag_extendedtag_parent" WHERE "tag_extendedtag_...
>form.save_m2m() #return errors ... struck here

So How should I need to save m2m field modelform. I had follow official doc which say that

If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn't possible to save many-to-many data for an instance until the instance exists in the database.

But I couldn't able to figure out what I am missing here.


text:
Q: Why isn't isnumber search not working correctly with given data? I am trying to get Excel to search for a series of keywords in title using the ISNUMBER() search function, but it's bringing back all FALSE, which is wrong. Any help would be greatly appreciated:
I made sure I F4'd the item list -- still wrong
=ISNUMBER(SEARCH(R2,$G$2:$G$22))

A: Use MATCH:
=ISNUMBER(MATCH("*"&R2&"*",$G$2:$G$22,0))

With the Search set up the way you have it, it will only return the value of the first in the list.  You can wrap SUMPRODUCT around the formula:
=SUMPRODUCT(--ISNUMBER(SEARCH(R2,$G$2:$G$22)))>0

But that is more intensive then the simple MATCH.
This assumes that the Keyword that is being looked-up is in R2 and the range $G$2:$G$22 us the list of titles.
If it is the other way around then the SEARCH is backwards and should be:
=SUMPRODUCT(--ISNUMBER(SEARCH($G$2:$G$22,R2)))>0


text:
Q: How to filter posts modified after specific date in Wordpress API v2 I am trying to fetch(filter) the posts modified after specific date through WordPress REST API 2.0-beta15 & WordPress v4.8.3 and update that with the existing posts in my client app.
Using after and before query params provided by WordPress I can filter posts based on date instead of modified field.
I have tried /wp-json/wp/v2/posts?filter[date_query][0][column]=post_modified_gmt&filter[date_query][0][after]=1+month+ago using this https://github.com/WP-API/rest-filter as mentioned in this issue, but this date_query filter is also not working now.
I need any option like
http://bankersdaily.in/wp-json/wp/v2/posts?modified_after=2017-10-31T13:32:10&_envelope
http://bankersdaily.in/wp-json/wp/v2/posts?after=2017-10-31T13:32:10&field=modified&_envelope
References:
https://developer.wordpress.org/rest-api/reference/posts/#list-posts
https://codex.wordpress.org/Class_Reference/WP_Query?#Date_Parameters

A: Native Support - WordPress 5.7
As of WordPress 5.7, support has been added for querying by the post modified date rather than the published date. Custom workarounds are no longer required.
Usage:
/wp-json/wp/v2/posts??modified_after=2021-01-01T00:00:00Z

Notes: https://make.wordpress.org/core/2021/02/23/rest-api-changes-in-wordpress-5-7/

A: It looks like it's not supported, skimming through the docs
Here are some workarounds:
1) Custom modified_after rest query parameter
We can add the modified_after rest query parameter for the post post type with:
add_filter( 'rest_post_collection_params', function( $query_params ) {
    $query_params['modified_after'] = [
        'description' => __( 'Limit response to posts published after a given ISO8601 compliant date.' ),
        'type'        => 'string',
        'format'      => 'date-time',
    ];
    return $query_params;
} );

and then modify the rest post query accordingly with:
add_filter( 'rest_post_query', function( $args, $request ) {
    if( isset( $request['modified_after'] ) && ! isset( $request['after'] ) ) {
        $args['date_query'][0]['after'] = $request['modified_after'];
        $args['date_query'][0]['column'] = 'post_modified';
    }
    return $args;
}, 10, 2 );

where we let after take priority over modified_after.
Example:
/wp-json/wp/v2/posts??modified_after=2017-11-07T00:00:00

Notes:
We might have used modified_gmt_after for the post_modified_gmt column.
It might be better to use a more unique name than modified_after to avoid a possible future name collision.
To extend this to other post types, we can use the rest_{$post_type}_collection_params and the rest_{$post_type}_query filters.
Another option is to create a custom endpoint and parameters, that's a more work to do there. It's of course a question if we should add a custom parameter to the current rest api. In some cases it should be ok, as we're not removing or modifying the response, or changing how other parameters work.
2) Custom date_query_column rest query parameter
Another approach would be to introduce a custom date_query_column rest query parameter:
add_filter( 'rest_post_query', function( $args, $request ) {
    if ( ! isset( $request['before'] ) && ! isset( $request['after'] ) )
        return $args;

    if( isset( $request['date_query_column'] ) )
        $args['date_query'][0]['column'] = $request['date_query_column'];

    return $args;
}, 10, 2 );

add_filter( 'rest_post_collection_params', function( $query_params ) {
    $query_params['date_query_column'] = [
            'description' => __( 'The date query column.' ),
            'type'        => 'string',
            'enum'        => [ 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt', 'comment_date', 'comment_date_gmt' ],
        ];
    return $query_params;
} );

that would be available if either after or before parameters are set.
Example:
/wp-json/wp/v2/posts??after=2017-11-07T00:00:00&date_query_column=post_modified

Hope it helps!

A: I have created a WordPress plugin WP REST API – Filter posts date wise using given column, those who need can use this.
Using this plugin we can specify the column(any of date, date_gmt, modified, modified_gmt) as query parameter date_query_column to query against value(s) given in before and/or after query parameters.
Usage
Use the date_query_column parameter on any post endpoint such as /wp/v2/posts or /wp/v2/pages in combination with before and/or after parameter.
/wp-json/wp/v2/posts??after=2017-11-08T13:07:09&date_query_column=modified

Github Repository of the same.


text:
Q: Cluster standard errors for Heckman selection model in R I am trying to obtain clustered standard errors for a Heckman selection model given the output from the "sampleSelection" package (selection command).
For replication, I am using the examples given in the STATA documentation (see Examples 1 & 2 on pages 7 & 9 - http://www.stata.com/manuals13/rheckman.pdf).
In R, I obtain the results from Example 1 as follows:
install.packages("readstata13")
library(readstata13)

install.packages("sampleSelection")
library(sampleSelection)

## Read STATA data
dat <- data.table(read.dta13("http://www.stata-press.com/data/r13/womenwk.dta"))

## Summary statistics
summary(dat[,.(age, education, married, children, wage, county)])

## Define indicator whether wage variable is defined
dat[, lfp := !is.na(wage)]

## STATA command Example 1: heckman wage educ age, select(married children educ age)
heckmanML <- selection(selection = lfp ~ married + children + education + age, outcome = wage ~ education + age, data = dat)

## Results Example 1
summary(heckmanML)

## STATA command Example 2: heckman wage educ age, select(married children educ age) vce(cluster county)
## <<stuck here>>

Any ideas how I can replicate the last command using the vce(cluster) option? I tried to play around with cluster.vcov from the multiwayvcov package but got stuck with the following error:
cluster.vcov(heckmanML, eval(heckmanML$call$data)[,county])
Error in `[<-.data.frame`(`*tmp*`, i, "K", value = numeric(0)) : replacement has length zero

A: I adapted code from Mahmoud Arai. I fiddled with the degrees-of-freedom to match the output from the Stata manual and I replace the variance-covariance matrix stored with the fitted model so that the summary output matches Stata's output (see second set of output below).
library(haven)
library(dplyr, warn.conflicts = FALSE)
library(sampleSelection)
#> Loading required package: maxLik
#> Loading required package: miscTools
#>
#> Please cite the 'maxLik' package as:
#> Henningsen, Arne and Toomet, Ott (2011). maxLik: A package for maximum likelihood estimation in R. Computational Statistics 26(3), 443-458. DOI 10.1007/s00180-010-0217-1.
#>
#> If you have questions, suggestions, or comments regarding the 'maxLik' package, please use a forum or 'tracker' at maxLik's R-Forge site:
#> https://r-forge.r-project.org/projects/maxlik/
library(sandwich)

## Read STATA data
dat <-
  read_stata("http://www.stata-press.com/data/r13/womenwk.dta") %>%
  ## Define indicator whether wage variable is defined
  mutate(lfp = !is.na(wage))

## STATA command Example 1: heckman wage educ age, select(married children educ age)
heckmanML <- selection(selection = lfp ~ married + children + education + age,
                       outcome = wage ~ education + age, data = dat)

## Results Example 1
summary(heckmanML)
#> --------------------------------------------
#> Tobit 2 model (sample selection model)
#> Maximum Likelihood estimation
#> Newton-Raphson maximisation, 3 iterations
#> Return code 8: successive function values within relative tolerance limit (reltol)
#> Log-Likelihood: -5178.304
#> 2000 observations (657 censored and 1343 observed)
#> 10 free parameters (df = 1990)
#> Probit selection equation:
#>              Estimate Std. Error t value Pr(>|t|)
#> (Intercept) -2.491015   0.189340 -13.156  < 2e-16 ***
#> married      0.445171   0.067395   6.605 5.07e-11 ***
#> children     0.438707   0.027783  15.791  < 2e-16 ***
#> education    0.055732   0.010735   5.192 2.30e-07 ***
#> age          0.036510   0.004153   8.790  < 2e-16 ***
#> Outcome equation:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept)  0.48579    1.07704   0.451    0.652
#> education    0.98995    0.05326  18.588   <2e-16 ***
#> age          0.21313    0.02060  10.345   <2e-16 ***
#>    Error terms:
#>       Estimate Std. Error t value Pr(>|t|)
#> sigma  6.00479    0.16572   36.23   <2e-16 ***
#> rho    0.70350    0.05123   13.73   <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> --------------------------------------------

vcovCL <- function(fm, cluster) {

  M <- length(unique(cluster))
  N <- length(cluster)
  dfc <- M/(M-1)

  u  <- apply(estfun(fm),2, function(x) tapply(x, cluster, sum))
  dfc * sandwich(fm, meat=crossprod(u)/N)
}

heckmanML[["vcovAll"]] <- vcovCL(heckmanML, dat$county)
summary(heckmanML)
#> --------------------------------------------
#> Tobit 2 model (sample selection model)
#> Maximum Likelihood estimation
#> Newton-Raphson maximisation, 3 iterations
#> Return code 8: successive function values within relative tolerance limit (reltol)
#> Log-Likelihood: -5178.304
#> 2000 observations (657 censored and 1343 observed)
#> 10 free parameters (df = 1990)
#> Probit selection equation:
#>              Estimate Std. Error t value Pr(>|t|)
#> (Intercept) -2.491015   0.115330 -21.599  < 2e-16 ***
#> married      0.445171   0.073147   6.086 1.39e-09 ***
#> children     0.438707   0.031239  14.044  < 2e-16 ***
#> education    0.055732   0.011004   5.065 4.47e-07 ***
#> age          0.036510   0.004038   9.042  < 2e-16 ***
#> Outcome equation:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept)  0.48579    1.30210   0.373    0.709
#> education    0.98995    0.06001  16.498   <2e-16 ***
#> age          0.21313    0.02099  10.151   <2e-16 ***
#>    Error terms:
#>       Estimate Std. Error t value Pr(>|t|)
#> sigma  6.00479    0.15520  38.691   <2e-16 ***
#> rho    0.70350    0.07088   9.925   <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> --------------------------------------------

Created on 2021-05-08 by the reprex package (v2.0.0)


text:
Q: Finding center and radius of circumcircle
Find the center and radius of the circle which circumscribes the triangle with (complex) vertices $a_1,a_2,a_3$. Express the result in symmetric form.

I'm not sure where to start in this question. The circumcenter is the intersection of the perpendicular bisectors, but I don't know how to calculate the line equation of the perpendicular bisectors yet. As for the radius, after we find the circumcenter $c$ we can calculate it using $|c-a_1|$ (or $|c-a_2|$ or $|c-a_3|$; all three should be equal.) So how can I calculate the circumcenter?

A: Let $R$ be the radius of the circumcircle of $a_1,a_2,a_3$ then the circumcenter $z$ is defined by the condition $|z-a_1|=|z-a_2|=|z-a_3|=R\,$. Expanding $R^2=|z-a_1|^2=(z-a_1)(\bar z - \overline{a_1})$ and similar for $a_2,a_3$ gives the system:
$$
\begin{cases}
\begin{align}
\overline{a_1}\,z + a_1\,\bar z + (R^2 - |z|^2) & = |a_1|^2  \\
\overline{a_2}\,z + a_2\,\bar z + (R^2 - |z|^2) & = |a_2|^2  \\
\overline{a_3}\,z + a_3\,\bar z + (R^2 - |z|^2) & = |a_3|^2
\end{align}
\end{cases}
$$
Eliminating $\bar z$ and $(R^2 - |z|^2)$ between the equations amounts to solving it as a linear system in $z$,$\bar z$ and $(R^2-|z|^2)$ which, by Cramer's rule, gives:
$$
z\;=\;\frac{\left|
        \begin{array}{ccc}
          |a_1|^2 & a_1 & -1 \\
          |a_2|^2 & a_2 & -1 \\
          |a_3|^2 & a_3 & -1
        \end{array}
      \right|}
     {\left|
        \begin{array}{ccc}
          \overline{a_1} & a_1 & -1 \\
          \overline{a_2} & a_2 & -1 \\
          \overline{a_3} & a_3 & -1
        \end{array}
      \right|}
\;=\;\frac{\left|
        \begin{array}{ccc}
          a_1 & |a_1|^2 & 1 \\
          a_2 & |a_2|^2 & 1 \\
          a_3 & |a_3|^2 & 1
        \end{array}
      \right|}
     {\left|
        \begin{array}{ccc}
          a_1 & \overline{a_1} & 1 \\
          a_2 & \overline{a_2} & 1 \\
          a_3 & \overline{a_3} & 1
        \end{array}
      \right|}
$$
(The formula itself has been posted in another answer here. The above is a derivation thereof.)

A: Here is a way of getting started. It might not be the best way, but it makes significant progress. Let $c$ be the centre of the circle and $r$ (a real number) the radius. You can write an equation for the square of the radius as $$(a_1-c)(\bar{a}_1-\bar c)=r^2=|a_1|^2+|c|^2-c\bar a_1-a_1\bar c$$
[note this is just the cosine rule for triangles in different notation]
You can write two other equations like this, and use them to eliminate $r^2$, $|c|^2$ (which appear together) and $\bar c$ so that you have a linear equation for $c$ in terms of things you know.