text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
How does the | affect a BNF grammar?
I'm working on a school project that requires me to parse a BNF grammar. I'm a little confused as to what role the pipe character (|) - which I believe means "or" - plays in a rule.
For example, if I had the following:
<a> ::= b c d | e f g
Which of the terminals is the | applied to? Using parentheses for grouping, which would describe how the "or" is applied?
(b c d) | (e f g)
(b c) (d) | (e) (f g)
Is the | applied to the entire set of terminals, or just the two next to the |?
And what if I had a set up like:
<a> ::= b | <c> <d>
<b> ::= e | f
<c> ::= g | h
Would it still be true if <c> and <d> refer to non-terminals? To what would the | be applied in this case?
A:
In general,
rule := a b c | d e f
is grouped as
rule := (a b c) | (d e f)
This doesn't change whether or not you apply them to terminals or non-terminals.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving a messy inequality
EDIT:
After much work I was able to reduce the inequality to a single variable function which I need to show is non-positive. That function is (for $0\leq p\leq\frac{1}{2}$)
$$\frac{p^2(\log(p))^2 - (1-p)^2(\log(1-p))^2}{1-2p} + \log(p)\log(1-p) + p\log(p)+(1-p)\log(1-p) \leq 0$$
This looks tractable, but is quite hard to prove since neither the function nor any of its derivatives are convex/concave/monotonic. Its graph looks like
.
Any inputs welcome!
END EDIT
I'm trying to prove this messy inequality I got while working on an information theoretic problem (more details below).
Let $0 \leq p,q \leq \frac{1}{2}$.
Let $H(x) = -x\log(x) - (1-x)\log(1-x)$ be the binary entropy function.
Let $p\star q = p(1-q) +q(1-p)$ (think of this as addition of two Bernoulli random variables in $\mathbb{Z}_2$)
The inequality is:
$$-\frac{(1-2q)}{(p \star q) (1- p \star q)\log\left(\frac{1-p}{p}\right)} + \frac{\log\left(\frac{1- p \star q}{p \star q}\right)}{p(1-p)\left(\log\left(\frac{1-p}{p}\right)\right)^2} - \frac{H(q)(1-2p)}{H(p)(p \star q) (1- p \star q)\log\left(\frac{1-q}{q}\right)} \leq 0$$
Some Remarks:
If we write this as $-A+B-C \leq 0$ with $A,B,C$ being the corresponding quantities above. I can show that $-A +B \geq 0$, so the $-C$ term subtracts enough to make the expression negative. The plot of $-A+B-C$ as a function of $p,q$ looks like
.
It appears to decrease in $q$ for a fixed $p$, starting at $0$ and going to $-\infty$ as $q$ goes to $\frac{1}{2}$.
Origin:
This inequality came from looking at a function $f(x,y) = H(H^{-1}(x)\star H^{-1}(y))$ where $f: [0,1]\times [0,1] \to [0,1]$. This function occasionally pops up in information theory, like when studying the binary symmetric channel or an inequality called Mrs. Gerber's Lemma. The inequality I have implies that $f(x,y)$ is concave along lines through the origin (i.e $f(x,\theta x)$ is concave in $x$). What I've written is a simplified version $f''$ along a line through the origin.
I'm at a complete loss as to how to attack this. All the plots I have show this is true, but a plot is not a proof. Any suggestions welcome!
A:
I think I managed to prove the entire inequality analytically. The whole proof is a bit long to post here (about 7 pages) and involves ugly looking expressions. I'll outline the general strategy I used:
Start with the original inequality
$$-\frac{(1-2q)}{(p \star q) (1- p \star q)\log\left(\frac{1-p}{p}\right)} + \frac{\log\left(\frac{1- p \star q}{p \star q}\right)}{p(1-p)\left(\log\left(\frac{1-p}{p}\right)\right)^2} - \frac{H(q)(1-2p)}{H(p)(p \star q) (1- p \star q)\log\left(\frac{1-q}{q}\right)} \leq 0$$
and throw all the $p\star q$ terms on one side to get
$$(p \star q)(1- p\star q)\log\left(\frac{1-p \star q}{p \star q}\right) \leq(1-2q)p(1-p)\log\left(\frac{1-p}{p}\right) + \frac{p(1-p)(1-2p)\left(\log\left(\frac{1-p}{p}\right)\right)^2 H(q)}{H(p)\log\left(\frac{1-q}{q}\right)}$$
Now keep $p \star q$ fixed $ = k$ say, and try minimise the right hand side. Notice that when $p = k, q = 0$ we have equality. This might lead us to hope that the right hand side is a decreasing function of $p$, and when $p$ becomes $k$ we have equality.
Now consider the partial derivative of the RHS in $p$, and try to show that this is negative. By some stroke of luck, it turns out that if we look at $\frac{\partial RHS}{\partial p}$ for a fixed $p$ and vary $k$, the value of $k$ which maximises $\frac{\partial RHS}{\partial p}$ is $k = p$. So its sufficient to prove $\frac{\partial RHS}{\partial p}|_{(p,p)} \leq 0$
$\frac{\partial RHS}{\partial p}|_{(p,p)}$ when evaluated gives me the second inequality (the one I added in the EDIT). Thus it suffices to show
$$p^2(\log(p))^2 - (1-p)^2(\log(1-p))^2 + (1-2p)\left(\log(p)\log(1-p) + p\log(p)+(1-p)\log(1-p)\right) \leq 0$$
Let me call the above expression $F(p)$. I showed that if $F(p) > 0$ somewhere, then $F'''(p)$ would have atleast $2$ zeros in $[0,0.5]$. (This is easy to show.) Explicitly computing $F'''(p)$ shows that it is $-\infty$ at $0$ and strictly positive at $0.5$. So, if we happened to show that $F'''$ is concave, it would have exactly one zero, and thus contradict the result that it should have $2$, and thus prove the result.
Now I do something truly horrible. I explicitly compute the 5-th derivative and show that it is negative, thus $F'''$ is indeed concave.
The inequality $F'''''(p) \leq 0$ can be somewhat simplified to get
$$P_1(p)\log(p) + P_2(p)\log(1-p) + P_3(p) \leq 0$$
where $P_1, P_2,P_3$ are some $7$-th degree polynomials.
I now use Sturm's theorem to show that over the range $[0,0.5]$ $P_1,P_2 \geq 0$. This, too, was quite horrible.
Now I use a polynomial approximation to $\log$, and use the positivity of $P_1,P_2$ to conclude
$$P_1(p)\log(p) + P_2(p)\log(1-p) + P_3(p)\leq P_1(p)\left( -(1-p) - \frac{(1-p)^2}{2}\right) + P_2(p)\left(-p - \frac{p^2}{2}\right) + P_3(p)$$
By another stroke of luck, the RHS here factorises to give $$ -24(1-p)^2 (p-0.5)^2 p^2 (p^2-p+\frac{7}{3})
$$
which is clearly seen to be negative, and thus by step $9$ I can now say that $F'''''$ is negative, and $F'''$ is concave, and it has only one root in $[0,0.5]$ and thus $F$ has to be non-positive everywhere in $[0,0.5]$.
In retrospect, I guess using numerical techniques (as advised in the comments section) would have been more prudent.
| {
"pile_set_name": "StackExchange"
} |
Q:
Speed up dividing date intervals by minutes in Sql Server
I need to divide some date intervals by minutes. (For example, 2012-01-01 10:00 - 2012-01-01 10:00 interval should be divided into 2012-01-01 10:01, 2012-01-01 10:02, ... 2012-01-01 10:10).
For example, there is a table
CREATE TABLE [dbo].[Events](
[ID] [int] IDENTITY(1,1) NOT NULL,
[EventStart] [datetime] NOT NULL,
[EventEnd] [datetime] NOT NULL,
[Amount] [float] NOT NULL,
CONSTRAINT [PK_Events] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
This table is filled like
DECLARE @i integer = 0;
DECLARE @initial_date datetime = '2012-01-01';
WHILE @i < 50000
BEGIN
INSERT INTO [Events] (EventStart, EventEnd, Amount) VALUES (DATEADD(MINUTE, 10*@i, @initial_date), DATEADD(MINUTE, 10*(@i + 1), @initial_date), @i);
SET @i = @i + 1;
END
As a result we have many 10 minutes intervals.
To divide it by minutes I use the following recursive CTE:
DECLARE @start_date datetime = '2012-01-01';
DECLARE @end_date datetime = '2013-01-02';
WITH Date_Ranges (StatDate, Amount, IntervalStart, CurrentMinute) AS (
SELECT
DATEADD(MINUTE, 0, ev.EventStart) AS StatDate, ev.Amount, ev.EventStart AS IntervalStart, 1 AS CurrentMinute
FROM [Events] ev
WHERE ev.EventStart BETWEEN @start_date AND @end_date
UNION ALL
SELECT
DATEADD(MINUTE, CurrentMinute, ev.EventStart), ev.Amount, ev.EventStart AS IntervalStart, CurrentMinute + 1
FROM [Events] ev
INNER JOIN Date_Ranges ranges ON (ranges.IntervalStart = ev.EventStart AND
ranges.StatDate >= ev.EventStart AND
ranges.StatDate < ev.EventEnd)
WHERE DATEADD(MINUTE, CurrentMinute, ev.EventStart) BETWEEN @start_date AND @end_date AND
ev.EventStart BETWEEN @start_date AND @end_date
)
SELECT *
FROM Date_Ranges --ORDER BY StatDate
The main problem is too slow execution of this recursive CTE on a large data amount.
So, how can I speed up this?
A:
This returns all 550,000 rows in roughly 1/2 the time of the recursive CTE.
DECLARE @start_date datetime = '2012-01-01';
DECLARE @end_date datetime = '2013-01-02';
SELECT DATEADD(MINUTE, x.number, ev.EventStart) AS StartDate,
ev.Amount,
ev.EventStart as IntervalStart,
x.number as CurrentMinute
FROM master.dbo.spt_values x
CROSS JOIN Events ev
WHERE x.type = 'P'
AND x.number <= DATEDIFF(MINUTE, ev.EventStart, ev.EventEnd)
AND ev.EventStart BETWEEN @start_date and @end_date
| {
"pile_set_name": "StackExchange"
} |
Q:
How to populate rows of a DE in email body
I am trying to populate DE row's in email body .
Ex , First Name , Last name and Email address from a DE to the email content .
I would like to have it populated through a script as with standard functionality I am not able to achieve it.
Thanks
A:
If you mean from the sendable, you can utilize personalization strings. This includes any fields you use when sending from a data extension.
Say your sendable DE looks like this:
SubscriberKey | EmailAddress | FirstName | LastName
You would use the following personalization strings:
%%SubscriberKey%% | %%EmailAddress%% | %%FirstName%% | %%LastName%%
But, I would recommend instead utilizing AttributeValue() to collect these. (e.g. SET @email = AttributeValue('EmailAddress') for inside AMPscript block or %%=AttributeValue('EmailAddress')=%% for inline use.
If you want to use relational data stored in a separate data extension from the sendable, this would be best achieved through a lookuprows or lookuporderedrows.
As it is generally the more utilized language in emails, I am going to show an example in AMPscript:
%%[
set @SubscriberKey = AttributeValue('SubscriberKey')
set @rowset = LookupRows('myLookupDE','SubscriberKey',@SubscriberKey)
set @row = Row(@rowset,1)
set @Email = Field(@row,"EmailAddress")
set @FirstName = Field(@row,"FirstName")
set @LastName = Field(@row,"LastName")
]%%
which is then output like this:
Hello %%=v(@FirstName)=%% %%=v(@LastName)=%%, your Email Address is %%=v(@Email)=%%!
| {
"pile_set_name": "StackExchange"
} |
Q:
Question about unusual highest weight modules for $U_q(sl(2))$
Background
Let $U_q(sl(2))$ be the quantum group associated with $sl(2)$ i.e. the associative algebra with 1 over $Q(q)$ generated by $x^+,x^-,K,K^{-1}$ with relations
$$KK^{-1}=K^{-1}K=1$$
$$Kx^+K^{-1}=q^2x^+,Kx^-K^{-1}=q^{-2}x^-$$
$$x^+x^{-}-x^{-}x^+=\frac{K-K^{-1}}{q-q^{-1}}$$
Here $q$ is indefinite, in particular not a root of unity. A $U_q(sl(2))$-module $V$ has highest weight $\omega \in Q(q)$ if there exists a vector $v \in V$ such that
$$ U_q(sl(2))\cdot v=V $$
$$ x^+\cdot v=0 $$
$$ K\cdot v=\omega v$$
Most standard texts (e.g. Chari Pressley, etc.) focus mainly on the case where $\omega$ equals $q$ to some power (i.e. $K$ acts as $q^m$ for some integer $m$ or $-q^m$ though this case is equivalent to the first by tensoring with a 1-dimensional module). If $\omega$ is not of this form then the module in question is necessarily infinite dimensional.
Question
Has anyone considered what happens when $K$ acts by something other than a power of $q$, say $2q-1$? I am especially interested in what happens in the $q=1$ specialization of these modules. Any references would be appreciated.
A:
When talking about modules for such a quantized enveloping algebra, you have to be explicit about whether the module is finite dimensional or not. (For affine or other infinite dimensional Lie algebras of interest, the parallel question is whether modules are integrable or not.) In Jantzen's introductory AMS text Lectures on Quantum Groups, for instance, he starts out with analogues of the traditional finite dimensional representations. Here the associated highest weights are (up to sign) given by powers of $q$ in the rank one case. The infinite dimensional modules with dominant integral highest weights then have reasonable properties as well.
It's possible in this special case to look at infinite dimensional modules with arbitrary highest weights, including simple modules, but typically these are far less understood. There is a lot of literature by now on quantum groups, but I'll mention one earlier paper by Lusztig: Quantum deformations of certain simple modules over enveloping algebras, Adv. in Math. 70 (1988). In Section 2 he defines very general highest weight modules, but then specializes to the integrable ones where more can be said.
I'm not at all sure where the general case leads. Keep in mind that even in the classical situation, infinite dimensional simple modules with arbitrary highest weights pose difficult problems.
| {
"pile_set_name": "StackExchange"
} |
Q:
With SQL Server XML data type, how to update the value attribute when searching with another attribute to locate the xml node?
I have a XML column in my table that stores a XML structure like this:
<cars>
<car name="Ford" value="123" />
<car name="Honda" value="456" />
</cars>
I want to modify all rows that have name="Honda" and value="456". I need to update the number 456 to 789.
I tried this:
UPDATE cars
SET XmlData.modify('replace value of (/cars/car[@name="Honda"]/value) with "789"')
WHERE isProcessed = 0
I am getting the error:
Msg 2261, Level 16, State 1, Line 41
XQuery Cars.XmlData.modify()]: There is no element named 'value' in the type 'element(car,#anonymous) *'.
A:
You were so close... Just missed .../@value)[1]
Example
Declare @Cars table (ID int,IsProcessed bit,XMLData xml)
Insert Into @Cars values
(1,0,'<cars><car name="Ford" value="123" /><car name="Honda" value="456" /></cars>')
Update @Cars
Set XMLData.modify('replace value of (/cars/car[@name="Honda"]/@value)[1] with "789"')
WHERE isProcessed = 0
Select * from @Cars
The Updated XML
<cars>
<car name="Ford" value="123" />
<car name="Honda" value="789" />
</cars>
| {
"pile_set_name": "StackExchange"
} |
Q:
Geodesic flow are generated by Hamiltonian vector field
Let $(M,g)$ be a Riemannian manifold and consider the Hamiltonian
\begin{equation*}
\begin{array}{rcl}
H:T^*M & \rightarrow&\mathbb{R} \\
(q,p) & \mapsto&H(q,p):=\frac{1}{2}g^{ij}(q)p_ip_j.
\end{array}
\end{equation*}
We would like to show that the Hamiltonian vector field $X_H:T^*M\rightarrow TT^*M$ generates the geodesic flow.
We can explicitely compute $X_H$, since its components satisfies Hamilton's equations:
\begin{equation*}
X_H=\dfrac{\partial H}{\partial p_j}\dfrac{\partial}{\partial q^j}-\dfrac{\partial H}{\partial q^j}\dfrac{\partial}{\partial p_k}=g^{ij}p_i\dfrac{\partial}{\partial q^j}-\frac{1}{2}\dfrac{\partial g^{ij}}{\partial q^k}p_ip_j\dfrac{\partial}{\partial p_k}.
\end{equation*}
We can see that the following vector field $Y:TM\rightarrow TTM$, over $TM$ generates the geodesic flow:
\begin{equation*}
Y(q,\dot{q}):=\dot{q}^i\dfrac{\partial}{\partial q^i}-\Gamma^j_{lk}\dot{q}^l\dot{q}^k\dfrac{\partial}{\partial\dot{q}^j}.
\end{equation*}
Indeed, we show that its integral curves are geodesics.
Let $\gamma:\mathcal{I}\rightarrow TM$, with $\gamma(t):=(\alpha(t),\beta(t))$, then
\begin{equation*}
\dot{\gamma}(t)=\dot{\alpha}^i(t)\dfrac{\partial}{\partial q^i}+\dot{\beta}^j(t)\dfrac{\partial}{\partial\dot{q}^j},
\end{equation*}
so $Y(\gamma(t))=\dot{\gamma}(t)$ $\iff$ the following hold
\begin{equation*}
\left\{\begin{array}{ll}
\dot{\alpha}^i(t)=\beta^i(t)& \\
\dot{\beta}^j(t)=-\Gamma^j_{lk}\beta^l(t)\beta^k(t)&
\end{array}\right.
\end{equation*}
This is the geodesic equation and so this proves that the integral curves of $Y$ are geodesics.
The problem is that $Y$ is a vector field over $TM$, while in the Hamiltonian formalism, $X_H$ is a vector field over $T^*M$. How are $X_H$ and $Y$ related? How can we show that $X_H$ generates the geodesic flow as $Y$ does?
Thank you all.
P.S. It is enough to show that the integral curves of $X_H$ satisfies the geodesic equation in the cotangent bundle? But then, what does it look like in the cotangent bundle?
A:
Throughout I'll use $x=x^1,\dots,x^n$ as local coordinates on $M$, $(x,v)$ as the induced local coordinates on $TM$, and $(x,p)$ as the induced local coordinates on $T^*M$ (with lower indices for $p_i$ and all others upper).
Your question is essentially asking about the correspondence between the Hamiltonian and Lagrangian formulations of the geodesic equations. For a general second order ODE, the correspondence is as follows: Given a Lagrangian $L:TM\to\mathbb{R}$, there is associated to $L$ a Legendre transformation $F_L:TM\to T^*M$ given by
$$
F_L(x,v)=\left(x,\frac{\partial L}{\partial v}\right)
$$
Provided $F_L$ is an isomorphism, we can write rewrite the entire problem on the cotangent bundle in terms of a Hamiltonian $H(x,p)=p_idx^i(F_L^{-1}(x,p))-L(F_L^{-1}(x,p))$.
After the rewriting, the Euler-Lagrange equations corresponds to Hamilton's equations. Writing both in terms of vector fields, the Euler-Lagrange vector field $X_L$ is $F_L$-related to the Hamiltonian vector field $X_H$, i.e. $X_H=dF_LX_L$.
In the case of the geodesic equation, the Lagrangian is $L(x,v)=\frac{1}{2}g_{ij}(x)v^iv^j$, so the Legendre transformation $F_L$ is just the musical isomorphism $\flat:TM\to T^*M$, given in coordinates by $\flat(x,v)=(x,g_{ij}(x)v^j)$. Its inverse is given by $\sharp(x,p)=(x,g^{ij}(x)p_j)$, and its differential is
$$
d\flat\left(\frac{\partial}{\partial x^i}\right)=\frac{\partial}{\partial x^i}+\frac{\partial g_{jk}}{\partial x^i}v^k\frac{\partial}{\partial p_j}\ \ \ \ \ \ \ d\flat\left(\frac{\partial}{\partial v^i}\right)=g_{ij}\frac{\partial}{\partial p_j}
$$
You've already written down the two vector fields in coordinates, so verifying that $d\flat X_L=X_H$ is just a computation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Studio add-in : Context menu split
I built a Visual Studio add-in and I have a context menu that shows in the code window. I have about 6 options and I want to break them up using lines. I can't seem to figure out how to insert a splitter line. I've tried a few different things but get exceptions.
Any ideas?
A:
I found it. CommandBarPopup.BeginGroup = true
| {
"pile_set_name": "StackExchange"
} |
Q:
Where was this flag flown?
I have a 48 Star flag that I have recently acquired from a seller off of a similar setting to Craigslist. He said he’s found it in an attic and really has no other information on it. Because the size is near 4 ft x 9ft, and it is truly tattered, I believe it had been flown somewhere other than in front of an average home. I have come to believe it could have flown on a ship from the mounting holes (as shown in the picture), they are very thick and sturdy galvanized eyelets to keep the metal from rusting. These eyelets are very different than those of a “normal flags” folded-over fabric with a grommet in it. Is it possible this flag could’ve been flown on an American ship? Or is it just an oversized home flag? In closing THIS FLAG IS MASSIVE!
A:
48 Star Flags were flown from July 4th 1912 when New Mexico(1911) and Arizona were added to the Union until July 4th 1960 when Alaska(1959) and Hawaii became states. By law the flag changes on the subsequent 4th of July following a state's addition to the Union.
So given the dates that means your flag could have flown during The American invasion of Mexico in 1914, WWI, WWII or Korea. Or of course on somebody's front porch during that time period.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add another string to complete existing strings
I have some data that look like
Category
A
C
E
J
AA
AB
AE
AK
AO
F
L
O
AW
AQ
The correct data should have two letters, such as AA, AB, and AK. However, some entries only have the second alphabet.
The final result would be:
Category
AA
AC
AE
AJ
AA
AB
AE
AK
AO
AF
AL
AO
AW
AQ
I know how we can add a string "A" to all entries in this column. However, is it possible to only add "A" to entries with one letter?
Thanks a lot for the help!
A:
Use Series.str.pad:
df['Category'] = df['Category'].str.pad(2, side='left', fillchar='A')
[out]
Category
0 AA
1 AC
2 AE
3 AJ
4 AA
5 AB
6 AE
7 AK
8 AO
9 AF
10 AL
11 AO
12 AW
13 AQ
A:
Try this:
df['Category'] = df['Category'].apply(lambda x: 'A' + x if len(x) < 2 else x)
| {
"pile_set_name": "StackExchange"
} |
Q:
Resumable Download in Cocoa
What is the best approach to write code for resumable downloads in cocoa? Should I use NSURLConnection, NSURLDownload or is there a better approach?
Regards
A:
Have a look at the ASIHTTPRequest library. Unfortunately the developer does not work on this library any more, but I find it still working reliably. There is a lot of nice stuff in this lib and you can make downloads resumable with one line of code.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS for ribbon end
How do I draw the end of a ribbon like the left side of this image using only CSS?
I know I can use the fact that corners in CSS are mitered, so I can have a div with a border of size 0 and other borders bigger to give me triangles. Is there a way to do this with only 1 div? Or do I need to stack some triangles? I'd really prefer to have 1 div so that users don't have to think about this and I can just use the CSS :before pseudo element to insert this. What's the best way to implement this?
IE9+ and modern versions of other browsers only need to be supported.
A:
HTML
<div class="ribbon">
<strong class="ribbon-content">Everybody loves ribbons</strong>
</div>
CSS
.ribbon {
font-size: 16px !important;
width: 50%;
position: relative;
background: #ba89b6;
color: #fff;
text-align: center;
padding: 1em 2em; /* Adjust to suit */
margin: 2em auto 3em;
}
.ribbon:before {
content: "";
position: absolute;
display: block;
bottom: -1em;
border: 1.5em solid #986794;
z-index: -1;
}
.ribbon:before {
left: -2em;
border-right-width: 1.5em;
border-left-color: transparent;
}
.ribbon .ribbon-content:before {
content: "";
position: absolute;
display: block;
border-style: solid;
border-color: #804f7c transparent transparent transparent;
bottom: -1em;
}
.ribbon .ribbon-content:before {
left: 0;
border-width: 1em 0 0 1em;
}
See Demo
Reference
A:
There are lots off resources on the web showing how to do this. A very good tutorial is online at css-tricks here http://css-tricks.com/snippets/css/ribbon/
Ive also stuck it in a jsfiddle for you here to play with http://jsfiddle.net/WqNQU/
<h1 class="ribbon">
<strong class="ribbon-content">Everybody loves ribbons</strong>
</h1>
.ribbon {
font-size: 16px !important;
/* This ribbon is based on a 16px font side and a 24px vertical rhythm. I've used em's to position each element for scalability. If you want to use a different font size you may have to play with the position of the ribbon elements */
width: 50%;
position: relative;
background: #ba89b6;
color: #fff;
text-align: center;
padding: 1em 2em; /* Adjust to suit */
margin: 2em auto 3em; /* Based on 24px vertical rhythm. 48px bottom margin - normally 24 but the ribbon 'graphics' take up 24px themselves so we double it. */
}
.ribbon:before, .ribbon:after {
content: "";
position: absolute;
display: block;
bottom: -1em;
border: 1.5em solid #986794;
z-index: -1;
}
.ribbon:before {
left: -2em;
border-right-width: 1.5em;
border-left-color: transparent;
}
.ribbon:after {
right: -2em;
border-left-width: 1.5em;
border-right-color: transparent;
}
.ribbon .ribbon-content:before, .ribbon .ribbon-content:after {
content: "";
position: absolute;
display: block;
border-style: solid;
border-color: #804f7c transparent transparent transparent;
bottom: -1em;
}
.ribbon .ribbon-content:before {
left: 0;
border-width: 1em 0 0 1em;
}
.ribbon .ribbon-content:after {
right: 0;
border-width: 1em 1em 0 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ESP8266 Wemos D1 Retrieving Wrong AP Mac Address
Using WiFi.BSSID and WiFi.BSSIDstr gives me some weird mac address.
the code is:
#include "ESP8266WiFi.h"
#include "ESP8266WiFiScan.h"
void setup() {
Serial.begin(115200);
//WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("Setup done");
Serial.println(WiFi.macAddress());
}
void loop() {
int n=WiFi.scanNetworks();
Serial.println(n);
for (int network = 0; network < n; network++){
Serial.println(WiFi.SSID(network));
Serial.println(WiFi.RSSI(network));
uint8_t* mac=WiFi.BSSID(n);
char APmac[13];
APmac[0]=0;
for (int i=0; i<6;i++) {
char buffer[3];
sprintf(buffer, "%02x", mac[i]);
strncpy((char *)(APmac+(i*2)), buffer, 3);
Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
}
Serial.println(APmac);
Serial.println(WiFi.BSSIDstr(n));
}
Serial.println();
Serial.println();
delay(10000);
}
The current output is 6D:98:C9:00:00:00 which is completely off. It duplicates this output for other APs too. Is this a hardware problem? I've seen other people using the same codes and it works for them. For reference WiFi.SSID(); and WiFi.RSSI(); both spits out correctly.
edit: I was testing both output to see which ever one was correct and unfortunately they're both wrong
A:
This seems wrong, you are trying to get String to interpret a byte, but are passing in a pointer to a byte:
String digit = String(*mac, HEX);
Try changing your example to:
uint8_t* mac=WiFi.BSSID(); // Gather the byte array
String APmac;
for (int i=0; i<6;i++) {
String digit = String(mac[i], HEX); // String() should see an int, not a pointer to a byte, with the directive to print it in HEX format
if (digit.length() <2)
APmac += String("0")+digit; // Corrected capitalization error
else
APmac +=digit; // Corrected capitalization error
//mac++; // Not necessary
Serial.print("["); Serial.print(i); Serial.print("]");
Serial.println(mac[i], HEX);
}
Serial.println(APmac); // Print the constructed String
Serial.println(WiFi.BSSIDstr()); // Print the pre-formatted string
Consider not using the String object, which may help condense the code a bit:
uint8_t* mac=WiFi.BSSID();
char APmac[13];
APmac[0]=0;
for (int i=0; i<6;i++) {
char buffer[3];
sprintf(buffer, "%02x", mac[i]);
strncpy((char *)(APmac+(i*2)), buffer, 3);
Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
}
Serial.println(APmac);
Serial.println(WiFi.BSSIDstr());
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to convert a MATLAB array to a Python array
I have this MATLAB code that I need to translate to python, however there is an issue in creating a new column in the firings array. In MATLAB, the code creates an n*2 matrix that is initially empty and I want to be able to do the same in python. Using NumPy, I created fired = np.where(v >= 30). However python creates a tuple rather than an array so it throws an error:
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
This is the code I have in MATLAB that I would like converted into Python
firings=[];
firings=[firings; t+0*fired, fired];
Help is appreciated! Thanks!
A:
np.where generates a two-element tuple if the array is 1D in nature. For the 1D case, you would need to access the first element of the result of np.where only:
fired = np.where(v >= 30)[0]
You can then go ahead and concatenate the matrices. Also a suggestion provided by user @Divakar would be to use np.flatnonzero which would equivalently find the non-zero values in a NumPy array and flattened into a 1D array for less headaches:
fired = np.flatnonzero(v >= 30)
Take note that the logic to concatenate would not work if there were no matches found in fired. You will need to take this into account when you look at your concatenating logic. The convenient thing with MATLAB is that you're able to concatenate empty matrices and the result is no effect (obviously).
Also note that there is no conception of a row vector or column vector in NumPy. It is simply a 1D array. If you want to specifically force the array to be a column vector as you have it, you need to introduce a singleton axis in the second dimension for you to do this. Note that this only works provided that np.where gave you matched results. After, you can use np.vstack and np.hstack to vertically and horizontally concatenate arrays to help you do what you ask. What you have to do first is create a blank 2D array, then do what we just covered:
firings = np.array([[]]) # Create blank 2D array
# Some code here...
# ...
# ...
# fired = find(v >= 30); % From MATLAB
fired = np.where(v >= 30)[0]
# or you can use...
# fired = np.flatnonzero(v >= 30)
if np.size(fired) != 0:
fired = fired[:, None] # Introduce singleton axis
# Update firings with two column vectors
# firings = [firings; t + 0 * fired, fired]; % From MATLAB
firings = np.vstack([firings, np.hstack([t + 0*fired, fired])])
Here np.size finds the total number of elements in the NumPy array. If the result of np.where generated no results, the number of elements in fired should be 0. Therefore the if statement only executes if we have found at least one element in v subject to v >= 30.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the difference between Amaretto and Crème de Noyaux?
Both Amaretto and Crème de Noyaux are sweet almond-flavored liqueurs.
My understanding is that Crème de Noyaux is typically red, whereas Amaretto is usually brown.
Other than the obvious difference in color, what's the difference between these two liqueurs?
What differences in production are associated with bottling a liqueur under the name "Crème de Noyaux" versus "Amaretto"?
What differences would you notice in a blind taste test? Would you be able to tell if I made a Pink Squirrel with amaretto, or a French Connection with crème de noyaux?
A:
What's the difference between Amaretto and Crème de Noyaux?
Amaretto
County of origin: Italy (Saronno, Italy)
Alcohol by Volume: 28%
Flavor: Slight bitter almond
"Flavoured from bitter almonds, various modern commercial brands are prepared from a base of apricot stones, peach stones, or almonds, all of which are natural sources of the benzaldehyde that provides the principal almond-like flavour of the liqueur." - Amaretto (Wikipedia)
Etymology: "The name amaretto originated as a diminutive of the Italian word amaro, meaning "bitter", which references the distinctive flavour lent by the mandorla amara or by the drupe kernel. However, the bitterness of amaretto tends to be mild, and sweeteners (and sometimes sweet almonds) enhance the flavour in the final products. Thus one can interpret the liqueur's name as a description of the taste as "a little bitter". - Amaretto (Wikipedia)
Bottles of Amaretto Liqueur
Crème de Noyaux
Country of origin: France
Alcohol by Volume: 40%
Color: Pink or Clear (Bols is red)
Flavor: Almond
"Crème de Noyaux (pronounced is an almond-flavored crème liqueur, although it is actually made from apricot kernels or the kernels of peach or cherry pits, which provide an almond-like flavor. Both Bols and Hiram Walker produce artificially colored red versions of the liqueur (either of which contribute the pink hue to Pink Squirrel cocktails) while Noyau de Poissy from France is available in both clear (blanc) and barrel-aged amber (ambre) versions." - Crème de Noyaux (Wikipedia)
Definition: A liqueur with a brandy base flavored primarily with essential oils derived from the kernels of peaches, plums, and cherries or from almonds, the predominant flavor being that of bitter almonds. - Crème de Noyau
Bols Creme de Noyaux Liqueur 1L
To me amaretto tastes a little less bitter than creme de noyaux, while crème de noyau tastes a little bit more nuttier at the same time. I am not a professional connoisseur so you can take or leave what I say here.
A:
As Ken pointed out (although didn't make a point of): Aside from being made using slightly different ingredients, one is a liqueur and one a creme liqueur, which contain a lot more sugar and are therefore more syrupy in consistency.
Therefore, although they taste similar, it may not be a good idea to substitute one for the other. I personally enjoy an amaretto over ice, but the idea of doing this with Creme de Noyaux makes me feel a little queasy (in the same way I love a maple syrup but am not going to add vodka and drink that over ice).
There are probably ways you can change the original recipes slightly to adjust for this difference and are then likely to get a similar flavour :)
| {
"pile_set_name": "StackExchange"
} |
Q:
c#: Switch case: if (case:)
This question might seem familiar to some of you who answered or viewed my previous question regarding the break; statement. I want to do something if case 1 was satisfied, and something else if case 2. Something like the following. Can anyone guide me (if it is doable) on how I can achieve what I'm trying to do instead of having to put my if statements inside the switch case?
switch (searchType)
{
case "SearchBooks":
Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
break;
case "SearchAuthors":
Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
break;
}
int count = int(Selenium.GetXpathCount("//[@id='Results_Table']");
if case was "SearchBooks"
{
//do something
}
else if case was "SearchAuthors"
{
//do something else
}
A:
if (searchType == "SearchAuthors")
You can't do any better than that.
A:
Call me geek. :)
Selenium.Type(string.Format(@"//*[@id='{0}_TextInput']", searchType), searchText);
Selenium.Click(string.Format(@"//*[@id='{0}_SearchBtn']", searchType));
And save the case statements.
Now, obviously, this only works if searchType values always correspond to actual element IDs.
A:
If the only line in common both cases is the
int count = int(Selenium.GetXpathCount("//[@id='Results_Table']");
then I would just write that twice.
int count;
switch (searchType)
{
case "SearchBooks":
Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
count = int(Selenium.GetXpathCount("//[@id='Results_Table']");
//do something
break;
case "SearchAuthors":
Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
count = int(Selenium.GetXpathCount("//[@id='Results_Table']");
//do something else
break;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
angularjs app not showing special characters in placeholder text in ui-select field
I have a multilingual angular app, and one of the languages has special characters, umlaut, for example. They are being shown fine on the labels, titles, headings, but not in placeholder text.
here is the code i have :
<label translate="app.title"></label>
<ui-select name="myoption" ng-model="app.option" theme="selectize">
<ui-select-match placeholder="{{ 'app.placeholder' | translate }}">
{{$select.selected.value}}
</ui-select-match>
<ui-select-choices repeat="o.key as o in tras.app.options | filter: $select.search">
<div ng-bind-html="o.value | highlight: $select.search"></div>
</ui-select-choices>
</ui-select>
label title has a special character like ä or ö which are being shown fine. But the same word is also in the placeholder text, but it is being shown as ä.
Why is it behaving like this? Could somebody help to fix it?
A:
this issue has been discussed here https://github.com/angular-translate/angular-translate/issues/1282
you need to turn off sanitize:
$translateProvider.useSanitizeValueStrategy(null);
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Antimagic Field suppress all layers of True Polymorph simultaneously?
Imagine that you have cast True Polymorph to turn a medium object into a Helmed Horror with Spell Immunity to Antimagic Field. If you were to then True Polymorph that Helmed Horror into something else, it would lose its Spell Immunity, as its entire statblock is changed. However, what exactly would happen if the newly True Polymorphed creature walked into an Antimagic Field?
I see two plausible outcomes:
Both layers of True Polymorph are suppressed simultaneously and the creature is immediately turned back into a medium object.
The most recent layer of True Polymorph is suppressed, at which point the Helmed Horror's Spell Immunity kicks in and prevents the next layer from being suppressed.
I think each of these interpretations has a decent argument:
This is how Dispel Magic works. If the Helmed Horror also had Spell Immunity to Dispel Magic, the underlying layer of True Polymorph could still be dispelled, because Dispel Magic reads (emphasis mine):
For each spell of 4th level or higher on the target, make an ability check using your spellcasting ability. The DC equals 10 + the spell's level. On a successful check, the spell ends.
Both layers of True Polymorph are on the target, and so both can be dispelled, and there is no reason to suspect they aren't dispelled simultaneously (before the Spell Immunity could ever kick in).
Antimagic Field reads (emphasis mine):
Any active spell or other magical effect on a creature or an object in the sphere is suppressed while the creature or object is in it.
And while there are two layers of True Polymorph on the creature, it seems reasonable to assume that only the most recent is "active", due to the rules for Combining Magical Effects:
The effects of the same spell cast multiple times don't combine, however. Instead, the most potent effect--such as the highest bonus--from those castings applies while their durations overlap, or the most recent effect applies if the castings are equally potent and their durations overlap.
This (plausibly, I think) could be interpreted to mean that the most recent layer of True Polymorph is suppressed first, at which point Antimagic Field would suppress the next layer if not for the Spell Immunity.
Is one of these two interpretations unambiguously supported by Rules as Written?
A:
Your assumption stated at the end is correct.
Your second possible interpretation mentions the following:
The most recent layer of True Polymorph is suppressed first, at which point Antimagic Field would suppress the next layer if not for the Spell Immunity.
Once the Helmed Horror is True Polymorphed into another creature, it no longer has Spell Immunity. Its stat block is replaced by that of its new form, and I'm assuming its new form doesn't also have Spell Immunity.
If the True Polymorph is ended on this form and it morphs back into a Helmed Horror, then the Spell Immunity would now be present, and this magical effect is immune to the antimagic field's effect because of the specificity.
The introduction to the game states:
Remember this: If a specific rule contradicts a general rule, the specific rule wins.
Antimagic field has a general effect of "everything in this range", while Helmed Horror's Spell Immunity specifies "ignore this particular thing".
The rule about combination you state means that you have two distinct True Polymorphs. They are not considered one effect, and each is separately active. This is more important for effects that confer a buff. Something currently affected by Shield of Faith to get +2 AC wouldn't benefit from a second casting.
| {
"pile_set_name": "StackExchange"
} |
Q:
Recover lost passion
Last year I played in a chess league in my city (Average of 1800 ELO). But I currently have a sense of boredom with chess in general. I have lost the passion for this game. Winning or losing don't affect me too much. I'm focused mainly on the quality of my games.
Playing chess tournaments takes some preparation: like tactics, endings, openings, ... I don`t feel bored with preparation or training.
But In the moment when I play with another person, I don´t enjoy it. I enjoy more playing against the computer. but this doesn't make sense. If anybody trains to be better, it is to put this learning into practice.
Could you give me any suggestions to recover the encouragement to play? Any tip to enjoy playing chess tournaments? What tips do you use to maintain your motivation at a high level?
A:
If this only concerns playing in tournaments just play casual non-tournament games.
I am not sure how you would judge the "quality of your games" if the outcome (win/loss) is not important to you.
If you haven't done so already, perhaps joining a chess club and playing in team competitions could motivate you.
A:
First, there seems to be nothing wrong with wanting quality over quantity in your games. But if you're worried that a creeping perfection is ruining your chances to enjoy a game, maybe you just need a break. I know there were times I thought I was getting bored with chess, so I played in a tournament to prove I wasn't, and I wound up playing what was frankly pretty boring chess just to avoid blunders, and I wound up more and frustrated than when I started.
Discovering knowledge for its own sake can be extremely rewarding. I had a lot of fun running my old games through a chess engine to see what sort of mistakes I commonly made. It was tough, but revealing.
Perhaps you are at a phase where studying things without the pressure of winning and losing is more exciting, or the enjoyment last longer. "Winning isn't everything" is a bit of a cliche, but in this case, maybe you will have more fun just meeting once a week to play several blitz games and to try out new odd openings.
| {
"pile_set_name": "StackExchange"
} |
Q:
Slow hash algorithm that does not require salt?
I usually choose bcrypt when hashing as I can set the work factor to slow down the calculations of the hash. However, I have to keep a copy of the hash in order to verify it (since it includes the salt) when the same input comes around again.
Are their any A) common and B) slow hashing algorithms that do not require a salt? In other words, I don't need to preserve the output state in order to calculate the exact same hash again?
I am not looking for a more secure/unbreakable hash - just one that takes a long, long time to work out.
At this point it seems that multiple rounds of SHA-256 is my current best option.
A:
You can use any common slow hash construction that takes a salt with a constant salt. This includes scrypt, bcrypt and PBKDF2.
You obviously lose the benefit of the salt. Since the purpose of a salt is preventing multi-target attacks, now an attacker can attack all hashes at the same time. I'd use at least a salt that's unique for your application, so an attacker can't attack your application at the same time as others.
Personally I'd go with scrypt, since it strengthens the most for a given derivation time limit, but you can use bcrypt or PBKDF2 if you prefer older/more popular constructions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Assign higher z-index to mask images
We are Fetching mask image from JSON & displaying inside Container
Onclick Mask image, we are allowing to upload another image on mask as below, also user can drag the uploaded image as in Codepen1, everything was fine...
Now Client want to display mask image above Box image, so I displayed mask image on top of box image as below :
Issue :
when I click on mask image [left side], higher z-index value assign to box image, so box image will override mask image. because mask image & box image are overlapped with each other.
when I click on mask image [right side], then there is no problem...
Also, I can able to drag the uploaded image successfully from the right side of mask image but not from the left side.
Z-index code :
container.enable = function() {
draggable = true;
$(canvas).attr("active", "true");
div.css({
"z-index": 2
});
}
container.disable = function() {
draggable = false;
$(canvas).attr("active", "false");
div.css({
"z-index": 1
});
}
container.selected = function(ev) {
var pos = container.mousePosition(ev);
var item = $(".masked-img canvas").filter(function() {
var offset = $(this).offset()
var x = pos.x - offset.left;
var y = pos.y - offset.top;
var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
return d[0] > 0
});
JQmasks.forEach(function(el) {
var id = item.length > 0 ? $(item).attr("id") : "";
if (el.id == id)
el.item.enable();
else el.item.disable();
});
};
Snippet :
var target;
const imageUrl = "";
let jsonData = {
"layers": [{
"name": "design3",
"x": 0,
"y": 0,
"width": 300,
"height": 300,
"layers":[
{
"type":"image",
"src":"14IVyVb.png",
"name":"bg_img",
"x":0,
"y":0,
"width":200,
"height":200
},
{
"type":"image",
"src":"l8vA9bB.png",
"name":"mask_image",
"x":100,
"y":15,
"width":180,
"height":166
}]
}]
};
const containerElement = $('#container');
const fileUp = $('#fileup');
let mask;
$(function() {
// Upload image onclick mask image
containerElement.click(function(e) {
// filtering out non-canvas clicks
if (e.target.tagName !== 'CANVAS') return;
// getting absolute points relative to container
const absX = e.offsetX + e.target.parentNode.offsetLeft + e.currentTarget.offsetLeft;
const absY = e.offsetY + e.target.parentNode.offsetTop + e.currentTarget.offsetTop;
const $canvasList = $(this).find('canvas');
// moving all canvas parents on the same z-index
$canvasList.parent().css({
zIndex: 0
});
$canvasList.filter(function() { // filtering only applicable canvases
const bbox = this.getBoundingClientRect();
const canvasTop = bbox.top + window.scrollY;
const canvasLeft = bbox.left + window.scrollX;
return (
absX >= canvasLeft && absX <= canvasLeft + bbox.width &&
absY >= canvasTop && absY <= canvasTop + bbox.height)
}).each(function() { // checking white in a click position
const x = absX - this.parentNode.offsetLeft - e.currentTarget.offsetLeft;
const y = absY - this.parentNode.offsetTop - e.currentTarget.offsetTop;
const pixel = this.getContext('2d').getImageData(x, y, 1, 1).data;
if (pixel[3] === 255)
{
if (!$(e.currentTarget).data('image_set' + target))
$(this).parent().css({
zIndex: 2
})
target = this.id;
console.log(target);
if (!$(e.currentTarget).data('image_set' + target))
setTimeout(fileUp.click.bind(fileUp), 20);
}
})
});
// Fetch mask images from json file - IGNORE this code
function getAllSrc(layers) {
let arr = [];
layers.forEach(layer => {
if (layer.src) {
arr.push({
src: layer.src,
x: layer.x,
y: layer.y,
height: layer.height,
width: layer.width,
name: layer.name
});
} else if (layer.layers) {
let newArr = getAllSrc(layer.layers);
if (newArr.length > 0) {
newArr.forEach(({
src,
x,
y,
height,
width,
name
}) => {
arr.push({
src,
x: (layer.x + x),
y: (layer.y + y),
height,
width,
name: (name)
});
});
}
}
});
return arr;
}
function json(data) {
var width = 0;
var height = 0;
let arr = getAllSrc(data.layers);
let layer1 = data.layers;
width = layer1[0].width;
height = layer1[0].height;
let counter = 0;
let table = [];
// container dimensions
containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
//end
for (let {
src,
x,
y,
name
} of arr) {
//Get Height and width of mask image [ edit button ]
var ImagePosition = arr;
//code end
var imageUrl1 = imageUrl;
var mask = $(".container").mask({
imageUrl: name.indexOf('mask_') !== -1 ? imageUrl1 : undefined,
// Fetch Mask images
maskImageUrl: 'http://i.imgur.com/' + src,
// end
onMaskImageCreate: function(img) {
// Mask image positions
img.css({
"position": "absolute",
"left": x + "px",
"top": y + "px"
});
// end
},
id: counter
});
// here
ImagePosition.map(function(cur, index) {
var available = cur.name.includes('mask_');
if (!available) {
$('.masked-img' + index).css('pointer-events', 'none');
}
});
table.push(mask);
fileup.onchange = function() {
let mask2 = table[target];
const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
document.getElementById('fileup').value = "";
};
counter++;
}
return mask;
}
mask = json(jsonData);
}); // end of function
// Image code
(function($) {
window.JQmasks = [];
$.fn.mask = function(options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
maskImageUrl: undefined,
imageUrl: undefined,
scale: 1,
id: new Date().getUTCMilliseconds().toString(),
x: 0, // image start position
y: 0, // image start position
onMaskImageCreate: function(div) {},
}, options);
// Create the image properties
settings.maskImage = new Image
settings.image = new Image
// set the cross-origin attributes
settings.maskImage.setAttribute('crossOrigin', 'anonymous');
settings.image.setAttribute('crossOrigin', 'anonymous');
settings.maskImage.onload = function() {
// once the mask is loaded, load the image
container.loadImage(settings.imageUrl)
container.drawMask()
}
settings.image.onload = function() {
// once the image is loaded, render to canvas
container.drawImage()
}
var container = $(this);
let prevX = 0,
prevY = 0,
draggable = false,
img,
canvas,
context,
image,
timeout,
initImage = false,
startX = settings.x,
startY = settings.y,
div;
container.mousePosition = function(event) {
return {
x: event.pageX || event.offsetX,
y: event.pageY || event.offsetY
};
}
container.selected = function(ev) {
var pos = container.mousePosition(ev);
var item = $(".masked-img canvas").filter(function() {
var offset = $(this).offset()
var x = pos.x - offset.left;
var y = pos.y - offset.top;
var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
return d[0] > 0
});
JQmasks.forEach(function(el) {
var id = item.length > 0 ? $(item).attr("id") : "";
if (el.id == id)
el.item.enable();
else el.item.disable();
});
};
container.enable = function() {
draggable = true;
$(canvas).attr("active", "true");
div.css({
"z-index": 2
});
}
container.disable = function() {
draggable = false;
$(canvas).attr("active", "false");
div.css({
"z-index": 1
});
}
container.drawMask = function() {
if (!settings.maskImage) return true;
canvas.width = settings.maskImage.width;
canvas.height = settings.maskImage.height;
context.save();
context.beginPath();
context.globalCompositeOperation = "source-over";
// draw the masked image after scaling
if (settings.maskImage) context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage.height);
context.restore()
};
container.drawImage = function() {
const img = settings.image
settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
context.globalCompositeOperation = 'source-atop';
context.save();
context.translate(settings.x + img.width / 2, settings.y + img.height / 2);
context.rotate(settings.rotate);
context.scale(settings.scale, settings.scale);
context.translate(-(settings.x + img.width / 2), -(settings.y + img.height / 2));
let width = img.width,
height = img.height;
if (img)
context.drawImage(img, settings.x, settings.y, width, height);
context.restore();
initImage = false;
}
// change the draggable image
container.onDragStart = function(evt) {
// console.log('Draw started');
if (evt.target.getContext) {
var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
$(canvas).attr("active", "true");
container.selected(evt);
prevX = evt.clientX;
prevY = evt.clientY;
var img = new Image();
evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);
evt.originalEvent.dataTransfer.setData('text/plain', 'anything');
}
};
container.onDragOver = function(evt) {
// console.log('Drag over');
if (evt.target.getContext) {
var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
if (pixel[3] === 255) {
if (draggable && $(canvas).attr("active") === "true") {
var x = settings.x + evt.clientX - prevX;
var y = settings.y + evt.clientY - prevY;
if (x == settings.x && y == settings.y)
return; // position has not changed
settings.x += evt.clientX - prevX;
settings.y += evt.clientY - prevY;
prevX = evt.clientX;
prevY = evt.clientY;
//logTMatrix(settings);
clearTimeout(timeout);
timeout = setTimeout(function() {
container.drawMask();
container.drawImage();
}, 1);
}
} else {
evt.stopPropagation();
return false;
}
}
};
container.loadImage = function(imageUrl) {
if (!imageUrl) return true;
settings.y = startY;
settings.x = startX;
prevX = prevY = 0;
initImage = true;
settings.image.src = imageUrl; // CHANGED
// sirpepole Add this
return settings.id;
};
container.loadMaskImage = function(imageUrl, from) {
canvas = document.createElement("canvas");
context = canvas.getContext('2d');
canvas.setAttribute("draggable", "true");
canvas.setAttribute("id", settings.id);
// settings.maskImageUrl = imageUrl;
settings.maskImage.src = imageUrl // CHANGED
div = $("<div/>", {
"class": "masked-img"
}).append(canvas);
// div.find("canvas").on('touchstart mousedown', function(event)
div.find("canvas").on('dragstart', function(event) {
if (event.handled === false) return;
event.handled = true;
container.onDragStart(event);
});
div.find("canvas").on('touchend mouseup', function(event) {
if (event.handled === false) return;
event.handled = true;
container.selected(event);
});
div.find("canvas").bind("dragover", container.onDragOver);
container.append(div);
if (settings.onMaskImageCreate)
settings.onMaskImageCreate(div);
// container.loadImage(settings.imageUrl);
// Moved this to the settings.maskImage.onload
};
if (settings.maskImageUrl) {
container.loadMaskImage(settings.maskImageUrl);
}
JQmasks.push({
item: container,
id: settings.id
})
// Edit image
div.addClass('masked-img' + settings.id);
div.attr('data-id', settings.id);
// ends
return container;
};
}(jQuery));
.container {
background: silver;
position: relative;
}
.container img {
position: absolute;
top: 0;
bottom: 250px;
left: 0;
right: 0;
margin: auto;
z-index: 999;
}
.masked-img {
overflow: hidden;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<input id="fileup" name="fileup" type="file" style="display:none">
<div id="container" class="container">
</div>
Here is Video link & Code in Pastebin & Fiddle & Codepen
A:
I am confused by the overall implementation and there are multiple lines terminated without semicolon. Anyway, the root cause is inside container.selected(). You don't need to implement your way to find which canvas is selected. You attach the event by using div.find("canvas").on('touchend mouseup', function(event) {...}; and the browser will trigger the event with the correct target for you. When the event is triggered, the listener will be invoked. The target is given in the event object (namely event.currentTarget). That is the spirit of event listener.
The original container.selected() predicts which canvas is touched by using mouse pointer position. Since box image and mask image have certain area overlaped, the result may contains two canvas and z-index is applied to the wrong one.
I modify container.selected() as follow
container.selected = function(ev) {
var pos = container.mousePosition(ev);
var item = ev.currentTarget;
JQmasks.forEach(function(el) {
var id = $(item).attr("id");
if (el.id == id)
el.item.enable();
else
el.item.disable();
});
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I invert a single row of a very large sparse matrix?
Problem
I research electron behavior in organic solar cells and have found a way to recast this problem in terms of a large (n=~60 million) Absorbing Markov Chain that I represent as a sparse matrix. The matrix has high dimension but only 12 nonzero entries per row (at most). From the Markov Chain, I want to build its fundamental matrix:
$\mathbf{Q} = (\mathbf{I} - \mathbf{V})^{-1}$
and use that matrix to find the first passage time from a specific initial state i to any absorbing state. I know that $Q_{ij}$ is the mean number of times that the system starting in state i visits state j before being absorbed. So, if I could calculate a single row of $\mathbf{Q}$, i.e. calculate a single row of the inverse of a given sparse matrix, then I would be done.
My question is, is it possible to calculate a single row of the inverse of a matrix without having to calculate the rest of the inverse?
Complications
The matrix is extremely large (dimension > 60 million) and the only way I can store it in memory is because it is so sparse. The inverse is known to be dense so I cannot calculate it all explicitly. It's no problem to store a few vectors of length 60 million though. I have access to a nice computer with many GB of RAM.
I have tried just solving the system using restarted GMRES(m), however even with ILU(2) preconditioning and as long a restart as my computer has RAM for (m = 50), GMRES has uselessly slow convergence and basically stagnates. The matrix is nonsymmetric but diagonally dominant by construction. It has real entries.
Edit More Info
V comes from a random walk problem in 3 dimensions with 2 particles on a cubic lattice, so each row in V is a particular combination of a location for particle 1 and a location for particle 2 in 3-space. I restrict their position to a box of side s to limit the size of the matrix. The problem requires that s be large enough such that $s^6$ is on the order of 60 million, hence the matrix size. V has unity on the diagonal and strictly negative off diagonal elements with magnitude < 1. There are at most 12 off diagonal elements for row, corresponding to two directions of hopping along each of the 3 cardinal axes for each of the 2 particles.
I have not yet tried solving the system with GMRES for a right-hand-side that is just a basis vector but have tried for a rhs that is all 1s, which would also solve the problem and that does not converge. I will try to solve for a basis vector rhs tomorrow. Would you expect that to have better convergence properties?
A:
Well, generally, for a matrix $A$ and a vector $b,$ it is much easier to compute $A^{-1}b$ than computing $A^{-1}$ (conjugate gradient is one way, there are others). So, to compute the first row, just compute $A^{-1} e_i$ for every basis vector $e_i,$ and then take the list of the first coordinates. This requires no extra memory, so while it will not be fast (you will have to run $60000000$ conjugate gradients, or whatever, but it will return.
| {
"pile_set_name": "StackExchange"
} |
Q:
Lost access to the unity interface how to fix?
o.k, this is embarrassing:
I have installed Compiz Config Settings Manager and tried to fix it so that the transition time between changing tabs (using alt+tab) will be short. by accident I un-pressed V from something else, and it asked me about a conflict - I pressed the "x" button to close the window and as a result I stopped seeing the unity interface. That is - I can not see any buttons of the left side.
I went to the terminal (ctrl+alt+F1) and ran
ccsm
As a result I got the following error:
$ ccsm
/usr/lib/python2.7/site-packages/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
Traceback (most recent call last):
File "/usr/bin/ccsm", line 93, in <module>
import ccm
File "/usr/lib/python2.7/site-packages/ccm/__init__.py", line 1, in <module>
from ccm.Conflicts import *
File "/usr/lib/python2.7/site-packages/ccm/Conflicts.py", line 26, in <module>
from ccm.Constants import *
File "/usr/lib/python2.7/site-packages/ccm/Constants.py", line 29, in <module>
CurrentScreenNum = gtk.gdk.display_get_default().get_default_screen().get_number()
AttributeError: 'NoneType' object has no attribute 'get_default_screen'
What should I do next?
A:
This seemed fixed once I went to terminal (ctrl+alt+F1) and pressed:
gconftool-2 --recursive-unset /apps/compiz-1
gconftool-2 --recursive-unset /apps/compizconfig-1
rm ~/.compiz-1/session/*
rm ~/.config/compiz-1/compizconfig/config
unity --reset
source: http://ubuntuforums.org/showthread.php?t=1866462
A:
You can try to reset unity settings with unity --replace and if fails try unity --reset
If all those fails and you still cannot get to CCSM then reinstall it with commands:
if you don't want to remove setting substitute purge with remove in command below
sudo apt-get purge compizconfig-settings-manager
sudo apt-get install compizconfig-settings-manager
Disclaimer: Iam not sure the link Iam about to post is still applicable as thread dates to 2008.
http://ubuntuforums.org/showthread.php?t=799070
UPDATE
It seems as if you are not yet logged in GUI, and so there is no XServer running yet. Try in failsafe mode (recovery mode) and fix things from there
| {
"pile_set_name": "StackExchange"
} |
Q:
GCD terminate request
I would like to send a request to server after a delay, but if user has changed state of UITextFiled this request should be terminated. What I have now is
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
sessionManager.session.invalidateAndCancel()
APIModel().searchRequest()...
}
but it actually does not stop the request from getting to server. I guess I should use GDC delay to wait a second before sending request and then, if UITextField changed, terminate it. But I could not find an example of this logic realisation.
A:
You can't "terminate" a request.
You can create an object with a "cancelled" property. Then you dispatch code that access that object, and which at appropriate times checks whether the "cancelled" property is true. And from the outside, you set cancelled to true when you feel like it.
If the operation manages to finish and detects that it was cancelled, it should then not produce any error message, and not do anything else, since it was cancelled.
| {
"pile_set_name": "StackExchange"
} |
Q:
endOfConversation not a function
My bot right now is using local memory, the goal is whenever a conversation end. I want to delete everything from local memory about this user. So I tried this onEndOfConversation.
Apparently this error shows up saying that onEndOfConversation is not a function.
This is my code :
const { CardFactory } = require('botbuilder');
const { DialogBot } = require('./dialogBot');
const WelcomeCard = require('./resources/welcomeCard.json');
class DialogAndWelcomeBot extends DialogBot {
constructor(conversationState, userState, dialog) {
super(conversationState, userState, dialog);
this.onMembersAdded(async (context, next) => {
const membersAdded = context.activity.membersAdded;
for (let cnt = 0; cnt < membersAdded.length; cnt++) {
if (membersAdded[cnt].id !== context.activity.recipient.id) {
//const welcomeCard = CardFactory.adaptiveCard(WelcomeCard);
//await context.sendActivity({ attachments: [welcomeCard] });
await dialog.run(context, conversationState.createProperty('DialogState'));
}
}
// By calling next() you ensure that the next BotHandler is run.
await next();
});
this.onEndOfConversation(async (context, next) => {
console.log("END!");
await conversationState.delete(context);
await userState.delete(context);
});
}
}
module.exports.DialogAndWelcomeBot = DialogAndWelcomeBot;
So how should I do this? If onEndOfConversation isn't recognize, what alternatives I can do to clear user and conversation from the memory after a dialogue ends.
A:
The endOfConversation activity handler is used internally when a bot is also coupled with a skill. When a conversation is ended by the user, the bot then sends this activity type to the skill notifying it that the conversation has ended with the user.
There are different ways you could attack this. The method I use is component dialogs. Modeled after the cancelAndHelpDialog design, when a user types "cancel" or "quit", the user is brought to an exit dialog where feedback is gathered, etc.
As part of the exiting process, you could call conversationState.delete() within the dialog followed by cancelAllDialogs(true).
Hope of help!
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the reason behind this huge Performance difference in .Net 4
I was just doing some research on RedBlack Tree. I knew that SortedSet class in .Net 4.0 uses RedBlack tree. So I took that part out as is using Reflector and created a RedBlackTree class. Now I am running some perf test on this RedBlackTree and SortedSet inserting 40000 sequential integral values (starting from 0 to 39999), I am astonished to see that there is huge perf difference as follows:
RBTree took 9.27208 sec to insert 40000 values
SortedSet took 0.0253097 sec to insert 40000 values
What is the reason behind it? BTW I ran the test in Release configuration only and here is the small test code
var stopWatch = new Stopwatch();
var rbT = new RedBlackTree<int>();
stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 40000; i++) {
rbT.Add(i);
}
stopWatch.Stop();
Console.WriteLine(stopWatch.Elapsed);
var ss = new SortedSet<int>();
stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 40000; i++) {
ss.Add(i);
}
stopWatch.Stop();
Console.WriteLine(stopWatch.Elapsed);
Edit
I would like to share the code also for RBTree what I've extracted so that you also can run the diagnostics
public class Node<T>
{
public Node(){}
public Node(T value)
{
Item = value;
}
public Node(T value, bool isRed)
{
Item = value;
IsRed = isRed;
}
public T Item;
public Node<T> Left;
public Node<T> Right;
public Node<T> Parent;
public bool IsRed;
}
public class RedBlackTree<T>
{
public RedBlackTree(){}
public Node<T> root;
int count, version;
Comparer<T> comparer = Comparer<T>.Default;
public void Add(T item)
{
if (this.root == null)
{
this.root = new Node<T>(item, false);
this.count = 1;
this.version++;
return;
}
Node<T> root = this.root;
Node<T> node = null;
Node<T> grandParent = null;
Node<T> greatGrandParent = null;
this.version++;
int num = 0;
while (root != null)
{
num = this.comparer.Compare(item, root.Item);
if (num == 0)
{
this.root.IsRed = false;
return;
}
if (Is4Node(root))
{
Split4Node(root);
if (IsRed(node))
{
this.InsertionBalance(root, ref node, grandParent, greatGrandParent);
}
}
greatGrandParent = grandParent;
grandParent = node;
node = root;
root = (num < 0) ? root.Left : root.Right;
}
Node<T> current = new Node<T>(item);
if (num > 0)
{
node.Right = current;
}
else
{
node.Left = current;
}
if (node.IsRed)
{
this.InsertionBalance(current, ref node, grandParent, greatGrandParent);
}
this.root.IsRed = false;
this.count++;
}
private static bool IsRed(Node<T> node)
{
return ((node != null) && node.IsRed);
}
private static bool Is4Node(Node<T> node)
{
return (IsRed(node.Left) && IsRed(node.Right));
}
private static void Split4Node(Node<T> node)
{
node.IsRed = true;
node.Left.IsRed = false;
node.Right.IsRed = false;
}
private void InsertionBalance(Node<T> current, ref Node<T> parent, Node<T> grandParent, Node<T> greatGrandParent)
{
Node<T> node;
bool flag = grandParent.Right == parent;
bool flag2 = parent.Right == current;
if (flag == flag2)
{
node = flag2 ? RotateLeft(grandParent) : RotateRight(grandParent);
}
else
{
node = flag2 ? RotateLeftRight(grandParent) : RotateRightLeft(grandParent);
parent = greatGrandParent;
}
grandParent.IsRed = true;
node.IsRed = false;
ReplaceChildOfNodeOrRoot(greatGrandParent, grandParent, node);
}
private static Node<T> RotateLeft(Node<T> node)
{
Node<T> right = node.Right;
node.Right = right.Left;
right.Left = node;
return right;
}
private static Node<T> RotateRight(Node<T> node)
{
Node<T> left = node.Left;
node.Left = left.Right;
left.Right = node;
return left;
}
private static Node<T> RotateLeftRight(Node<T> node)
{
Node<T> left = node.Left;
Node<T> right = left.Right;
node.Left = right.Right;
right.Right = node;
left.Right = right.Left;
right.Left = left;
return right;
}
private static Node<T> RotateRightLeft(Node<T> node)
{
Node<T> right = node.Right;
Node<T> left = right.Left;
node.Right = left.Left;
left.Left = node;
right.Left = left.Right;
left.Right = right;
return left;
}
private void ReplaceChildOfNodeOrRoot(Node<T> parent, Node<T> child, Node<T> newChild)
{
if (parent != null)
{
if (parent.Left == child)
{
parent.Left = newChild;
}
else
{
parent.Right = newChild;
}
}
else
{
this.root = newChild;
}
}
}
Edit
I ran the same diagnostic on some other data structure (some created by me*, some from .net framework**) and here is the interesting results
*AATree 00:00:00.0309294
*AVLTree 00:00:00.0129743
**SortedDictionary 00:00:00.0313571
*RBTree 00:00:09.2414156
**SortedSet 00:00:00.0241973
RBTree is the same as above (stripped out from SortedSet class). I tried with 400000 values also, but RBTree seems taking FOREVER, I really don't know why.
A:
You have a bug in your Node<T> class. When you call the constructor that only takes a single value argument you should be setting IsRed to true.
I suppose that the fixed Node<T> class should look something like this:
public sealed class Node<T>
{
public T Item { get; private set; }
public bool IsRed { get; set; }
public Node<T> Left { get; set; }
public Node<T> Right { get; set; }
public Node(T value)
{
Item = value;
IsRed = true;
}
public Node(T value, bool isRed)
{
Item = value;
IsRed = isRed;
}
}
Another option -- my preference -- would be to omit that constructor altogether and always require IsRed to be set explicitly when you instantiate a new node:
public sealed class Node<T>
{
public T Item { get; private set; }
public bool IsRed { get; set; }
public Node<T> Left { get; set; }
public Node<T> Right { get; set; }
public Node(T value, bool isRed)
{
Item = value;
IsRed = isRed;
}
}
And then replace this line in your Add method...
Node<T> current = new Node<T>(item);
...with this...
Node<T> current = new Node<T>(item, true);
A:
reverse the order of the tests and repeat the measurement.
randomize your data. Sorted sets behave strangely when you insert pre-sorted data.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to output Regression Analysis summary from polynomial regression with scikit-learn?
I currently have the following code, which does a polynomial regression on a dataset with 4 variables:
def polyreg():
dataset = genfromtxt(open('train.csv','r'), delimiter=',', dtype='f8')[1:]
target = [x[0] for x in dataset]
train = [x[1:] for x in dataset]
test = genfromtxt(open('test.csv','r'), delimiter=',', dtype='f8')[1:]
poly = PolynomialFeatures(degree=2)
train_poly = poly.fit_transform(train)
test_poly = poly.fit_transform(test)
clf = linear_model.LinearRegression()
clf.fit(train_poly, target)
savetxt('polyreg_test1.csv', clf.predict(test_poly), delimiter=',', fmt='%f')
I wanted to know if there was a way to output a summary of the regression like in Excel ? I explored the attributes/methods of linear_model.LinearRegression() but couldn't find anything.
A:
This is not implemented in scikit-learn; the scikit-learn ecosystem is quite biased towards using cross-validation for model evaluation (this a good thing in my opinion; most of the test statistics were developed out necessity before computers were powerful enough for cross-validation to be feasible).
For more traditional types of statistical analysis you can use statsmodels, here is an example taken from their documentation:
import numpy as np
import statsmodels.api as sm
nsample = 100
x = np.linspace(0, 10, 100)
X = np.column_stack((x, x**2))
beta = np.array([1, 0.1, 10])
e = np.random.normal(size=nsample)
X = sm.add_constant(X)
y = np.dot(X, beta) + e
model = sm.OLS(y, X)
results = model.fit()
print(results.summary())
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 1.000
Model: OLS Adj. R-squared: 1.000
Method: Least Squares F-statistic: 4.020e+06
Date: Sun, 01 Feb 2015 Prob (F-statistic): 2.83e-239
Time: 09:32:32 Log-Likelihood: -146.51
No. Observations: 100 AIC: 299.0
Df Residuals: 97 BIC: 306.8
Df Model: 2
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [95.0% Conf. Int.]
------------------------------------------------------------------------------
const 1.3423 0.313 4.292 0.000 0.722 1.963
x1 -0.0402 0.145 -0.278 0.781 -0.327 0.247
x2 10.0103 0.014 715.745 0.000 9.982 10.038
==============================================================================
Omnibus: 2.042 Durbin-Watson: 2.274
Prob(Omnibus): 0.360 Jarque-Bera (JB): 1.875
Skew: 0.234 Prob(JB): 0.392
Kurtosis: 2.519 Cond. No. 144.
==============================================================================
| {
"pile_set_name": "StackExchange"
} |
Q:
Strange bug in +IE8
Please take a look at this page via IE 8 or 9: http://sneakyrascal.com/starpons/about.html
As seen there are two footers but in fact I only added one footer. I figured it's connected with <a> tag. when I remove it, it will work fine.
Thanks in advance for any help
A:
You open a new a instead of closing it:
<a href="images/Ruby_BIS_0011.jpg" class="iframe" ><img src="images/Ruby_BIS_0011-300x234.jpg" /><a>
You should have found this when using a the validator.
| {
"pile_set_name": "StackExchange"
} |
Q:
find curvature of an image of a mug in PIL?
I am trying to paste an image over a mug no there will there stills left, center, right of the mug on each of them I have to show the part of the image pasted. Now the mug on a 2-D screen has some curvature, So the image pasted will also have to have the same curvature. How do I do this?? One thing I thought is if somehow I can find out the curvature of the bottom part I can maintain the same distance and paste each small part by cropping every time and then pasting it again at same distance from the bottom curvature???
A:
There is a bash script called cylinderize that uses ImageMagick to achieve this effect.
So depending on what exactly your goal is, you could either just use this script or try to reverse engineer the algorithm they used.
I think the algorithm you described might not result in a realistic looking picture. You only apply the distortion in the y direction and ignore the distortion in the x direction.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I convert a comma-delimited list into a select box
I have a variable that has more than one value in it. The output of the list is like this:
Output1, Output2, Output3, Output4, Output5
I use the the <cfset varpo = "#output#">
How can I convert this output to a select box with the value of each options same as the name.
Ps: The output list is automatically gotten from the server in that format.
It's like I haven't seen any answered question to this because none worked.
A:
<cfset list= "Output1, Output2, Output3, Output4, Output5" />
<cfset arr = listToArray (list, ",") />
<cfset len = ArrayLen( arr ) />
<select>
<cfloop from="1" to="#len#" index="idx" >
<option><cfoutput>#arr[idx]#</cfoutput></option>
</cfloop>
</select>
OR
<select>
<cfloop list="Output1, Output2, Output3, Output4, Output5" index="item">
<option><cfoutput>#item#</cfoutput></option>
</cfloop>
</select>
| {
"pile_set_name": "StackExchange"
} |
Q:
Wordpress Multisite redirecting to wp-signup.php
I have recently set up a second blog on my Wordpress multisite. The primary blog on the Multisite is www.example.com, and the second blog I have set up two days ago is www.example2.org.
Unfortunately, when going to www.example2.org, WordPress redirects to https://www.example.com/wp-signup.php?new=
On the same server, I have set up a corresponding test Multisite, with test.example.com being the primary blog and test.example2.org the second blog. It is working without a problem.
The Multisite-related .htaccess and wp-config.php settings are the same for both the test and the live Multisite, so that wouldn't be the problem. I've also verified that on the live Multisite I have www.example2.org correctly set in the wp_blogs table, and also it is correctly set as https://www.example2.org on the siteurl and home rows of the wp_2_options table (the _2_ part corresponding to the blog ID on the Multisite).
I would appreciate any suggestions on why this redirect is happening and/or how to resolve it. I don't even know which file is issuing the redirect (I don't think it's wp-signup.php) so I can't look at the relevant code to debug it further.
A:
After many hours of debugging and despair, the problem is now solved. It turned out to be a very obscure thing.
The redirect is issued by the function ms_load_current_site_and_network() inside /wp-includes/ms-load.php. It was issuing the redirect because /wp-includes/ms-settings.php was not able to set a domain. The reason it was not able to set a domain is because $_SERVER['HTTP_HOST'] was not set.
$_SERVER['HTTP_HOST'] not being set had to do with the PHP setting auto_globals_jit. It was set to On, resulting in the $_SERVER array not being set (as explained in this comment). Even though $_SERVER['HTTP_HOST'] and the rest were defined when loading a single php file with phpinfo(); in it, they were not defined when loading Wordpress's php files. And that led to the redirect.
Setting auto_globals_jit to Off in php.ini resolved it.
Bonus info:
The issue was additionally made more complicated by some form of caching (which I couldn't pin down or clear). So I had to rely on behavior that I saw occur only once and couldn't replicate afterwards. For example, I created a separate php file to just check if $_SERVER['HTTP_HOST'] is set - and initially it wasn't. Following the suggestion from the comment, I used $_SERVER['HTTP_HOST'] twice in the php file - and immediately saw that it was now set. However, when reverting the change and having $_SERVER['HTTP_HOST'] only once in the php file, it still remained set - suggesting I was seeing a cached response. I coulnd't get it to break again after I fixed it once.
Just documenting this here in case someone encounters similar behavior.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proguard with Reflection
I've got a question regarding Proguard. I'm pretty new to using it and was wondering conceptually what classes in your project should you keep via the Proguard config txt file?
As far as I can tell the only ones that really matter are classes in which reflection is used. Such as if you use Sugar ORM then any subclasses of SugarRecord should be kept. Same if you use OkHttp3 to convert a class to JSON.
I guess I am just wondering what other "gotchas" are there to look for?
Thanks!
A:
Libs you use often have specified Proguard rules so copy it to your rules. You should keep classes where you use reflection. Where you specify class names or fields by string.
For example you should keep api models and their fields because they are serialized from e.g json. (If you use Gson you can use @SerializedName annotation)
| {
"pile_set_name": "StackExchange"
} |
Q:
What conditions are required to say $\lim \int |f_n - g_n| =0$, where $f_n, g_n$ : PDFs of random variable.
Is there hint/reference, that the conditions to be met in order to say
$$\lim \int |f_n - g_n| =0$$
$f_n, g_n$ : PDFs of random variables, $X_n, Y_n$.
Is it sufficient to show that $X_n \to c$, $Y_n \to c$, both almost surely?
A:
If $X_n$ and $Y_n$ have the same density function i.e. $(f_n=g_n)$ then $\int|f_n-g_n|=0$ for all
$n$. Your condition that the random variables have the same constant limit is completely unnecessary.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java CLI UI-design: frameworks or libraries?
I'm currently working on a small utility program that only requires a command line interface, and I started wondering if Java provided any standard way of creating the CLI, in a similar way that Swing and the likes exist for GUIs. I'm not really interested in command line parameters and parsing of them, but rather the command based interaction the user has with the program to use it. This is for the situations where GUI simply is unnecessary or not an option for using the program.
Googling the subject pretty much only results in tutorials on how to use BufferedReader and the likes to do rudimentary interaction with the user, aimed at people learning the basics of Java and writing simple UI that asks for name and prints "Hello World!" etc..
Are the any libraries that are focused on providing a good framework for quickly implementing a more complex CLI UI or is this really something that everyone implements in ad hoc manner for their own utilities?
Maybe someone knows of patterns for the implementation that were created back in time when not everything was graphical? That would also be useful resource.
A:
You can also have a look and Clamshell-cli or spring shell:
Clamshell-cli is relatively simple and easy to use : You can look at jmx-cli to get a nice example of what can be done with it.
Spring Shell is bigger but more feature-full (tab completion, etc). It has been extracted from spring Roo and released as an independent framework
A:
Perhaps CLI Toolkit...
http://alexis.royer.free.fr/CLI/
A:
There is a project called JLine that provides cross-platform support for general command-line input handling:
http://jline.sourceforge.net/
More of a support library than a framework though.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generic data structure libraries for C?
Which libraries do you guys use for generic data structures like linked list, binary tree etc.?
What are the most common, efficient libraries? Can you name some?
A:
GDSL - The Generic Data Structures Library
Gnulib - The GNU Portability Library
GLib
SGLIB
| {
"pile_set_name": "StackExchange"
} |
Q:
How to resolve LVL obfuscation error
I have a project that I've been using proguard with successfully for a long time, purposely running with an older version of ADB (pre r12) because I always seem to hit errors that take too long to resolve. I recently updated to r16, and doing so completely broke my ability to build on the command line using -> "ant release"
I found an overload of information that allowed me to resolve multiple problems, but now I have the following problem, and I've none of the suggestions I've tried has worked:
[dx] UNEXPECTED TOP-LEVEL EXCEPTION:
[dx] java.lang.IllegalArgumentException: already added: Lcom/android/vend
ing/licensing/AESObfuscator;
[dx] at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection
.java:123)
[dx] at com.android.dx.dex.file.DexFile.add(DexFile.java:163)
[dx] at com.android.dx.command.dexer.Main.processClass(Main.java:486)
[dx] at com.android.dx.command.dexer.Main.processFileBytes(Main.java:
455)
[dx] at com.android.dx.command.dexer.Main.access$400(Main.java:67)
[dx] at com.android.dx.command.dexer.Main$1.processFileBytes(Main.jav
a:394)
[dx] at com.android.dx.cf.direct.ClassPathOpener.processArchive(Class
PathOpener.java:245)
[dx] at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPath
Opener.java:131)
[dx] at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpe
ner.java:109)
[dx] at com.android.dx.command.dexer.Main.processOne(Main.java:418)
[dx] at com.android.dx.command.dexer.Main.processAllFiles(Main.java:3
29)
[dx] at com.android.dx.command.dexer.Main.run(Main.java:206)
[dx] at com.android.dx.command.dexer.Main.main(Main.java:174)
[dx] at com.android.dx.command.Main.main(Main.java:95)
[dx] 1 error; aborting
BUILD FAILED
C:\Users\Public\android_sdk_r3\android-sdk-windows\tools\ant\build.xml:752: The
following error occurred while executing this line:
C:\Users\Public\android_sdk_r3\android-sdk-windows\tools\ant\build.xml:754: The
following error occurred while executing this line:
C:\Users\Public\android_sdk_r3\android-sdk-windows\tools\ant\build.xml:766: The
following error occurred while executing this line:
C:\Users\Public\android_sdk_r3\android-sdk-windows\tools\ant\build.xml:256: null
returned: 1
I know that it's saying AESObfuscator is being added twice, but I'm not sure of all the various places that it is being pulled in to my project. Other posts referencing this problem resulted in people providing many different possible solutions. I'm hoping someone can tell me definitively what to remove.
LVL's jar file is listed under "Reference Libraries." I manually copied the jar file to the libs folder to resolve other errors I encountered. Right-clicking my project and selecting "Properties" -> "Java Build Path" -> "Libraries" has the LVL jar file, Android 2.2, and com.android.ide.eclipse.adt.LIBRARIES. Initially "Libraries" had Android 2.2 and "Reference Libraries" but I manually removed reference libraries at someone else's suggestion, but this caused errors in Eclipse. I then manually added the LVL jar back in "Libraries" by selecting "Add external JAR" and the result was the 3 items above.
What do I need to do to resolve this? Thanks.
A:
There were a few different things I did to get everything working, but unfortunately I'm uncertain if there was one certain step that did the trick.
I deleted the extra src folders that were added for each library I had after performing the upgrade.
I stopped using LVL as an external library, and just added the source code directly to my project.
In Eclipse, I went into Properties -> Android, and in the Library section of the window that appears I deleted all references.
There were specific errors that were shown in Eclipse for the proguard files being used in my project, but those were easily identified and corrected.
At this point I thought everything should have worked, but I still had problems. So I cleaned the project, and suddenly everything worked fine. So, it appears that I needed to take each of the above steps in order to solve my problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to download World MODIS image from ESRI ImageServer?
I need to download the following dataset that is available online in ESRI website: https://sampleserver3.arcgisonline.com/ArcGIS/rest/services/World/MODIS/ImageServer. I can view the map in arcmap as instructed but I need to download the original raster so that I can further process. This layer has 12 files of 12 different months.
A:
The layer provided by ESRI is designed for "view-only" purpose. I don't think you can download the actual data using it. USGS is probably the way to go if you want to get the actual MODIS data.
| {
"pile_set_name": "StackExchange"
} |
Q:
Windows 8 bottom app bar
I've been trying to get an App bar implemented in a WinRT metro app (C# / XAML), but don't know where to begin. I've tried using the <ApplicationBar/> tag and I get a Type not found error.
There's no help online, could someone update this post with the answer so that it'll serve as a reference to other programmers as well?
There's only a JavaScript sample which isn't of much help.
A:
This should work:
<AppBar
VerticalAlignment="Bottom">
<Button
AutomationProperties.Name="Play"
Style="{StaticResource PlayAppBarButtonStyle}"
Command="{Binding PlayCommand}" />
</AppBar>
– you would put that in the layout root grid of your page.
*EDIT
Note: According to documentation - you should put it in Page.BottomAppBar property, although at least in Windows 8 Consumer Preview - it works fine when used in any Grid, which is convenient if your UI isn't tightly coupled to a Page control.
*EDIT 2, response from MSFT:
The recommended approach is to use the Page.BottomAppBar/TopAppBar properties.
There are known hit-testing issues in the Consumer Preview if AppBars are added without using these properties
The AppBars do not use the proper animations if they are added without using these properties
If AppBars are added as children of arbitrary elements then it's easier for multiple controls to attempt to create/modify AppBars, resulting in an inconsistent user experience
*EDIT 3
The CustomAppBar in WinRT XAML Toolkit can be used anywhere, animates based on Vertical/Horizontal-Alignment, can have other content overlaid on top of it and also has a CanOpen property that allows to block it from opening.
| {
"pile_set_name": "StackExchange"
} |
Q:
Incorporating JavaScript into HTML to create a pantone-style column
I'm trying to make a pantone-style column, with one totally red div and the others all decreasing shades of that red. Basically, I've got a variable 'op' for opacity, that starts at 1 and decreases until it's equal to .1. Here's the code that I use (on Codepen). '.column' is my big container, and '.box' is for all the smaller divs. My issue is that the editor doesn't recognize 'op' as part of the div's style. How can I fix this?
var op = 1;
for (var i = 0; i <= 10; i++) {
$('.column').append('<div class="box", style="opacity:op;">Hello.</div>')
op = op - .1
}
A:
var op = 1;
for (var i = 0; i <= 10; i++) {
$('.column').append('<div class="box", style="opacity:'+op+';">Hello.</div>')
op = op - .1
}
Insert the variable
Javascript doesn't have a native string parser like most other languages.
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS 7 - Restrict landscape orientation only in one view controller
I need to open the first view controller only in portrait mode. As the rest view controllers will use both orientation. So i have added both orientation in plist file.
-(BOOL) shouldAutorotate {
//Never called
}
- (NSUInteger) supportedInterfaceOrientations {
//Never called
}
can any one tell me how to restrict
A:
Fixed it simply by creating UINavigationController class and overriding
-(NSUInteger)supportedInterfaceOrientations
{
AppDelegate *appDelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
if(appDelegate.isOrientationOn) {
return UIInterfaceOrientationMaskAll;
}
return UIInterfaceOrientationMaskPortrait;
}
Use this custom navigation controller class in root window and that's all.
| {
"pile_set_name": "StackExchange"
} |
Q:
Factor subset of finite group
Let $G$ be a group of order $n$ and $d$ a positive divisor of $n$. Is it true that there exists a subset $A$ of $G$ with $d$ elements and a subset $B$ such that $G=AB$ and $|AB|=|A||B|$ (equivalently, the product $AB$ is direct)?
Note: If $G$ has the property that there exists a subgroup of $G$ with order $d$ or $n/d$, then we can show that the answer is positive (see
A question about finite groups (a weak version of the converse of Lagrange theorem)).
Now, is the answer positive for
${\rm PSL}(2,8)$, ${\rm PSL}(2,11)$, ${\rm PSL}(2,13)$, ${\rm SL}(2,11)$, ${\rm SL}(2,13)$,
${\rm PSL}(2,17)$, ${\rm A}_7$, ${\rm PSL}(2,19)$, ${\rm A}_5 \times {\rm A}_5$?
About $PSL_2(8)$ (in the last following comment, by Russ Woodroofe). If it has subgroups of indexes $6$, $14$ and $21$ with the property $P(*,*)$, then we can say that $PSL_2(8)$ has $P(*,*)$. Note that $PSL_2(8)$ has subgroups of indexes $6$ (that is solvable and so $P(*,*)$ is true for it), $14$ (that is also solvable) and $21$ (with order $84$). Now, is $P(*,*)$ valid for the last subgroup? (if yes, then $PSL_2(8)$ has $P(*,*)$).
A:
This is true for solvable groups, at least. We are given a group $G$ of order $ab$, where $a$ and $b$ are integers, and we want subsets $A$ and $B$ of $G$ such that $|A| = a$,
$|B| = b$ and $G = AB$. We work by induction on $|G|$ to prove that $A$ and $B$ exist if $G$ is solvable. We can certainly assume that $|G| > 1$. Since $G$ is solvable, it has a subgroup $H$ of prime index $p$, and we can assume without loss that $p$ divides $b$. Then $|H| = (a)(b/p)$, so by the inductive hypothesis, we can write $H = AX$, where $|A| = a$ and $|X| = b/p$. Now let $T$ be a set of representatives for the right cosets of $H$ in $G$. Then $|T| = p$ and
$G = HT = AXT$. Let $B = XT$, so $AB = G$. Also, $|B| = |XT| \le |X||T| = (b/p)p = b$. Equality must hold here since $AB = G$.
A:
You can handle several of the groups on the list from your edit with a modification of the argument of Marty Isaacs. For the rest, you can find guidance as to what a counterexample would look like.
Say that $G$ satisfies $P(a,b)$ if $ab = |G|$ and there are subsets $A$ and $B$ of cardinalities $a$ and $b$ such that $G = AB$. Write $P(*,*)$ when $G$ satisfies $P(a,b)$ for any $a,b$ with $ab = |G|$.
The following has exactly the same proof as the solvable argument.
Lemma: If $H$ is a subgroup of $G$ satisfying $P(a,b)$, and $[G:H] = t$, then $G$ satisfies $P(a,bt)$.
Then if $G$ has a maximal subgroup of prime index satisfying $P(*,*)$, then $G$ also satisfies $P(*,*)$. That handles $A_5$, $PSL_2(7)$, and $A_5 \times A_5$.
Moreover, if $G$ has a maximal subgroup of index $t$, then $G$ satisfies $P(a,b)$ for every pair $a,b$ with t dividing $b$ (and of course $ab=|G|$).
This lets us handle $A_6$, which has maximal subgroups of index 6, 10, and 15. If $ab = 60$ then either $a$ or $b$ is divisible by one of these.
$A_7$ then follows, since $A_6$ is a maximal subgroup of $A_7$ having (prime) index 7.
Similar (but slightly more involved) arguments to those for $A_6$ show that $A_8$ satisfies $P(*,*)$.
The first open case is $PSL_2(8)$, which has order $504 = 2^3 \cdot 3^2 \cdot 7$, and maximal subgroups with indices 9, 28, and 36. Since every subgroup satisfies $P(*,*)$, the possible places where $PSL_2(8)$ could fail $P(*,*)$ are $P(12, 42)$ and $P(21, 24)$.
By the way, GAP will calculate the relevant data for these arguments for you pretty easily. The following commands will do it (replace $G$ with your favorite group):
G:=PSL(2,7);; Print(Size(G), " = ", FactorsInt(Size(G)), "\n"); Set(List(MaximalSubgroups(G), x->Index(G, x)));
| {
"pile_set_name": "StackExchange"
} |
Q:
GoogleMaps iOS SDK GMSMapView Class Deallocated
I am working on integrating the GoogleMaps iOS SDK into my project and I keep getting this error:
'NSInternalInconsistencyException' 'An instance 0x7fea5e93e210 of
class GMSMapView was deallocated while key value observers were still
registered with it. Current observation info:
Here's my view controller code:
import UIKit
import GoogleMaps
class ViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
var locationManager = CLLocationManager()
var didFindMyLocation = false
let mapView = GMSMapView()
override func viewDidLoad() {
super.viewDidLoad()
let mapView = GMSMapView()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
let camera: GMSCameraPosition = GMSCameraPosition.cameraWithLatitude(37.61729,longitude: -122.38229, zoom: 18)
mapView.camera = camera
mapView.delegate = self
mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if !didFindMyLocation {
let myLocation: CLLocation = change![NSKeyValueChangeNewKey] as! CLLocation
mapView.camera = GMSCameraPosition.cameraWithTarget(myLocation.coordinate, zoom: 18.0)
mapView.settings.myLocationButton = true
didFindMyLocation = true
}
}
}
A:
Just as it says: "key value observers were still registered with it", which is essentially complaining that you didn't un-register the KVO observer.
KVO, in this sense, is kinda like NSNotification - if you registered an observer in, say, viewDidLoad:, you need to remove the observer in, say, viewDidDisappear: or dealloc.
In your case, try to add dealloc function and use removeObserver:forKeyPath:context: to unsubscribe from KVO. Read more at mattt's article for KVO here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is this element selecting itself?
I'm trying to highlight a list item immediately preceded by the item being hovered.
<ul>
<li><a href="#">link</a></li> <!-- this one should be highlighted when... -->
<li><a href="#">link</a></li> <!-- ...this one is hovered -->
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
</ul>
However, the selector I'm using, li + li:hover, for some reason is selecting itself.
li:hover + li selected the li immediately following the one hovered, but I need the one immediately before it. Am I using the wrong selector?
Here's a fiddle demonstrating the problem:
A:
CSS combinators can only access descendants and later siblings. They cannot access previous ones.
Once CSS4 comes around, you can do this:
!li! + li:hover
(Note: syntax is not finalised, as far as I know)
However, in the mean time, try this:
ul, ul>li {transform:scaleY(-1)}
And reverse the order of items in the list.
Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
Control not initialized in Edge/IE on Page_Init()
Is there a different order of calling the constructors for controls depending on the browser brand?
In my project there is a DevExpress Captcha control, it's rendered in a MyForm.aspx page. When I open the app in Chrome/Firefox, it works fine, there is a random string inside Code property, but when I open the same page in Edge/IE, it is always null (even inside Page_Init), so it returns false always.
I thought maybe there is different order of calling the constructor for this control depending on the browser, what else could be the reason that this control is not initialized in some browsers and others yes?
public partial class MyForm: System.Web.UI.Page
{
private string CaptchaCode { get; set; }
protected void Page_Init(object sender, EventArgs e)
{
CaptchaCode = Captcha.Code;
}
protected void btnPurchaseCardSecurity_Click(object sender, EventArgs e)
{
// line breaks added for readability. [ed]
Captcha.IsValid = string.Equals(Request.Params["Captcha$TB"]
.Replace('o', '0').Replace('i', 'l'), CptCode,
StringComparison.CurrentCultureIgnoreCase);
}
Bellow is the control in aspx
<dx:ASPxCaptcha ID="Captcha" runat="server">
<ChallengeImage />
</dx:ASPxCaptcha>
A:
I am still struggling to get this working on Edge/IE but so far I have discovered what's causing the trouble. DevExpress captcha component might not be working when you access the page via HTTP instead of HTTP protocol IF inside the web.config requireSSL is set to true. So for now, everything shows up using HTTP, it just doesn't transfer the initialized value of the captcha UI-serverside wise in Edge, but it does in Chrome and Firefox.
I can't access the site using HTTPS.
ASPxCaptcha does not work with HTTP when RequireSSL is set in the web.config
ASPxCaptcha does not work with HTTP when RequireSSL is set to True in the web.config, because cookies are secured in this case and ASPxCaptcha cannot get the session ID that is stored in them.
Thus, it is necessary to use HTTPS in this case.
For all those having a similar problem go check out this link for other possible solutions:
https://www.devexpress.com/Support/Center/Question/Details/KA18582/how-to-resolve-issues-with-aspxcaptcha
One of the things that helped is going to project properties > Web > Servers and replacing Project URL's HTTP to HTTPS from the URL of the project. Than VS asked me to install SSL certificate. Accessing the site via https and everything works!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to query enum flags using bitwise operators in Linq to NHibernate
I have a problem where a bitwise operation on a query like the following generates N+1 selects:
var files = (from f in Session.Query<File>()
where f.ProjectID == id && ((f.State & FileState.WaitingForFile) == FileState.WaitingForFile)
select f;
Instead of generating the expected SQL, NHibernate performs N+1 selects (all rows in File) and tests the binary condition on the client. The issue seems to be linked with Lazy loading as NHibernateProfiler shows the following culprit in its stack trace: FileProxy.get_State
How do I get NHibernate to generate the correct SQL (Where ProjectID = x AND State & y = y) ?
Detailed information follows:
I am using NHibernate 3.2.0.4.
Here are the classes I'm using:
public class File
{
public virtual int ID { get; set; }
public virtual int ProjectID { get; set; }
public virtual AttachedFileType AttachedFileType { get; set; }
public virtual FileState State { get; set; }
[...]
}
[Flags]
public enum FileState
{
None = 0x0,
Available = 0x1,
WaitingForFile = 0x2,
Archived = 0x4,
[...]
}
Thank you for your time.
A:
I found the problem: I was actually running the query on an entity's ISet instead of from Session.Query() as in my simplified example. This caused the select N+1 pattern when accessing f.State through lazy loading.
Whoops :)
| {
"pile_set_name": "StackExchange"
} |
Q:
generate a "create table" sql command based on an existing table in mysql
I have a mysql shell but for security reasons I cannot run the mysqldump command.
I have a table that I made a while ago with a lot of columns, and I want to generate a new "create table" command to create that table on a different database.
Is there some command I can run in the mysql shell to generate that?
Thanks.
A:
This should work:
SHOW CREATE TABLE tbl_name
You should have SELECT privileges for the table.
A:
FYI, if your user has access to both databases on the same server, you can do this:
CREATE TABLE db2.tablename LIKE db1.tablename;
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove apt repository?
Some while ago I may have accidentally added an apt repository with an invalid URL. Now, every time I run sudo apt update, the following error message shows at the bottom:
E: The repository 'http://archive.canonical.com (lsb_release Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
I've tried using sudo add-apt-repository --remove 'http://archive.canonical.com (lsb_release Release', after running the command there was no difference. How can I remove this url from my apt repository list?
Edit: The url http://archive.canonical.com (lsb_release Release is not found in my /etc/apt/sources.list
The following gist contains both the contents of /etc/apt/sources.list as well as the output of sudo apt update
https://gist.github.com/MrSiliconGuy/4ae2c649e5133f7edff012bfd6483d70
Edit: Turns out it was the line deb http://archive.canonical.com/ (lsb_release -sc) partner
You cannot have shell commands in your apt source file
A:
The repositories are stored in a file located at /etc/apt/sources.list.
You can edit that to suit your needs.
| {
"pile_set_name": "StackExchange"
} |
Q:
MUL instruction doesn't support an immediate value
I've read a few tutorials and examples, but I cannot wrap my head around how the MUL instruction works. I've used ADD and SUB without problems. So apparently this instruction multiplies its operand by the value in a register.
What register (eax, ebp, esp, etc.) is multiplied by the first operand? And what register is the result stored in, so I can move it to the stack? Sorry, I'm just learning x86 assembly.
When I try to compile this line...
mul 9
I get, Error: suffix or operands invalid for 'mul'. Can anyone help me out?
global main
main:
push ebp
movl ebp, esp
sub esp, byte +8
mov eax, 7
mul 9
mov [esp], eax
call _putchar
xor eax, eax
leave
ret
A:
MUL can't use an immediate value as an argument. You have to load '9' into a register, say,
movl $7, %eax
movl $9, %ecx
mull %ecx
which would multiply eax by ecx and store the 64-bit product in edx:eax.
There's a good comprehensive reference of x86 assembly instructions on the Intel web site, see here
http://www.intel.com/Assets/PDF/manual/253666.pdf
http://www.intel.com/Assets/PDF/manual/253667.pdf
But that is probably far more information that you need now.
A:
http://siyobik.info/index.php?module=x86&id=210
the destination operand is an implied
operand located in register AL, AX or
EAX (depending on the size of the
operand); the source operand is
located in a general-purpose register
or a memory location
The result is stored in register AX,
register pair DX:AX, or register pair
EDX:EAX (depending on the operand
size), with the high-order bits of the
product contained in register AH, DX,
or EDX, respectively. If the
high-order bits of the product are 0,
the CF and OF flags are cleared;
otherwise, the flags are set.
In your source it should be mul instead of mull
A:
I'm not an expert but I think your problem is that mul will not accept a direct operand in your case the decimal constant 9 so try putting 9 in let's say register bx like this:
mov bx, 9
mul bx
To answer your question about mul in general it looks like this:
mul reg/memory
and does that:
dx:ax := ax*reg/mem
So with words it expects a single operand which should either be a register or a memory location (storing the value to be multiplied so essentially a variable) and multiplies it by ax and then depending on how long the register/memory (so the operand you gave) was stores it in either ax or dx:ax or edx:eax
I hope I helped you there pal!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert plus (+) sign to "=+" with htaccess?
I want to convert every url which contains "+" to "=+"
for example that url:
http://www.bedavaemlaksitesi.com/mersinemlakrehberi210/index3.php?+
should be like this:
http://www.bedavaemlaksitesi.com/mersinemlakrehberi210/index3.php?=+
tried that and few other lines but doesn't work so far, i'm guessing it causes a loop or something.
RewriteRule ^([^/\.]+)+([^/\.]+)?$ $1=+$2 [R]
A:
I'm just gonna give you a literal answer for that specific example. Not sure if that will actually help you:
RewriteCond %{QUERY_STRING} ^([+])$
RewriteRule /index3.php$ index3.php?=(%1) [R,L]
You cannot repleace each + in the QS, as you do need a separate condition to match it first.
Also about your original rule:
RewriteRule ^([^/\.]+)+([^/\.]+)?$ $1=+$2 [R]
Escaping the dot in the charclass is redundant, [^/.] suffices. And you need at least a separator between the two groups / to make sense. But you can't match the query_string there, that's handled separately from the current filepath.
See alsos: ServerFault: Everything You Ever Wanted to Know about Mod_Rewrite Rules but Were Afraid to Ask? -and- HttpdWiki: Manipulating the Query String
| {
"pile_set_name": "StackExchange"
} |
Q:
Angularjs $httpd assign variable onSuccess to $scope empty
I have a controller:
.controller('myController', ['$scope','$http', function ($scope,$http,) {
$scope.saveit = function () {
$scope.key = '';
$http.get('/getHash',{"key": $scope.key})
.success(function(response, status, headers, config){
$scope.key = response.key;
});
}
console.log ($scope.key) // key is empty
}
Why is at the end $scope.key empty?
A:
It won't be set until you actually call saveit(), which you won't have done yet when your log statement is executed. You've defined a function that sets key, but you haven't invoked it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Set TextBlock's text to string plus binding item?
I have a ListView with multiple TextBlocks in it. Is it possible to have something such as this?
TextBlock x:Name="AuthorInfo" Text="Author: {Binding data.author}"
or would it be better to just add it to data.author when that is set?
A:
If it's XAML you could use StringFormat
<TextBox Text="{Binding Path=data.author, StringFormat=Author: {0}}"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
Continuous functions that satisfies $f(x) + f(1-x) + f(\sqrt{x^2+(1-x)}) = 0$ and $f(\frac12)=0$
$f:[0,1]\rightarrow \mathbb{R}$ is a continuous function which satisfies
$$
f(x) + f(1-x) + f\left(\sqrt{x^2+(1-x)}\right) = 0 \text{ and } f\left(\tfrac12\right)=0.
$$
Can someone give explicit examples of $f$, apart from the trivial solution, $f(x)=0$? And are there infinitely many solutions for $f$?
I can derive some properties like $f(\frac{\sqrt3}2)=0$ or $f(0)=-2f(1)$, but I can't generate particular examples. Continuity seems important here, but I can't see how to use it, for if we take $f(x)=0$, for $x\in (0,1)$, and $f(1)=1$, $f(0)=-2$ also works.
A:
First, notice that $\sqrt{x^2+1-x}\geq\sqrt{3}/2$ for all $x\in[0,1]$. Let $g:[1/2,\sqrt{3}/2]\to\mathbb R$ be an arbitrary continuous function such that $g(1/2)=g(\sqrt{3}/2)=0$. Then, define $f:[0,1]\to\mathbb R$ as follows:
\begin{align*}
f(x)=\begin{cases}
0&\text{if $x\in[0,1-\sqrt{3}/2]$,}\\
-g(1-x)&\text{if $x\in(1-\sqrt{3}/2,1/2]$,}\\
g(x)&\text{if $x\in(1/2,\sqrt{3}/{2}]$,}\\
0&\text{if $x\in(\sqrt{3}/2,1]$.}
\end{cases}
\end{align*}
For example:
| {
"pile_set_name": "StackExchange"
} |
Q:
Drawing Google Fusion Tables on Esri Silverlight Map?
I've been asked to add drawing support for Google Fusion Tables to an Esri Silverlight map application. For example this one showing Full-Year Stream Temperature Monitoring Sites for the Western US.
Ideally, I'd like to be able to handle this just like any other mapservice layer by providing the url and add it to the map.
Does anyone know of an easy way to do this?
A related question is: would doing this be a violation of the Google Fusion Table Terms of Service?
5.3. You agree not to access (or attempt to access) any of the
Services by any means other than through the interface that is
provided by Google, unless you have been specifically allowed to do so
in a separate agreement with Google.
Does this mean I have to use Googles javascript API method if I want to show layers from fusion tables?
A:
You can wrap the Fusion Table in the Open GeoServices REST api and make it look like a native AGS MapServer or FeatureServer. That's pretty much what Arc2Earth Sync will do for you automatically for your Fusion Tables or Earth Builder layers (in addition to synchronizing with a local FGDB)
The FT table you described above has an ID of 1236296
AGS FeatureServer (direct query of vector data via FT SQL API)
http://beta.arc2cloud.com/9280826/ArcGIS/rest/services/gft/1236296/FeatureServer/0/
AGS MapServer (uses the FT generated tiles, not sure this will be allowed in the future)
http://beta.arc2cloud.com/9280826/ArcGIS/rest/services/gft/1236296/MapServer
Saved map from ArcGIS.com with the feature server added:
http://bit.ly/o4hNQc
cheers
brian
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS / Soundcloud API - Downloading track from Soundcloud API without stream_url request
Part of my iOS app is playing songs downloaded from Soundcloud with the help of their API. However, the songs are fully downloaded then played, not streamed. When the GET request is sent using the stream_url, the request takes extremely long to load into an AVAudioPlayer (I guess because of the 128kb/s cap on a track that is over an hour long), and the request using download_url does not work, most likely because downloading on the track is setup to only be accessible through a Facebook Band page.
I was curious if there is a faster way to download a track with these 2 options eliminated. Otherwise, is there a way to start streaming the song while the rest of the song loads into the player. For example, can I load the first 5 minutes of a track into a temporary player and then when the other player fully loads, have it take over the playing? The Soundcloud tracks being accessed are all from a friend, so I can ask him to change account options if necessary.
A:
I have found a really good answer here to speed up the playing using AVPlayer.
Soundcloud iOS API - playing sound from link
I've tried already and the response is really good!
The code is:
NSString *trackID = @"100026228";
NSString *clientID = @"YOUR_CLIENT_ID";
NSURL *trackURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.soundcloud.com/tracks/%@/stream?client_id=%@", trackID, clientID]];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:trackURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// self.player is strong property
self.player = [[AVAudioPlayer alloc] initWithData:data error:nil];
[self.player play];
}];
[task resume];
A:
you need to use streaming technique instead of AVAudioPlayer . You can use AudioStreamer to allow playing audio while the loading. this solve my problem
| {
"pile_set_name": "StackExchange"
} |
Q:
AttributeError: 'str' object has no attribute 'sign'
When I run my python script, it gives me the following error. Not sure how to resolve it. I think so either the problem is in the version of python, I am using python 3.6 or It could be some packages not included. Please see the included image for error.
Thanks.
Error
Code:
f = open('c:\ExamCreator\My Project-9352ed298182.json')
key = f.read()
f.close()
credentials = ServiceAccountCredentials(
'CLIENT_EMAIL', key,
scope=
'https://www.googleapis.com/auth/admin.directory.user',
sub='[email protected]'
)
http = httplib2.Http()
http = credentials.authorize(http)
userinfo = {
'primaryEmail': '[email protected]',
'name': {
'givenName':'John','familyName':'Smith'
},
'password': 'Hello1'
}
service = build("admin", "directory_v1", http=http)
service.users().insert(body=userinfo).execute()
A:
It appears that signer is being interpreted as a string, which inherently is just...a string. Not a dict or a list, both of which have attrs. Please post the function that is throwing this error. Also, this SO question and answer may be relevant to your interests.
| {
"pile_set_name": "StackExchange"
} |
Q:
In OS X, how does manually sandboxing an application from the internet compare to blocking it with Little Snitch?
I want to prevent inbound and outbound connections to one application. I can buy Little Snitch if it's the best option, but it feels like I wouldn't be getting much value out of it for that one use.
I've been trying to read up on OSX's ability to manually sandbox applications from functions you can specify. I'm wondering if this is something worth pursuing - meaning will it be as good (or more effective) than Little Snitch to block one application only, and how complex is it to set up for an OS X novice?
I've been trying to work out exactly how to go about this. 'man sandbox-exec' probably tells me all I need to know, but I need more dumbed-down steps of the whole process if possible.
A:
For most purposes, the following is good enough for most situations:
sandbox-exec -n no-network command
However, it's not more effective—there's numerous ways of apps escaping the sandbox. Little Snitch also lets you be more specific with what you are blocking—specific ports/etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Microsoft Outlook 2003 Search Tools
Does anyone know of any free add-ons for Microsoft Outlook 2003 or later that will allow you to search email?
A:
Lookout which MS bought for some purpose is still available at Major Geeks. It was a great tool. Probably won't work for anything later than 2003 but I'm not sure.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using if statements in for loops
Currently I am using an if statement inside of a for loop counting an array
for(count = 0; count < order.length; count++)
{
if(order[count] == "")
{
alert("You must select an item");
return false;
}
else
{
$.mobile.changePage();
$("#idTag").after("<p>"+order[count]+"<p/>");
}
}
My issue is that if order[0] has information in it and if any other array index has no information the alert will still run when I don't want it to. Is there anyway to make sure that once the array is checked it just runs through the else statement without going back to the if statement.
Any help would be appreciated
John
A:
Maintain a flag
var flag = 0;
for(count = 0; count < order.length; count++)
{
if(order[count] == "" && flag == 0)
{
alert("You must select an item");
break;
}
else
{
flag = 1;
$.mobile.changePage();
}
}
if(flag == 1)
return false;
| {
"pile_set_name": "StackExchange"
} |
Q:
A question concerning series of functions.
Suppose $\sum_1^\infty a_n$ converges. Then is it true that $\sum_1^\infty b_n$ is convergent and $b_n$ goes to zero as $n\to \infty$? Here $b_n =a_{n+1}-a_n$.
I trued for some counter examples but did not get any. Thanks in advance.
A:
Your partial sums will be telescopic, that is $b_1+b_2+\dots+b_n=(a_2-a_1)+(a_3-a_2)+(a_4-a_3)+\dots+(a_{n+1}-a_n)=a_{n+1}-a_1$ (Observe how the intermediate terms are cancelling each other). Now since $\sum_na_n$ converges, $a_n\to 0$, therefore $b_1+\dots+b_n=a_{n+1}-a_1\to -a_1$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unpacking list values to a text
I a list, that I want to unpack to a part of text.
The goal is eventually exporting the text to a txt file and then to use VPN to implement it to our database.
The text is this:
'"name": "----"',
'"lei": " "',
'"parentId": "0"',
'"status": "ACTIVE"',
'"type": "1"',
'"country": "----"',
'"region": "1"',
'"address": "----"',
'"domains": "None"'
It started from a DataFrame that I turned into a list, so basically each value in each of the lists is correlated to the same one with the same index in the other lists.
The goal is to have 318 texts like the one I wrote that each text will have the 3 values.
The lists are - "Name", "Country", "Address"
I thought of using map with a for loop but I'm not so sure how to make that happen.
Any suggestions?
A:
I think you could use python's string formatting to achieve what you are trying to do, and, as you suggested, use map to perform the task on all your files.
The idea is to write a generic text, like the one you presented, replacing the "----" fields by "{0}", "{1}", "{2}" fields. Then, applying text.format(name, country, adress) will fill the fields, in that order, with the contents of the name, country and adress fields.
To map it, you will also want to unpack a tuple containing the arguments, using the splat operator (*) : text.format(*tuple_of_arguments).
Thus, an acceptable solution is to use a code of the following form:
list_of_tuples = [
('nameA', 'countryA', 'adressA'),
('nameB', 'countryB', 'adressB')
] # fill this, and maybe use a generator instead (e.g. using zip)
for e in map(lambda x : text.format(*x), list_of_tuples):
# do what you want of the formatted text stored in e
I hope this helps !
| {
"pile_set_name": "StackExchange"
} |
Q:
Possible large data set from subquery?
I can't show you my exact problem and query due to its complexity, but I will simplify the problem into another alike one.
Here goes:
There are 5 tables, containing information about apples, cars, books, computers and clothes. Each table from the above can have comments and all the comments are stored inside a single table called Comments (with a user_id column). And to link those 5 tables with their own comments I had to create 5 other link tables names AppleComments, CarComments, BookComments, and so on.
My query wants to retrieve all my comments from those 5 category types.
I can think of 2 ways, one faster than the other.
I can join the 5 tables with its linking table and then with comments where comments.user_id = me and then UNION ALL the results into 1 result set:
SELECT <column_names> FROM AppleComments
INNER JOIN Comments ON AppleComments.comment_id = Comments.comment_id
WHERE Comments.user_id = me
UNION ALL
SELECT <column_names> FROM CarComments
INNER JOIN Comments ON CarComments.comment_id = Comments.comment_id
WHERE Comments.user_id = me
etc...
I can select all the comment id-s from the linkin tables with union all and then inner join this subquery with the Comments table to get the other info about them.
SELECT <column_names>
FROM (
Select AppleComments.comment_id FROM AppleComments
UNION ALL
Select CarComments.comment_id FROM CarComments
UNION ALL
Select BookComments.comment_id FROM BookComments
UNION ALL
Select ComputerComments.comment_id FROM ComputerComments
UNION ALL
Select ClothesComments.comment_id FROM ClothesComments) AS items
INNER JOIN Comments ON items.comment_id = Comments.comment_id
WHERE Comments.user_id = me
The second one is faster and produces a smaller execution plan.
The problem is, since the subquery 'items' from ex. 2 selects all the comments from the database actually and then inner joins with the comments table, my concern is that it will poorly perform when dealing with too many rows. Maybe too much memory?
Right now I can't tell since 90% of the comments are mine, but judging a little bit each example, I'd say the 1st one is the one that retrieves smaller amounts of data (per total).
What if there are 1 million comments in the DB and only 100 of mine...
Thanks.
A:
Your intuition is correct. UNION ALL will pretty much obliterate chances of optimisation down the road. Do everything you can before unioning; the first approach is the right one.
Except it's begging the question of why do you have similar things in five different tables, and why do you even have linking tables in what appears to be a 1-to-n relationship? Would a single table with a itemtype field not suffice? If you have extra data, then have optional foreign links to additional data tables, is what I'd do...
Of course, this is a made-up universe, I don't have a clue about your original problem :)
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I remove tab bar when user navigates to another screen?
My goal is simply to remove my app's tab bar whenever the user navigates to a specific screen, so that I have more space available.
Currently, my storyboard looks like this:
Whenever the user clicks a button they will be taken to another screen, which is the last screen in the sequence. My goal is to simply remove the tab bar, but keep the navigation.
If I use a show detail segue, then it will remove the tab bar but also the navigation, which is something I don't want.
This is the final screen (but it still has tab bar):
A:
You can even set the property hidesBottomBarWhenPushed equal to true on your DestinationViewController. You can do it in your prepareForSegue method override.
if let vc = segue.destinationViewController as? YOURVIEWCONTROLLER {
vc.hidesBottomBarWhenPushed = true
}
In this way, if the ViewController should need the bottom bar in other cases, it'll be shown
A:
All you need it to set hidesBottomBarWhenPushed = true on the view controller you want it to be hidden on. insert in viewDidLoad()
You can also set this in the storyboard of the children view controllers
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I parse a primitive of a Json File?
I have the following JSON file from a Get Request:
{
"vcalendar": [
{
"version": "2.0",
"prodid": " CalendarID",
"vevent": [
{
"uid": " EventID",
"dtstamp": "20180725T000000",
"status": "CONFIRMED",
"dtstart": [
"20180213",
{
"value": "DATE"
}
],
"dtend": [
"20180214",
{
"value": "DATE"
}
],
"summary": " Event subject",
"description": "Event description"
}
]
}
],
"success": true
}
And I want to get the dtstart and dtend primitive number in this case it would be "20180213" and "20180214", but I can't deserialize the JSON File how I usually do it in order to get the information I want.
To get the other values I use:
public class iCalendarFile
{
public List<iCalendar> vcalendar { get; set; }
}
public class iCalendar
{
public List<iCalendarEvent> vevent { get; set; }
}
public class iCalendarEvent
{
public string summary { get; set; }
public string description { get; set; }
public List<string> dtstart { get; set; }
public List<string> dtend { get; set; }
}
And deserialize it like that:
public static async void makeGetRequest(TraceWriter log) {
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
var result = reader.ReadToEnd();
var jsonObject = JsonConvert.DeserializeObject<iCalendarFile>(result);
foreach (iCalendar icalobject in jsonObject.vcalendar ) {
foreach (iCalendarEvent Object in icalobject.vevent)
{
foreach(String tmp in Object.dtstart){
log.Info(tmp);
}
}
}
reader.Close();
dataStream.Close();
response.Close();
}
My Error is:
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'vcalendar[0].vevent[0].dtstart[0]', line 1, position 238.
at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
at Newtonsoft.Json.JsonTextReader.ReadAsString()
at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
If you have any Idea how to access the value in dtstart I would be grateful. Thanks for your help!
A:
At the first change JSON Class with that (https://jsonutils.com/)
#region JsonClass
public class Vevent
{
public string uid { get; set; }
public string dtstamp { get; set; }
public string status { get; set; }
public IList<object> dtstart { get; set; }
public IList<object> dtend { get; set; }
public string summary { get; set; }
public string description { get; set; }
}
public class Vcalendar
{
public string version { get; set; }
public string prodid { get; set; }
public IList<Vevent> vevent { get; set; }
}
public class iCalendarFile
{
public IList<Vcalendar> vcalendar { get; set; }
public bool success { get; set; }
}
#endregion
After That u can:
var jsonObject = JsonConvert.DeserializeObject<iCalendarFile>(sb);
for (int i = 0; i < jsonObject.vcalendar[0].vevent[0].dtstart.Count; i++)
{
Console.WriteLine(jsonObject.vcalendar[0].vevent[0].dtstart[i].ToString());
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Bash Console commands (Codeship console): how to exit from current "inputs"
Excuse me for the imprecisions in the question but I don't know how it is called what I'm trying.
In the CodeShip documentation is stated that I can pass to the SSH CodeShip debug build some commands using their command line application.
So, I should do something like cs setup-commands and I'm prompted with this:
rof@railsonfire_unique_string_sfivbe8bwucb9:~$ cs setup-commands
Your setup commands:
phpenv local 5.6
phpenv local 5.6
In Your setup commands: I put my commands but then, how can I "execute" them?
The second phpenv local 5.6 line is wrote by the command-line application. I think is something to signal the command were taken, but the behavior is ever the same: I remain "blocked" in the command setup-commands. After setting setup-commands I have to set also test-commands but all the things I write are taken by Your setup commands:.
How can I "submit and exit" the command setup-commands to then launch test-commands and set those other commands?
I think this is something related to Bash, but I don't know what it is...
And I don't know which is the correct terminology.
Can someone help me with this? So I will can also update my question to be more precise. Thank you.
A:
Not sure about your case, but usually the input is considered finished, when th input file (in your case stdin) is closed.
Try to press Ctrl+D, it should end your input (and so signal the program hat you stopped typing for this session)
| {
"pile_set_name": "StackExchange"
} |
Q:
Загрузить фотографию по url в альбом сообщества (vk api)
Подскажите, что не так делаю? Вот код:
class Model_Vk {
private $access_token;
private $url = "https://api.vk.com/method/";
/**
* Конструктор
*/
public function __construct($access_token) {
$this->access_token = $access_token;
}
/**
* Делает запрос к Api VK
* @param $method
* @param $params
*/
public function method($method, $params = null) {
$p = "";
if( $params && is_array($params) ) {
foreach($params as $key => $param) {
$p .= ($p == "" ? "" : "&") . $key . "=" . urlencode($param);
}
}
$response = file_get_contents($this->url . $method . "?" . ($p ? $p . "&" : "") . "v=" . VK_API_VERSION ."&". "access_token=" . $this->access_token);
if( $response ) {
return json_decode($response);
}
return false;
}
public function uploadImage($file, $group_id = null, $album_id = null) {
$params = array();
if( $group_id ) {
$params['group_id'] = $group_id;
}
if( $album_id ) {
$params['album_id'] = $album_id;
}
//Получаем сервер для загрузки изображения
$response = $this->method("photos.getUploadServer", $params);
if( isset($response) == false ) {
print_r($response);
exit;
}
$server = $response->response->upload_url;
// file_put_contents('img.jpg', file_get_contents($file));
// $file = dirname(__FILE__) . '/img.jpg';
$postparam=array("file1"=>"@".$file);
//$postparam = new CURLFile($file);
print_r($postparam);
echo '<br>';
//Отправляем файл на сервер
$ch = curl_init($server);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postparam);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; charset=UTF-8'));
$json = json_decode(curl_exec($ch));
curl_close($ch);
print_r($json);
echo '<br>';
//Сохраняем файл в альбом
$photo = $this->method("photos.save", array(
"server" => $json->server,
"photos_list" => $json->photos_list,
"album_id" => $album_id,
"hash" => $json->hash,
"gid" => $group_id
));
print_r($photo);
echo '<br>';
if( isset($photo->response[0]->id) ) {
return $photo->response[0]->id;
} else {
return false;
}
}
}
До того как пытаюсь передать url картинки на сервер происходит нормально (получаю токен, адрес сервера), но после передачи постом картинки на адрес сервера возвращает пустой массив photos_list, url картинки вида https://cdn.thesolesupplier.co.uk/2017/09/MITA-x-ASICS-GT-II-Squirrel-Brown-05.png, в чем проблема?
A:
В комментариях вам указал основные ваши проблемы с реализацией, для того, чтобы загрузить фотографию на сервер VK, фотография должна быть уже на вашем сервере, и, для дальнейшей загрузки, вы должны указать полный путь к этой фотографии. Сначала сохраняете фото на своем сервере, потом загружаете уже в VK.
Касаемо вашей модели, теория хорошая, но реализация ужасная. По недавно оставленному моему ответу касаемо загрузки фотографий на сервер ВК, можно набросать несложный класс:
class Model_VK
{
public $access_token, $v;
const API = 'https://api.vk.com/method/';
public function __construct($access_token, $v)
{
$this->access_token = $access_token;
$this->v = $v;
}
public function uploadImage($file, $group_id = null, $album_id = null)
{
list($params['group_id'], $params['album_id']) = [$group_id, $album_id];
$upl = $this->vk('photos.getUploadServer', $params)->response->upload_url;
if (isset($upl))
{
$upload = json_decode($this->curl($upl, ['file1' => new CURLFile($file)]));
if (isset($upload->server))
{
$photo = $this->vk('photos.save', [
'server' => $upload->server,
'photos_list' => $upload->photos_list,
'album_id' => $album_id,
'hash' => $upload->hash,
'group_id' => $group_id
]);
print_r($photo);
}
}
}
public function vk($method, $params)
{
list($params['access_token'], $params['v']) = [$this->access_token, $this->v];
return json_decode($this->curl(self::API . $method, $params));
}
public function curl($url, $params = false)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if (isset($params))
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
$upd = curl_exec($ch);
curl_close($ch);
return $upd;
}
}
Имея это, создаем экземпляр класса и обращаемся к функции uploadImage:
$new = new Model_VK('token_user', '5.85');
$new->uploadImage(__DIR__.'/photo.jpg', 158853183, 251951515);
После загрузки фотографии в альбом, на экран будет выведен результат. Вот и все :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Marcar checkboxes quando escolher valor do select, vindo de um BD em PHP (Laravel)
Estou com um problema que não sei como resolver e não sei como procurar.
Estou construindo um sistema no php - laravel.
Este sistema terá níveis de usuários.
Já fiz toda a parte de cadastros, alterações, visualizações dos usuários, grupos e permissões.
Porém, travei em uma parte que provavelmente terei que usar javascript, mas tenho conhecimento muito básico em JS.
Na hora de adicionar um usuário, tenho um SELECT com os grupos (ex. ADMIN, USERS...) e uma lista de checkbox com as permissões gerais ( de todos os grupos)... até ai tranquilo, consigo selecionar o grupo e quais premissoes eu quero.
Mas precisava fazer o seguinte:
Que quando eu selecionasse (ex. ADMIN) no select, o JS já preenchesse todas as permissões que o ADMIN tem direito, e aí o usuário pudesse selecionar manualmente se deseja mais alguma permissão ou não.
Preciso fazer isso pois quando adicionar o usuário, preciso saber quais permissões são de direito de cada grupo, para assim, saber qual devo cadastrar.
A:
Eu recomendaria que tu fizesse uma requisição AJAX para buscar um JSON com as permissões padrões.
Por exemplo, podes criar uma rota no Laravel ('/permissoes/{grupo}') que tu pode verificar qual o grupo e retorna o JSON, naõ sei como tu salvou isso no BD, mas a princípio é só selecionar e retornar que o LAravel monta o JSON.
No teu script, quando vier o data com a resposta deste AJAX, tu percorre num forEach este JSON, para cada entrada padrão, tu busca pelo DOM usando jQuery e seta este checkbox como marcado (checked).
Um evento no select para quando o valor mudar, ele buscar as permissões padrões pela AJAX e tá feito.
Se quiser fazer mais hardcoded ainda e ignorar o AJAX, pode colocar estes JSON com as permissões de cada grupo num array no teu próprio script, vai evitar as requisições para buscar o JSON mas é uma solução menos elegante do meu ponto de vista.
| {
"pile_set_name": "StackExchange"
} |
Q:
populate custom listview from audio files inside a folder
I'm trying to get files from a folder and populate recyclerview based on the name of files using a custom adapter.
This is how I'm doing it:
In onBindViewHolder:
Product m = dataList.get(position);
//title
holder.title.setText(m.getTitle());
And :
void popList() {
Product product = new Product();
File dir = new File(mainFolder);//path of files
File[] filelist = dir.listFiles();
String[] nameOfFiles = new String[filelist.length];
for (int i = 0; i < nameOfFiles.length; i++) {
nameOfFiles[i] = filelist[i].getName();
product.setTitle(nameOfFiles[i]);
}
songList.add(product);
}
But the problem is, it just adds the first item.
I can't figure it out where should I loop to add it all.
A:
You need to create separate product objects for items in loop and add it to list instead of creating a single Product object in list which will hold the last set data
void popList() {
Product product ;
File dir = new File(mainFolder);//path of files
File[] filelist = dir.listFiles();
String[] nameOfFiles = new String[filelist.length];
for (int i = 0; i < nameOfFiles.length; i++) {
// create product
product = new Product();
nameOfFiles[i] = filelist[i].getName();
product.setTitle(nameOfFiles[i]);
// add it to list
songList.add(product);
}
}
Your code walk through
void popList() {
Product product = new Product(); // one object
// ..code
for (int i = 0; i < nameOfFiles.length; i++) {
nameOfFiles[i] = filelist[i].getName();
product.setTitle(nameOfFiles[i]); // at the end of loop set last file name to object
}
songList.add(product); // one object in the list , end of story
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make a batch file to execute win rar in multiple folders
Iam really new to batch files so pls bear with me.
I want to make a batch file that can take folders from different locations and then zip it in to one win rar file in a location like
c:\projects\test
c:\www\site
c:\logs\office
to
c:backup\{{date}}_backup.rar
thanx in advance
A:
@echo off
(
echo c:\projects\test
echo c:\www\site
echo c:\logs\office
)>list.txt
"%programfiles%\winrar\rar" a "c:\backup\%date:/=-%_backup.rar" @list.txt
If you are on Win-x64 set the rar path: "%programfiles(x86)%\winrar\rar"
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Wallace Keefe know Lex Luthor's plan in Batman v. Superman?
I was re-watching Batman V Superman: Dawn of Justice the other day, and I was thinking...
Did Wallace Keefe (the former Wayne employee who was crippled when the building collapsed) know that Lex Luthor had embedded a bomb in his high-tech wheelchair? On first watch, I just figured Wallace knew but then I realized he doesn't really have a reason to know. Lex said he wanted Wallace to "stand for something" but wouldn't Wallace have assumed speaking in front of the Senator was the "stance" Lex wanted him to take? It also seemed like Lex's assistant didn't know the bomb was a plan either.
A:
UPDATE:
This might only be from the Ultimate Edition, not the Theatrical Cut
No, Wallace did not know that Lex embedded a bomb in his wheel chair.
If you remember from the movie, after the bomb in the wheel chair happened.. police and Lois went and inspected Wallace's home and Lois noticed that his refrigerator was full of fresh groceries and the fruit that was in the bowls was still fresh.
So, with observing that.. one could ask why would Wallace recently buy groceries if he knew he was going to die? I believe Lois said in the movie that 'he didn't know he was going to die'.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to add bloc in the top of columns.yaml
I am new to octobercms,i am trying to create a know plugin to add a statistics in the top of all my columns.yaml, how can I do that without add a htm bloc in all my columns list
enter image description here
A:
Please read https://octobercms.com/docs/plugin/extending#extending-backend-list
You can extend the columns, you can extend the fields, etc.. a lot of it, but not the header. I also checked in the code, but there is no programmatical way to extend the header that's laid out in the documentation or code.
You need to find another way to interface with those classes or columns than the way you had tought out
| {
"pile_set_name": "StackExchange"
} |
Q:
Return json on exit php
I have been using $.getJSON in order to verify if a script has done its job properly, using exit("{'status':true}") (or false) but now I need the script to return a value (or an array). I see that I can't use exit('{ "status": $myarray}');. What can I use instead? I am new to php- is it possible to do something like return '{ "status": $myarray}'; or something alike?
Thanks in advance
A:
You can use the following function:
json_encode($data);
See:
http://php.net/manual/en/function.json-encode.php
A:
In your php, use json_encode as such:
<?php
header('Content-Type: application/json');
echo json_encode($myarray);
// or, `exit(json_encode($myarray))` if global scope (see *REF)
?>
and in your jQuery use getJSON normally:
$.getJSON("test.php",function(result){
...
});
(*) REF: PHP - exit or return which is better?
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I solve this problem. (error: Cannot find getter for field.)
I have a problem. I clone this github project. https://github.com/SimpleMobileTools/Simple-Calendar
Then I update Kotlin in Android Studio. When I run project, I take errors and I didn't solve them.
That are errors when I build it:
22:51:20: Executing task 'build'...
Executing tasks: [build]
:app:checkDebugClasspath UP-TO-DATE
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:compileDebugAidl NO-SOURCE
:app:compileDebugRenderscript UP-TO-DATE
:app:checkDebugManifest UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:mainApkListPersistenceDebug UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:createDebugCompatibleScreenManifests UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:splitsDiscoveryTaskDebug UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:kaptGenerateStubsDebugKotlin UP-TO-DATE
e: C:\Users\Ayberk\Simple-Calendar\app\build\tmp\kapt3\stubs\debug\com\simplemobiletools\calendar\pro\models\Event.java:11: error: Cannot find getter for field.
private java.lang.Long id;
^
e: C:\Users\Ayberk\Simple-Calendar\app\build\tmp\kapt3\stubs\debug\com\simplemobiletools\calendar\pro\models\Event.java:39: error: Cannot find getter for field.
private java.lang.String importId;
^
e: C:\Users\Ayberk\Simple-Calendar\app\build\tmp\kapt3\stubs\debug\com\simplemobiletools\calendar\pro\models\EventType.java:10: error: Cannot find getter for field.
private java.lang.Long id;
^
e: C:\Users\Ayberk\Simple-Calendar\app\build\tmp\kapt3\stubs\debug\com\simplemobiletools\calendar\pro\models\EventRepetition.java:10: error: Cannot find getter for field.
private java.lang.Long id;
^
e: C:\Users\Ayberk\Simple-Calendar\app\build\tmp\kapt3\stubs\debug\com\simplemobiletools\calendar\pro\models\EventRepetitionException.java:10: error: Cannot find getter for field.
private java.lang.Long id;
^
:app:kaptDebugKotlin
w: C:\Users\Ayberk\Simple-Calendar\app\build\tmp\kapt3\stubs\debug\com\simplemobiletools\calendar\pro\databases\EventsDatabase.java:7: warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false.
public abstract class EventsDatabase extends androidx.room.RoomDatabase {
^
:app:kaptDebugKotlin FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> Compilation error. See log for more details
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUİLD FAILED in 4s
14 actionable tasks: 1 executed, 13 up-to-date
22:51:25: Task execution finished 'build'.
This is first errors' generated java class:
package com.simplemobiletools.calendar.pro.models;
import java.lang.System;
@androidx.room.Entity(tableName = "events", indices = {@androidx.room.Index(unique = true, value = {"id"})})
@kotlin.Metadata(mv = {1, 1, 13}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000X\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\t\n\u0000\n\u0002\u0010\b\n\u0002\b\u0002\n\u0002\u0010\u000e\n\u0002\b(\n\u0002\u0010\u000b\n\u0002\b\u001c\n\u0002\u0010\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0019\n\u0002\u0010\u0000\n\u0002\b\u0003\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0010 \n\u0002\b\u0003\n\u0002\u0018\u0002\n\u0002\b\u0004\b\u0087\b\u0018\u0000 z2\u00020\u0001:\u0001zB\u00b9\u0001\u0012\b\u0010\u0002\u001a\u0004\u0018\u00010\u0003\u0012\b\b\u0002\u0010\u0004\u001a\u00020\u0005\u0012\b\b\u0002\u0010\u0006\u001a\u00020\u0005\u0012\b\b\u0002\u0010\u0007\u001a\u00020\b\u0012\b\b\u0002\u0010\t\u001a\u00020\b\u0012\b\b\u0002\u0010\n\u001a\u00020\b\u0012\b\b\u0002\u0010\u000b\u001a\u00020\u0005\u0012\b\b\u0002\u0010\f\u001a\u00020\u0005\u0012\b\b\u0002\u0010\r\u001a\u00020\u0005\u0012\b\b\u0002\u0010\u000e\u001a\u00020\u0005\u0012\b\b\u0002\u0010\u000f\u001a\u00020\u0005\u0012\b\b\u0002\u0010\u0010\u001a\u00020\u0005\u0012\b\b\u0002\u0010\u0011\u001a\u00020\b\u0012\b\b\u0002\u0010\u0012\u001a\u00020\u0005\u0012\b\b\u0002\u0010\u0013\u001a\u00020\u0003\u0012\b\b\u0002\u0010\u0014\u001a\u00020\u0003\u0012\b\b\u0002\u0010\u0015\u001a\u00020\u0003\u0012\b\b\u0002\u0010\u0016\u001a\u00020\b\u00a2\u0006\u0002\u0010\u0017J\u000e\u0010M\u001a\u00020N2\u0006\u0010O\u001a\u00020\u0000J\u0018\u0010P\u001a\u00020Q2\u0006\u0010R\u001a\u00020Q2\u0006\u0010O\u001a\u00020\u0000H\u0002J \u0010S\u001a\u00020Q2\u0006\u0010R\u001a\u00020Q2\u0006\u0010O\u001a\u00020\u00002\u0006\u0010T\u001a\u000201H\u0002J\u0010\u0010U\u001a\u0004\u0018\u00010\u0003H\u00c6\u0003\u00a2\u0006\u0002\u0010*J\t\u0010V\u001a\u00020\u0005H\u00c6\u0003J\t\u0010W\u001a\u00020\u0005H\u00c6\u0003J\t\u0010X\u001a\u00020\u0005H\u00c6\u0003J\t\u0010Y\u001a\u00020\bH\u00c6\u0003J\t\u0010Z\u001a\u00020\u0005H\u00c6\u0003J\t\u0010[\u001a\u00020\u0003H\u00c6\u0003J\t\u0010\\\u001a\u00020\u0003H\u00c6\u0003J\t\u0010]\u001a\u00020\u0003H\u00c6\u0003J\t\u0010^\u001a\u00020\bH\u00c6\u0003J\t\u0010_\u001a\u00020\u0005H\u00c6\u0003J\t\u0010`\u001a\u00020\u0005H\u00c6\u0003J\t\u0010a\u001a\u00020\bH\u00c6\u0003J\t\u0010b\u001a\u00020\bH\u00c6\u0003J\t\u0010c\u001a\u00020\bH\u00c6\u0003J\t\u0010d\u001a\u00020\u0005H\u00c6\u0003J\t\u0010e\u001a\u00020\u0005H\u00c6\u0003J\t\u0010f\u001a\u00020\u0005H\u00c6\u0003J\u00c4\u0001\u0010g\u001a\u00020\u00002\n\b\u0002\u0010\u0002\u001a\u0004\u0018\u00010\u00032\b\b\u0002\u0010\u0004\u001a\u00020\u00052\b\b\u0002\u0010\u0006\u001a\u00020\u00052\b\b\u0002\u0010\u0007\u001a\u00020\b2\b\b\u0002\u0010\t\u001a\u00020\b2\b\b\u0002\u0010\n\u001a\u00020\b2\b\b\u0002\u0010\u000b\u001a\u00020\u00052\b\b\u0002\u0010\f\u001a\u00020\u00052\b\b\u0002\u0010\r\u001a\u00020\u00052\b\b\u0002\u0010\u000e\u001a\u00020\u00052\b\b\u0002\u0010\u000f\u001a\u00020\u00052\b\b\u0002\u0010\u0010\u001a\u00020\u00052\b\b\u0002\u0010\u0011\u001a\u00020\b2\b\b\u0002\u0010\u0012\u001a\u00020\u00052\b\b\u0002\u0010\u0013\u001a\u00020\u00032\b\b\u0002\u0010\u0014\u001a\u00020\u00032\b\b\u0002\u0010\u0015\u001a\u00020\u00032\b\b\u0002\u0010\u0016\u001a\u00020\bH\u00c6\u0001\u00a2\u0006\u0002\u0010hJ\u0013\u0010i\u001a\u0002012\b\u0010j\u001a\u0004\u0018\u00010kH\u00d6\u0003J\u0006\u0010l\u001a\u00020\u0005J\u0006\u0010m\u001a\u00020\u0003J\u0006\u0010n\u001a\u00020oJ\u0006\u0010p\u001a\u00020\u0005J\u0006\u0010q\u001a\u000201J\f\u0010r\u001a\b\u0012\u0004\u0012\u00020\u00050sJ\t\u0010t\u001a\u00020\u0005H\u00d6\u0001J\u0014\u0010u\u001a\u0002012\f\u0010v\u001a\b\u0012\u0004\u0012\u00020\u00050wJ\t\u0010x\u001a\u00020\bH\u00d6\u0001J\u0006\u0010y\u001a\u00020NR\u001a\u0010\u0018\u001a\u00020\u0005X\u0086\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b\u0019\u0010\u001a\"\u0004\b\u001b\u0010\u001cR\u001e\u0010\n\u001a\u00020\b8\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b\u001d\u0010\u001e\"\u0004\b\u001f\u0010 R\u001e\u0010\u0006\u001a\u00020\u00058\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b!\u0010\u001a\"\u0004\b\"\u0010\u001cR\u001e\u0010\u0013\u001a\u00020\u00038\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b#\u0010$\"\u0004\b%\u0010&R\u001e\u0010\u0012\u001a\u00020\u00058\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b\'\u0010\u001a\"\u0004\b(\u0010\u001cR\"\u0010\u0002\u001a\u0004\u0018\u00010\u00038\u0006@\u0006X\u0087\u000e\u00a2\u0006\u0010\n\u0002\u0010-\u001a\u0004\b)\u0010*\"\u0004\b+\u0010,R\u001e\u0010\u0011\u001a\u00020\b8\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b.\u0010\u001e\"\u0004\b/\u0010 R$\u00100\u001a\u0002012\u0006\u00100\u001a\u0002018F@FX\u0086\u000e\u00a2\u0006\f\u001a\u0004\b0\u00102\"\u0004\b3\u00104R\u001e\u0010\u0015\u001a\u00020\u00038\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b5\u0010$\"\u0004\b6\u0010&R\u001e\u0010\t\u001a\u00020\b8\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b7\u0010\u001e\"\u0004\b8\u0010 R\u001e\u0010\u0014\u001a\u00020\u00038\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b9\u0010$\"\u0004\b:\u0010&R\u001e\u0010\u000b\u001a\u00020\u00058\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b;\u0010\u001a\"\u0004\b<\u0010\u001cR\u001e\u0010\f\u001a\u00020\u00058\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b=\u0010\u001a\"\u0004\b>\u0010\u001cR\u001e\u0010\r\u001a\u00020\u00058\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b?\u0010\u001a\"\u0004\b@\u0010\u001cR\u001e\u0010\u000e\u001a\u00020\u00058\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\bA\u0010\u001a\"\u0004\bB\u0010\u001cR\u001e\u0010\u0010\u001a\u00020\u00058\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\bC\u0010\u001a\"\u0004\bD\u0010\u001cR\u001e\u0010\u000f\u001a\u00020\u00058\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\bE\u0010\u001a\"\u0004\bF\u0010\u001cR\u001e\u0010\u0016\u001a\u00020\b8\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\bG\u0010\u001e\"\u0004\bH\u0010 R\u001e\u0010\u0004\u001a\u00020\u00058\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\bI\u0010\u001a\"\u0004\bJ\u0010\u001cR\u001e\u0010\u0007\u001a\u00020\b8\u0006@\u0006X\u0087\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\bK\u0010\u001e\"\u0004\bL\u0010 \u00a8\u0006{"}, d2 = {"Lcom/simplemobiletools/calendar/pro/models/Event;", "Ljava/io/Serializable;", "id", "", "startTS", "", "endTS", "title", "", "location", "description", "reminder1Minutes", "reminder2Minutes", "reminder3Minutes", "repeatInterval", "repeatRule", "repeatLimit", "importId", "flags", "eventType", "parentId", "lastUpdated", "source", "(Ljava/lang/Long;IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIIILjava/lang/String;IJJJLjava/lang/String;)V", "color", "getColor", "()I", "setColor", "(I)V", "getDescription", "()Ljava/lang/String;", "setDescription", "(Ljava/lang/String;)V", "getEndTS", "setEndTS", "getEventType", "()J", "setEventType", "(J)V", "getFlags", "setFlags", "getId", "()Ljava/lang/Long;", "setId", "(Ljava/lang/Long;)V", "Ljava/lang/Long;", "getImportId", "setImportId", "isPastEvent", "", "()Z", "setPastEvent", "(Z)V", "getLastUpdated", "setLastUpdated", "getLocation", "setLocation", "getParentId", "setParentId", "getReminder1Minutes", "setReminder1Minutes", "getReminder2Minutes", "setReminder2Minutes", "getReminder3Minutes", "setReminder3Minutes", "getRepeatInterval", "setRepeatInterval", "getRepeatLimit", "setRepeatLimit", "getRepeatRule", "setRepeatRule", "getSource", "setSource", "getStartTS", "setStartTS", "getTitle", "setTitle", "addIntervalTime", "", "original", "addMonthsWithSameDay", "Lorg/joda/time/DateTime;", "currStart", "addXthDayInterval", "forceLastWeekday", "component1", "component10", "component11", "component12", "component13", "component14", "component15", "component16", "component17", "component18", "component2", "component3", "component4", "component5", "component6", "component7", "component8", "component9", "copy", "(Ljava/lang/Long;IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIIILjava/lang/String;IJJJLjava/lang/String;)Lcom/simplemobiletools/calendar/pro/models/Event;", "equals", "other", "", "getCalDAVCalendarId", "getCalDAVEventId", "getEventRepetition", "Lcom/simplemobiletools/calendar/pro/models/EventRepetition;", "getEventStartTS", "getIsAllDay", "getReminders", "", "hashCode", "isOnProperWeek", "startTimes", "Landroidx/collection/LongSparseArray;", "toString", "updateIsPastEvent", "Companion", "calendar_debug"})
public final class Event implements java.io.Serializable {
private int color;
@org.jetbrains.annotations.Nullable()
@androidx.room.PrimaryKey(autoGenerate = true)
private java.lang.Long id;
@androidx.room.ColumnInfo(name = "start_ts")
private int startTS;
@androidx.room.ColumnInfo(name = "end_ts")
private int endTS;
@org.jetbrains.annotations.NotNull()
@androidx.room.ColumnInfo(name = "title")
private java.lang.String title;
@org.jetbrains.annotations.NotNull()
@androidx.room.ColumnInfo(name = "location")
private java.lang.String location;
@org.jetbrains.annotations.NotNull()
@androidx.room.ColumnInfo(name = "description")
private java.lang.String description;
@androidx.room.ColumnInfo(name = "reminder_1_minutes")
private int reminder1Minutes;
@androidx.room.ColumnInfo(name = "reminder_2_minutes")
private int reminder2Minutes;
@androidx.room.ColumnInfo(name = "reminder_3_minutes")
private int reminder3Minutes;
@androidx.room.ColumnInfo(name = "repeat_interval")
private int repeatInterval;
@androidx.room.ColumnInfo(name = "repeat_rule")
private int repeatRule;
@androidx.room.ColumnInfo(name = "repeat_limit")
private int repeatLimit;
@org.jetbrains.annotations.NotNull()
@androidx.room.ColumnInfo(name = "import_id")
private java.lang.String importId;
@androidx.room.ColumnInfo(name = "flags")
private int flags;
@androidx.room.ColumnInfo(name = "event_type")
private long eventType;
@androidx.room.ColumnInfo(name = "parent_id")
private long parentId;
@androidx.room.ColumnInfo(name = "last_updated")
private long lastUpdated;
@org.jetbrains.annotations.NotNull()
@androidx.room.ColumnInfo(name = "source")
private java.lang.String source;
private static final long serialVersionUID = -32456795132345616L;
public static final com.simplemobiletools.calendar.pro.models.Event.Companion Companion = null;
public final void addIntervalTime(@org.jetbrains.annotations.NotNull()
com.simplemobiletools.calendar.pro.models.Event original) {
}
private final org.joda.time.DateTime addMonthsWithSameDay(org.joda.time.DateTime currStart, com.simplemobiletools.calendar.pro.models.Event original) {
return null;
}
private final org.joda.time.DateTime addXthDayInterval(org.joda.time.DateTime currStart, com.simplemobiletools.calendar.pro.models.Event original, boolean forceLastWeekday) {
return null;
}
public final boolean getIsAllDay() {
return false;
}
@org.jetbrains.annotations.NotNull()
public final java.util.List<java.lang.Integer> getReminders() {
return null;
}
public final int getEventStartTS() {
return 0;
}
public final long getCalDAVEventId() {
return 0L;
}
public final int getCalDAVCalendarId() {
return 0;
}
@org.jetbrains.annotations.NotNull()
public final com.simplemobiletools.calendar.pro.models.EventRepetition getEventRepetition() {
return null;
}
public final boolean isOnProperWeek(@org.jetbrains.annotations.NotNull()
androidx.collection.LongSparseArray<java.lang.Integer> startTimes) {
return false;
}
public final void updateIsPastEvent() {
}
public final boolean isPastEvent() {
return false;
}
public final void setPastEvent(boolean isPastEvent) {
}
public final int getColor() {
return 0;
}
public final void setColor(int p0) {
}
@org.jetbrains.annotations.Nullable()
public final java.lang.Long getId() {
return null;
}
public final void setId(@org.jetbrains.annotations.Nullable()
java.lang.Long p0) {
}
public final int getStartTS() {
return 0;
}
public final void setStartTS(int p0) {
}
public final int getEndTS() {
return 0;
}
public final void setEndTS(int p0) {
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String getTitle() {
return null;
}
public final void setTitle(@org.jetbrains.annotations.NotNull()
java.lang.String p0) {
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String getLocation() {
return null;
}
public final void setLocation(@org.jetbrains.annotations.NotNull()
java.lang.String p0) {
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String getDescription() {
return null;
}
public final void setDescription(@org.jetbrains.annotations.NotNull()
java.lang.String p0) {
}
public final int getReminder1Minutes() {
return 0;
}
public final void setReminder1Minutes(int p0) {
}
public final int getReminder2Minutes() {
return 0;
}
public final void setReminder2Minutes(int p0) {
}
public final int getReminder3Minutes() {
return 0;
}
public final void setReminder3Minutes(int p0) {
}
public final int getRepeatInterval() {
return 0;
}
public final void setRepeatInterval(int p0) {
}
public final int getRepeatRule() {
return 0;
}
public final void setRepeatRule(int p0) {
}
public final int getRepeatLimit() {
return 0;
}
public final void setRepeatLimit(int p0) {
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String getImportId() {
return null;
}
public final void setImportId(@org.jetbrains.annotations.NotNull()
java.lang.String p0) {
}
public final int getFlags() {
return 0;
}
public final void setFlags(int p0) {
}
public final long getEventType() {
return 0L;
}
public final void setEventType(long p0) {
}
public final long getParentId() {
return 0L;
}
public final void setParentId(long p0) {
}
public final long getLastUpdated() {
return 0L;
}
public final void setLastUpdated(long p0) {
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String getSource() {
return null;
}
public final void setSource(@org.jetbrains.annotations.NotNull()
java.lang.String p0) {
}
public Event(@org.jetbrains.annotations.Nullable()
java.lang.Long id, int startTS, int endTS, @org.jetbrains.annotations.NotNull()
java.lang.String title, @org.jetbrains.annotations.NotNull()
java.lang.String location, @org.jetbrains.annotations.NotNull()
java.lang.String description, int reminder1Minutes, int reminder2Minutes, int reminder3Minutes, int repeatInterval, int repeatRule, int repeatLimit, @org.jetbrains.annotations.NotNull()
java.lang.String importId, int flags, long eventType, long parentId, long lastUpdated, @org.jetbrains.annotations.NotNull()
java.lang.String source) {
super();
}
@org.jetbrains.annotations.Nullable()
public final java.lang.Long component1() {
return null;
}
public final int component2() {
return 0;
}
public final int component3() {
return 0;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String component4() {
return null;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String component5() {
return null;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String component6() {
return null;
}
public final int component7() {
return 0;
}
public final int component8() {
return 0;
}
public final int component9() {
return 0;
}
public final int component10() {
return 0;
}
public final int component11() {
return 0;
}
public final int component12() {
return 0;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String component13() {
return null;
}
public final int component14() {
return 0;
}
public final long component15() {
return 0L;
}
public final long component16() {
return 0L;
}
public final long component17() {
return 0L;
}
@org.jetbrains.annotations.NotNull()
public final java.lang.String component18() {
return null;
}
@org.jetbrains.annotations.NotNull()
public final com.simplemobiletools.calendar.pro.models.Event copy(@org.jetbrains.annotations.Nullable()
java.lang.Long id, int startTS, int endTS, @org.jetbrains.annotations.NotNull()
java.lang.String title, @org.jetbrains.annotations.NotNull()
java.lang.String location, @org.jetbrains.annotations.NotNull()
java.lang.String description, int reminder1Minutes, int reminder2Minutes, int reminder3Minutes, int repeatInterval, int repeatRule, int repeatLimit, @org.jetbrains.annotations.NotNull()
java.lang.String importId, int flags, long eventType, long parentId, long lastUpdated, @org.jetbrains.annotations.NotNull()
java.lang.String source) {
return null;
}
@org.jetbrains.annotations.NotNull()
@java.lang.Override()
public java.lang.String toString() {
return null;
}
@java.lang.Override()
public int hashCode() {
return 0;
}
@java.lang.Override()
public boolean equals(@org.jetbrains.annotations.Nullable()
java.lang.Object p0) {
return false;
}
@kotlin.Metadata(mv = {1, 1, 13}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000\u0012\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010\t\n\u0000\b\u0086\u0003\u0018\u00002\u00020\u0001B\u0007\b\u0002\u00a2\u0006\u0002\u0010\u0002R\u000e\u0010\u0003\u001a\u00020\u0004X\u0082T\u00a2\u0006\u0002\n\u0000\u00a8\u0006\u0005"}, d2 = {"Lcom/simplemobiletools/calendar/pro/models/Event$Companion;", "", "()V", "serialVersionUID", "", "calendar_debug"})
public static final class Companion {
private Companion() {
super();
}
}
}
I fixed kotlin version at current version and rebuild it. But there is not change anything. I search this errors and try their solutions. But didn't worked. And other problem I didn't any change in java file. Android Studio is saying "Files under the "build" folder are generated and should not be edited".
A:
I clone the project
update kotlin
rename keystore.properties_sample to keystore.properties
run it.. and everything works fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting up pagination for list method in Django Rest framework viewset
I have a Viewset which has the following list method:
class PolicyViewSet(viewsets.ViewSet):
def list(self, request):
queryset = Policy.objects.all()
serializer = PolicySerializer(queryset, many=True)
return Response(serializer.data)
This works as intended and I get my desired Response.However, now I am trying to limit the objects returned per GET request and for that I am using pagination.I have defined the following in the settings.py:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20
}
The docs say:
Pagination is only performed automatically if you're using the generic views or viewsets.
However, my result is still not paginated.What else do I need to do to enable pagination ?
A:
If you overwrite your list or any main method you need to explicitly called for that.
class PolicyViewSet( viewsets.GenericViewset):
def list(self, request):
queryset = Policy.objects.all()
page = self.paginate_queryset(queryset)
serializer = PolicySerializer(page, many=True)
return self.get_paginated_response(serializer.data)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use [DllImport("")] in C#?
I found a lot of questions about it, but no one explains how I can use this.
I have this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.FSharp.Linq.RuntimeHelpers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
public class WindowHandling
{
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
Can someone help me to understand why it gives me an error on the DllImport line and on the public static line?
Does anyone have an idea, what can I do?
Thank you.
A:
You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Expression result unused — what's wrong with my C code?
I making a program which runs a "greedy" algorithm — one which asks for an input value of change owed and returns the minimum amount of coins required to return that change while using as few coins as possible. The only coins which can be used are the quarter, dime, nickel and penny. Please take a look at my code and tell me how I could fix the error being displayed.
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
float change;
int counter;
counter = 0;
do
{
printf("Please imput how much change is owed: ");
change = GetFloat();
}
while (change<=0);
int centv;
{
centv = round(change*100);
}
int quarter, dime, nickel, penny;
quarter= 25;
dime= 10;
nickel= 5;
penny= 1;
{
while( centv>=quarter )
{
(centv-25);
counter++;
}
while( centv>=dime )
{
(centv-10);
counter++;
}
while( centv>=nickel )
{
(centv-5);
counter++;
}
while( centv>=penny)
{
(centv-1);
counter++;
}
if(centv == 0)
{
printf("%i \n", counter);
}
}
}
The errors I'm getting are with the lines (centv-25), (centv-10), (centv-5) and (cent-1).
The error message is "expression result unused" for all of them.
How do I fix this?
A:
If you are trying to change the value of centv, you need something like centv = centv - 25;
centv - 25 should be replaced with centv = centv - 25, and similarly for the other lines.
| {
"pile_set_name": "StackExchange"
} |
Q:
Missing second array data using importrange in google sheets
I am trying to join two columns of data from two separate sheets. The first range appears fine, but the second briefly shows "loading" but is over written by the fist range of data. I have attached an example. Here is the formula:
=ARRAYFORMULA({Sheet2!A1:A; Sheet3!A1:A})
In this example, the data from Sheet3 is not appearing. My assumption is that it is because the range is dynamic (I don't know how much data will be in each column).
A:
The reason is because you need to sort your arrays OR filter out the blanks - it basically tends to only include the second array below the rest of the rows of the first one, including blank rows
if order of the data DOESN'T matter to you, you can simply wrap the entire function with a final SORT.
=sort(ARRAYFORMULA({Sheet2!A1:A; Sheet3!A1:A}))
If order DOES matter, you can use this function:
={FILTER(Sheet2!A1:A,LEN(Sheet2!A1:A)>1);FILTER(Sheet3!A1:A,LEN(Sheet3!A1:A)>1)}
| {
"pile_set_name": "StackExchange"
} |
Q:
.Net how to set IsReadOnly for a property for a usercontrol
I have a user control in .NET with 2 new property
Prop1: Boolean
Prop2: String
I want to make Prop2 READONLY in the property grid when the user set Prop1 to false.
A:
If you want to make the property appearance read-only (gray) at run-time based on some criteria, you need to assign a CustomTypeDescriptor to your class which provides metadata about your class for property grid.
PropertyGrid control uses the type descriptor of the object to extract information about its properties to show. The type descriptor, returns a list of PropertyDescriptor objects as list of properties. Each PropertyDescriptor contains some methods and properties to return display name, description, and other information about the property. IsReadOnly property of the PropertyDescriptor is responsible to inform the PropertyGrid if the property should be read only.
Example
In the following example, I created a class containing two properties. Editable and StringProperty. If the Editable is true then StringProperty is editable, otherwise it would be read-only and will be shown as gray in PropertyGrid.
MyPropertyDescriptor
It's responsible to provide metadata for property. When implementing this class, for most properties, we will use the trivial implementation which uses original property's implementations, but for IsReadOnly we will decide based on the value of Editable property of the owner object:
using System;
using System.ComponentModel;
using System.Linq;
public class MyPropertyDescriptor : PropertyDescriptor
{
PropertyDescriptor p;
SampleClass o;
public MyPropertyDescriptor(PropertyDescriptor originalProperty, SampleClass owenr)
: base(originalProperty) { p = originalProperty; o = owenr; }
public override bool CanResetValue(object component)
{ return p.CanResetValue(component); }
public override object GetValue(object component) { return p.GetValue(component); }
public override void ResetValue(object component) { p.ResetValue(component); }
public override void SetValue(object component, object value)
{ p.SetValue(component, value); }
public override bool ShouldSerializeValue(object component)
{ return p.ShouldSerializeValue(component); }
public override AttributeCollection Attributes { get { return p.Attributes; } }
public override Type ComponentType { get { return p.ComponentType; } }
public override bool IsReadOnly { get { return !o.Editable; } }
public override Type PropertyType { get { return p.PropertyType; } }
}
MyTypeDescriptor
It's responsible to provide a list of properties for the object. For StringProperty which we are going to change its behavior at run-time, we will return a MyPropertyDescriptor:
using System;
using System.ComponentModel;
using System.Linq;
public class MyTypeDescriptor : CustomTypeDescriptor
{
ICustomTypeDescriptor d;
SampleClass o;
public MyTypeDescriptor(ICustomTypeDescriptor originalDescriptor, SampleClass owner)
: base(originalDescriptor) { d = originalDescriptor; o = owner; }
public override PropertyDescriptorCollection GetProperties()
{ return this.GetProperties(new Attribute[] { }); }
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
var properties = base.GetProperties(attributes).Cast<PropertyDescriptor>()
.Select(p => p.Name == "StringProperty" ? new MyPropertyDescriptor(p, o) : p)
.ToArray();
return new PropertyDescriptorCollection(properties);
}
}
MyTypeDescriptionProvider
It's responsible to return a type descriptor for your object, when someone (like property grid) request type description:
using System;
using System.ComponentModel;
public class MyTypeDescriptionProvider : TypeDescriptionProvider
{
public MyTypeDescriptionProvider()
: base(TypeDescriptor.GetProvider(typeof(object))) { }
public override ICustomTypeDescriptor GetTypeDescriptor(Type type, object o)
{
ICustomTypeDescriptor baseDescriptor = base.GetTypeDescriptor(type, o);
return new MyTypeDescriptor(baseDescriptor, (SampleClass)o);
}
}
SampleClass
At last, the implementation of the class:
using System;
using System.ComponentModel;
[TypeDescriptionProvider(typeof(MyTypeDescriptionProvider))]
public class SampleClass
{
[RefreshProperties(RefreshProperties.All)]
public bool Editable { get; set; }
string sp;
public string StringProperty
{
get { return sp; }
set
{
if (Editable)
sp = value;
}
}
}
Result
Further reading
You can read about some other solutions in the following post:
Make a Property Read-Only in PropertyGrid
| {
"pile_set_name": "StackExchange"
} |
Q:
Xcode11 Archive fails: no such file or directory Objects-normal/arm64/UniversalSDK.SwiftFileList
I am trying to build a universal framework from existing source code in Xcode11.
When I Archive, it fails with following error:
/<unknown>:1:1: no such file or directory: '/Users/apple/SANDBOX/VoiceSampler/@/Users/apple/Library/Developer/Xcode/DerivedData/VoiceSampler-foeghskagbaeclezzbypkqnjnuos/Build/Intermediates.noindex/ArchiveIntermediates/BuildUniversalSDK/IntermediateBuildFilesPath/VoiceSampler.build/Release-iphoneos/UniversalSDK.build/Objects-normal/arm64/UniversalSDK.SwiftFileList'
/:1:1: no such file or directory: '/Users/apple/SANDBOX/VoiceSampler/@/Users/apple/Library/Developer/Xcode/DerivedData/VoiceSampler-foeghskagbaeclezzbypkqnjnuos/Build/Intermediates.noindex/ArchiveIntermediates/BuildUniversalSDK/IntermediateBuildFilesPath/VoiceSampler.build/Release-iphoneos/UniversalSDK.build/Objects-normal/arm64/UniversalSDK.SwiftFileList'
I was able to Archive the same in Xcode 10.3 earlier. Not sure what changed.
Please help me solve this Archive error.
A:
I don't know if it helps, but for me it happens when I run the Swift compiler manually from inside XCode (a script which builds a separate Swift framework). XCode sets the environment variable SWIFT_RESPONSE_FILE_PATH_normal_x86_64 (variant and architecture) which points to that particular missing .SwiftFileList file. Unsetting this environmant variable solved the issue for us.
This is how we unset it in the external script:
for V in ${BUILD_VARIANTS}; do
for A in ${ARCHS}; do
unset SWIFT_RESPONSE_FILE_PATH_${V}_${A}
done
done
| {
"pile_set_name": "StackExchange"
} |
Q:
java web app decorating/includes issues
Background: we have a system that was written in an older CMS based on Java back during the 2002-2003 days. We want to keep moving forward with our new stuff, using tomcat, stripes, and sitemesh. We have navigation, layouts, "pods", js, css, etc, that we've taken out of the old CMS and into a few of our new apps so we have consistent look and feel.
We now need some sort of solution to get rid of all the code duplication going on. Our apps are running on the same VM at the moment, but that might change. We need a way for all of our tomcat instances to access some common elements (and those elements may/may not need to do some server side stuff).
The best we've come up with so far is making a fairly standard sitemesh decorator, that uses c:import to get what it needs, and plugs it right in. This solution has some network overhead which could bog it down and introduce a fail point. We've looked at <%@ include file="/something.jsp" %> as well but that seems to be only context relative. We could use c:import and point it at localhost, which seems to be the best solution so far.
Are there other templating/decorating frameworks out there (Tiles?) that could make this simpler? What are we missing?
A:
I'm not quite sure what you're trying to do here. My interpretation is this: You have a number of resources that you want to reuse in a number of apps. You don't want to have these files duplicated in all apps, as it would make it hard to maintain consistency across the apps.
If this is your question, I would suggest that you keep your common resources in jar files. This gives you several advantages:
Your resources are local - no network overhead
You have control over updates to the resources.
An example of nr 2: You keep your common page layouts in page-layouts-1.x.jar. You keep on making minor releases of the page layouts that doesn't affect the apps using it - they are drop-in replacements. One day, you decide to redesign your apps completely and release page-layouts-2.0.jar. This require some rewrites to the apps using it. Now, if the apps bundles the page layouts, as opposed to keeping them in a shared class loader on the server, migrating to the 2.0 layout isn't an all or nothing affair. You can migrate one app at a time to use the 2.0 layout, while the others still use the 1.x layout.
We are doing this very successfully, using JSF and Facelets.
You might want to have a look at Weblets. I have no idea whether SiteMesh or Tiles got any direct support for serving up resources from the class path, but I assume you can tweak them to do this.
Hope it helps
| {
"pile_set_name": "StackExchange"
} |
Q:
CoreData entities to UITableView with sections
My data model is very simple, like a regular word dictionary:
The letters are the letters of the alphabet, the words are the words and definitions of the dictionary. My goal is to display the data in a UITableView with the Letter being the section and the words beneath.
My code:
var fetchedResultsController: NSFetchedResultsController!
override func viewDidLoad() {
super.viewDidLoad()
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Letter")
let letterSort =
NSSortDescriptor(key: "letterName", ascending: true)
fetchRequest.sortDescriptors = [letterSort]
fetchedResultsController =
NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: context,
sectionNameKeyPath: "letterName",
cacheName: "dict")
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
}
func numberOfSectionsInTableView
(tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count
}
func tableView(tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
let sectionInfo =
fetchedResultsController.sections![section]
return sectionInfo.name
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
let sectionInfo =
fetchedResultsController.sections![section]
print(sectionInfo.numberOfObjects)
return sectionInfo.numberOfObjects
}
I learned this code from a tutorial. It seems to work. The section number equals 26, and each header is a through z.
The question is how do I get the number of rows in a section and how do I reference the data to put them in a row?
A:
I don't think this code is going to do what you want. Typically the NSFetchRequest that you use to construct the NSFetchedResultsController that populates a UITableView or UICollectionView must fetch the entity type you actually want to display (or things become complicated). Have you tried something like this?
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Word")
let letterSort =
NSSortDescriptor(key: "letter.letterName", ascending: true)
let wordSort = NSSortDescriptor(key: "word", ascending: true)
fetchRequest.sortDescriptors = [letterSort, wordSort]
fetchedResultsController =
NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: context,
sectionNameKeyPath: "letter.letterName",
cacheName: "dict")
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
Assuming that your word values and associated letters are correct, I think this should do what you want. It's also worth noting that the cacheName must be unique in your application, so you might want something more complex than simply "dict".
| {
"pile_set_name": "StackExchange"
} |
Q:
'list' object has no attribute 'items' in Python's BeautifulSoup renderContents
In an attempt to remove unwanted/unsafe tags and attributes from input, I am using the below code (almost entirely by http://djangosnippets.org/snippets/1655/):
def html_filter(value, allowed_tags = 'p h1 h2 h3 div span a:href:title img:src:alt:title table:cellspacing:cellpadding th tr td:colspan:rowspan ol ul li br'):
js_regex = re.compile(r'[\s]*(&#x.{1,7})?'.join(list('javascript')))
allowed_tags = [tag.split(':') for tag in allowed_tags.split()]
allowed_tags = dict((tag[0], tag[1:]) for tag in allowed_tags)
soup = BeautifulSoup(value)
for comment in soup.findAll(text=lambda text: isinstance(text, Comment)):
comment.extract()
for tag in soup.findAll(True):
if tag.name not in allowed_tags:
tag.hidden = True
else:
tag.attrs = [(attr, js_regex.sub('', val)) for attr, val in tag.attrs.items() if attr in allowed_tags[tag.name]]
return soup.renderContents().decode('utf8')
It works well for unwanted or whitelisted tags, attributes not whitelisted and even badly formatted html. However if any whitelisted attributes are present, it raises
'list' object has no attribute 'items'
at the last line, which is not helping me much. type(soup) is <class 'bs4.BeautifulSoup'> whether it raises an error or not, so I don't know what it's referring to.
Traceback:
[...]
File "C:\Users\Mark\Web\www\fnwidjango\src\base\functions\html_filter.py" in html_filter
30. return soup.renderContents().decode('utf8')
File "C:\Python27\lib\site-packages\bs4\element.py" in renderContents
1098. indent_level=indentLevel, encoding=encoding)
File "C:\Python27\lib\site-packages\bs4\element.py" in encode_contents
1089. contents = self.decode_contents(indent_level, encoding, formatter)
File "C:\Python27\lib\site-packages\bs4\element.py" in decode_contents
1074. formatter))
File "C:\Python27\lib\site-packages\bs4\element.py" in decode
1021. indent_contents, eventual_encoding, formatter)
File "C:\Python27\lib\site-packages\bs4\element.py" in decode_contents
1074. formatter))
File "C:\Python27\lib\site-packages\bs4\element.py" in decode
1021. indent_contents, eventual_encoding, formatter)
File "C:\Python27\lib\site-packages\bs4\element.py" in decode_contents
1074. formatter))
File "C:\Python27\lib\site-packages\bs4\element.py" in decode
1021. indent_contents, eventual_encoding, formatter)
File "C:\Python27\lib\site-packages\bs4\element.py" in decode_contents
1074. formatter))
File "C:\Python27\lib\site-packages\bs4\element.py" in decode
983. for key, val in sorted(self.attrs.items()):
Exception Type: AttributeError at /"nieuws"/article/3-test/
Exception Value: 'list' object has no attribute 'items'
A:
Try replacing
tag.attrs = [(attr, js_regex.sub('', val)) for attr, val in tag.attrs.items() if attr in allowed_tags[tag.name]]
with
tag.attrs = dict((attr, js_regex.sub('', val)) for attr, val in tag.attrs.items() if attr in allowed_tags[tag.name])
| {
"pile_set_name": "StackExchange"
} |
Q:
Um ponteiro global pode apontar para uma variável local?
No caso abaixo, por exemplo:
int *pnum;
void main(){
int num = 10;
pnum = #
}
O que aconteceria se eu tentasse acessar o valor apontado do ponteiro fora da função main ?
A:
Vamos colocar um código real para ver o que acontece:
#include <stdio.h>
int *pnum;
void teste() {
printf("%d\n", *pnum);
}
void teste2() {
int num = 20;
pnum = #
}
void teste3() {
int num = 30;
num++;
}
int main() {
int num = 10;
pnum = #
teste();
teste2();
teste3();
teste();
}
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
O problema não é a variável ser global. É ela apontar para uma variável local. O código só deveria ter um ponteiro apontando para um endereço local (stack) ou no heap. O que acontece se não respeitar isto?
Códigos assim podem apontar para valores arbitrário, para endereços que não possuem dados garantidos.
Quando chamamos a função teste(), ela executa normalmente e pega o valor correto, afinal o endereço do ponteiro é uma área da pilha que está preservada. O stack frame da função Main() não desaparece quando chama outra função. Pelo contrário, um é empilhado no outro.
Note que a linguagem não garante isto. Mas é assim que costuma funcionar. O risco é seu. Se soube o que está fazendo, vai dar tudo certo.
Aí chamamos teste2() que muda o valor do ponteiro. Agora ele aponta para a variável local desta função e não mais para a função Main(). Esta variável tem outro valor. Até aí tudo bem.
Agora chamamos teste3(). Note que criamos uma variável local com novo valor. Mas não mudamos o ponteiro para apontar para esta variável. Ele vai continuar apontando para a variável local de teste2(), certo?
Mas como isto é possível se aquela variável não existe mais? Bem, o endereço de memória continua lá, está apontando pra ele. O que acontece agora?
Chamamos o teste() que imprime o valor da variável local de teste3() que nunca foi referenciado pelo ponteiro pnum. Por que isto ocorre?
Porque no fim da função teste2() o seu conteúdo é desempilhado. Não é apagado, mas fica livre para uso. Com a chamada da teste3(), é empilhado no mesmo lugar onde tinha os dados da teste2(). Por coincidência o valor da variável local de teste3() foi colocado no mesmo lugar onde estava a variável local de teste2(). Mas foi só uma coincidência. Deu sorte, podia ser pior.
Quando você vai subindo a pilha dá até para prever que valores estarão na pilha, mas quando você desce da pilha, qualquer valor que tenha lá deve ser considerado lixo e não deve ser acessado. A linguagem não impede.
Os dois motivos para existir o heap são: ter dados muito grandes que poderiam estourar a pilha ou justamente poder ter dados "vivos" criados por uma função mais alta sendo acessados por funções mais baixas em endereço "garantido".
A:
Sim, como o ponteiro aponta para o endereço da memória é possível modificar as variáveis locais através de um ponteiro global ou simplesmente passando o endereço da sua variável local para um ponteiro como parâmetro para uma função f(&ponteiro) ou para um ponteiro global int * pGlobal;, veja um exemplo abaixo:
#include <stdio.h>
int * pGlobal;
void foo(void)
{
*pGlobal = 100;
}
int main(void)
{
int num = 15;
pGlobal = #
printf("\n%d", *pGlobal);
printf("\n%d", num);
*pGlobal = 5;
printf("\n%d", *pGlobal);
printf("\n%d", num);
foo();
printf("\n%d", *pGlobal);
printf("\n%d", num);
return 0;
}
Acessando e modificando a variável declarada na função main:
void foo(void)
{
*pGlobal = 100;
}
Veja funcionando no Ideone.
Veja mais sobre ponteiros aqui nesta pergunta.
| {
"pile_set_name": "StackExchange"
} |
Q:
Delete same submatrices in a bigger matrix. Matlab
I want to analyse 2x2 blocks in a bigger matrix and if two of the blocks are the same, delete them. The code I tried to write myself for that looks somewhat like this (C is a big matrix with 2 colums):
n=size(C,1);
for k=1:2:(n-3)
for l=(k+2):2:(n-1)
if C(k:k+1,1:2)==C(l:l+1,1:2);
C([l,l+1],:)=[];
else
end
end
end
The problem I run into is, that matlab does not "notice" that the size of C is shrinking when it deletes rows in it. That means eventually the code runs into a problem because it is asking for the equal check in a dimension too high. How can I avoid it? Is there an entirely better way to do it?
I tried to wrap my head around the "unique" command, too. But that only works for rows. I need 2x2 segments (starting at an odd row).
Complete (original) code here:
A=[1,0;0,1i];
B=1/sqrt(2)*[1,1;1,-1];
C=[0,0;0,0];
C(1:2,1:2)=A(1:2,1:2);
C(3:4,1:2)=B(1:2,1:2);
for m=1:20
d=size(C,1)
C_A=C*A;
C_B=C*B;
s_a=size(C_A);
s_a=s_a(1,1);
s_b=size(C_B);
s_b=s_b(1,1);
C((d+1):(d+s_a),1:2)=C_A(1:s_a,1:2);
C((d+s_a+1):(d+s_a+s_b),1:2)=C_B(1:s_b,1:2);
n=size(C,1);
for k=1:2:(n-3)
for l=(k+2):2:(n-1)
if C(k:k+1,1:2)==C(l:l+1,1:2);
C([l,l+1],:)=[];
else
end
end
end
new_n=size(C,1)
if d==new_n
error('Done')
else
end
end
A:
To make your code work as it is, first reverse the direction of the l loop:
for l = (size(C,1)-1):-2:(k+2)
That way you're deleting from the end and recalculating the max index each time you increment k. But you're still going to run into trouble with the k loop, so just change that to a while loop. Also, using == to compare 2x2 matrices will give you 4 values, probably not what you want. Using isequal will give you a single boolean if the two matrices have all the same values.
k = 1;
while (k < size(C,1))
for l = (size(C,1)-1):-2:(k+2)
if isequal(C(k:k+1,1:2), C(l:l+1,1:2))
C([l,l+1],:) = [];
end
end
k = k + 2;
end
Alternatively, you can use unique by rearranging each 2x2 submatrix into a row:
D = reshape(C.', 4, []).';
U = unique(D, 'rows');
C = reshape(U.', 2, []).';
If you're dealing with floating-point values, it's never a good idea to compare them for equality; the limited precision of floating point values will always cause you trouble. To get around this, you can create a function to compare for equality within a tolerance.
isequalTol=@(a,b,tol) all(abs(a-b) < tol);
This function will work for scalars, vectors, or matrices. Now you define a tolerance and replace isequal with isequalTol:
tol = eps(1);
k = 1;
while (k < size(C,1))
for l = (size(C,1)-1):-2:(k+2)
if isequalTol(C(k:k+1,1:2), C(l:l+1,1:2), tol) % equal within tolerance
C([l,l+1],:) = [];
end
end
k = k + 2;
end
| {
"pile_set_name": "StackExchange"
} |
Q:
diagonal problem in octagon
I have not understand the question clearly. Can you give me hints (with figure) so I can move on .
A:
Take a look at a single vertex. How many diagonals can be drawn from that vertex? Of those, how many are not parallel to any side of the octagon (that is, how many belong to $B$)? What does this tell you, given the rotational symmetry of the figure?
As an alternate approach, we may determine these explicitly with combinatorics and pictures. There are $8$ vertices, so $\binom{8}{2}=28$ line segments that connect pairs of vertices. Of these, $8$ are edges, leaving $28-8=20$ diagonals. The diagonals that are not parallel to any edge are those between opposite vertices (only $4$ such diagonals) and those between vertices with a common neighbor ($8$ of these, forming two squares). Hence, $B$ has $12$ diagonals, and $A$ has $20-12=8$ diagonals (which you can actually draw in sequence without lifting your pencil).
| {
"pile_set_name": "StackExchange"
} |
Q:
convert mysql to query to laravel query
Hello i am trying to convert this mysql query to laravel query but still i have no success. can you please help to convert this mysql query to laravel query.
Mysql query as below
select *,SUM(pp.starting_balance) as total from (select `aa`.*,
GROUP_CONCAT( CONCAT(cc.purchasedescription," (",bb.quantity,")") SEPARATOR " , ") as bundle_item
from `composite_inventories` as aa
left join
`composite_has_inventories` as bb on `aa`.`id` = `bb`.`composite_inventory_id`
left join
`inventories` as cc on `bb`.`inventory_id` = `cc`.`id`
where
`aa`.`subscriber_id` = '2'
group by
`aa`.`id`) as tt left join `composite_has_warehouses` as pp on `tt`.`id` = `pp`.`composite_inventory_id` group by pp.composite_inventory_id
I tried to build as below but not working
$row = DB::table('composite_inventories')->select('composite_inventories.*',
DB::raw('SUM(composite_has_warehouses.starting_balance) as total')
DB::raw('GROUP_CONCAT( CONCAT(inventories.purchasedescription," (",composite_has_inventories.quantity,")") SEPARATOR " , ") as bundle_item')
)
->leftJoin('composite_has_inventories', 'composite_inventories.id', '=', 'composite_has_inventories.composite_inventory_id')
->leftJoin('inventories', function($join) {
$join->on('composite_has_inventories.inventory_id', '=', 'inventories.id');
})
->where('composite_inventories.subscriber_id',$subscriber_id)
->groupBy('composite_inventories.id')
->leftJoin('composite_has_warehouses', 'composite_inventories.id', '=', 'composite_has_warehouses.composite_inventory_id')
->get();
A:
You can use a DB::select() method and place your raw query as a string:
DB::select("select *,SUM(pp.starting_balance) as total from (select `aa`.*,
DB::raw('GROUP_CONCAT( CONCAT(cc.purchasedescription,' (',bb.quantity,')') SEPARATOR ' , ') as bundle_item ')
from `composite_inventories` as aa
left join
`composite_has_inventories` as bb on `aa`.`id` = `bb`.`composite_inventory_id`
left join
`inventories` as cc on `bb`.`inventory_id` = `cc`.`id`
where
`aa`.`subscriber_id` = '2'
group by
`aa`.`id`) as tt left join `composite_has_warehouses` as pp on `tt`.`id` = `pp`.`composite_inventory_id` group by pp.composite_inventory_id");
| {
"pile_set_name": "StackExchange"
} |
Q:
read data of specific length from a specific position ios
I have the following code for reading a file in length of specific size:
int chunksize = 1024;
NSData* fileData = [[NSFileManager defaultManager] contentsAtPath:URL];
NSString* fileName = [[message.fileURL lastPathComponent] stringByDeletingPathExtension];
NSString* extension = [[message.fileURL pathExtension] lastPathComponent];
NSFileHandle* fileHandle = [NSFileHandle fileHandleForReadingAtPath:[self retrieveFilePath:fileName andExtension:extension]];
file=@"test.png";
int numberOfChunks = ceilf(1.0f * [fileData length]/chunksize); //it s about 800
for (int i=0; i<numberOfChunks; i++)
{
NSData *data = [fileHandle readDataOfLength:chunksize];
....//some code
}
// read a chunk of 1024 bytes from position 2048
NSData *chunkData = [fileHandle readDataOfLength:1024 fromPosition:2048];//I NEED SOMETHING LIKE THIS!!
A:
You need to set the file pointer to the offset you want to read from:
[fileHandle seekToFileOffset:2048];
And then read the data:
NSData *data = [fileHandle readDataOfLength:1024];
Be aware that errors are reported in the form of NSExceptions, so you'll want some @try/@catch blocks around most of these calls. In fact the use of exceptions to report errors means I often make my own file-access functions to ease their use; for example:
+ (BOOL)seekFile:(NSFileHandle *)fileHandle
toOffset:(uint32_t)offset
error:(NSError **)error
{
@try {
[fileHandle seekToFileOffset:offset];
} @catch(NSException *ex) {
if (error) {
*error = [AwzipError error:@"Failed to seek in file"
code:AwzipErrorFileIO
exception:ex];
}
return NO;
}
return YES;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Process for using show.bs.dropdown in Bootstrap
What is the process for using the show.bs.dropdown event when a dropdown is clicked?
Example:
When I clicked the dropdown to expand, it needs to run the code:
$('#myDropdown').on('show.bs.dropdown', function () {
// do something…
})
A:
The Bootstrap dropdown show event is tied to the parent element of the dropdown. For example, notice the id=myDropdown..
<div class="btn-group" id="myDropdown">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Menu
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="#">Choice1</a></li>
<li><a href="#">Choice2</a></li>
<li><a href="#">Choice3</a></li>
<li class="divider"></li>
<li><a href="#">Choice..</a></li>
</ul>
</div>
Is handled by this event..
$('#myDropdown').on('show.bs.dropdown', function () {
alert('hello');
})
Demo: http://www.bootply.com/114783
| {
"pile_set_name": "StackExchange"
} |
Q:
Can interceptors be executed between authentication and action execution?
Moving from container-managed authentication to the Spring Security plugin in a Grails 3.1.9 app. In the container-managed world, our Grails interceptors executed AFTER authentication for a secured resource. However, with Spring Security, the interceptors (with before() logic) execute with the following sequence:
Call to secured resource
Interceptor stack intercepts request, returns true
Redirected to form login page
Successful authentication
Redirection to requested resource
We have interceptors that should only fire for authenticated users. Is there a way to have interceptors executed between step 4 & 5 instead of this flow? Or is this where our interceptor logic needs to move into Spring Security filters?
A:
It's a little more clear if you look at the flow in a 2.x app since there's a web.xml file where it's more clear what order several of the parts run in, but it's basically the same in 2.x and 3.x.
The plugin's filter chain is registered as one filter and it's configured to run after the grailsWebRequest filter but before the GrailsDispatcherServlet. This is to support annotated controllers that may have URL mappings that are different from the default (e.g. PersonController.show() may map to /person/show but the app could have mapped it to any valid uri (and combination of REST verb(s)), so I need to be able to search the compiled url mapping instances to figure out what controller action will run for the current request. In the filter I know what URL is being requested, but not what security rule(s) to apply; if everything was url-based it would be simple and precompiled at startup, but with annotated controllers I only know what rules apply to controller methods.
The servlet runs after the filters, and that's where the controller is determined and invoked. Interceptors (and Grails filters (not to be confused with servlet Filters) in 2.x) are actually Spring HandlerInterceptors that get composed along with a 'handler' into a HandlerExecutionChain. This is generic enough to work with any type of request but in practice the handler is a controller, so the scope is much narrower than if it were a servlet Filter.
So to get back to your actual question, your best option is to do the work in a filter that's added to the Spring Security filter chain. These are pretty simple to implement and the process is described in the plugin docs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spherical Harmonics expansion of a Dirac Delta at the North Pole
I think all the coefficients for the spherical harmonic expansion of a delta function at the north pole should be a constant (presumably 1), but I'm having difficulties calculating them. Could someone kindly take some time showing me how they are calculated, thanks a lot!
A:
I don't see why they all have to be 1. A difficulty with the North pole is that the usual coordinate system has a singularity there. So think about a function that approximates the delta function, maybe something constant in a small radius around the North pole.
I'm using the definitions here: http://en.wikipedia.org/wiki/Spherical_harmonics#Orthogonality_and_normalization http://en.wikipedia.org/wiki/Spherical_coordinate_system (I think we are using the "physics" version of spherical coordinates.)
It seems to me that the $f_l^m$ coefficients should be zero whenever $m \ne 0$, because you are integrating $e^{im\varphi}$ from $\varphi=0$ to $2\pi$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Abstract Factory Design Pattern implementation in C++ using Qt Creator
I am trying to make all the creational design patterns and I'm having some trouble with the abstract factory method. I normally program in Python, however, I had heard C++ was good for really having to understand design patterns explicitly, which is proving to be right, err.
I'm basically following this guide on Tutorials Point.
My question is how would I change my current code to correctly implement the abstract factory method in C++ with a factory producer as I believe its something to do with my Factory Producer extra layer of abstraction that is causing my issues. I have included all my code.
I tried to make a simple diagram to explain better but it's not the most formal UML but is essentially what I would like to make. My main.cpp file should illustrate better the functionality I'm trying to understand how to make.
P.s. I'm just trying to improve to apply for jobs so please let me know if you have any feedback on writing better SO questions, coding style, variable naming or even C++ conventions.
Main
main.cpp - Main implementation file
Tests creating an abstract factory, abstract sword and abstract warrior.
#include "factoryproducer.h"
using namespace std;
int main(int argc, char *argv[]) {
AbstractFactory* warriorFactory = FactoryProducer::createFactory("warriorfactory");
Warrior* tinyWarrior = warriorFactory->createWarrior("tinywarrior");
Warrior* normalWarrior = warriorFactory->createWarrior("normalwarrior");
Warrior* largeWarrior = warriorFactory->createWarrior("largewarrior");
Warrior* giantWarrior = warriorFactory->createWarrior("giantwarrior");
cout<<tinyWarrior->getName().toStdString()<<endl;
cout<<normalWarrior->getName().toStdString()<<endl;
cout<<largeWarrior->getName().toStdString()<<endl;
cout<<giantWarrior->getName().toStdString()<<endl;
AbstractFactory* SwordFactory = FactoryProducer::createFactory("swordfactory");
Sword* tinySword = swordFactory->createSword("tinysword");
Sword* normalSword = swordFactory->createSword("normalsword");
Sword* largeSword = swordFactory->createSword("largesword");
Sword* giantSword = swordFactory->createSword("giantsword");
cout<<tinySword->getName().toStdString()<<endl;
cout<<normalSword->getName().toStdString()<<endl;
cout<<largeSword->getName().toStdString()<<endl;
cout<<giantSword->getName().toStdString()<<endl;
return a.exec();
}
Abstract Factory Class
abstractfactory.h - Abstract Factory header file
#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H
#include "warrior.h"
#include "sword.h"
#include <QString>
class AbstractFactory {
public:
// Public Methods
~AbstractFactory();
virtual Warrior* createWarrior(QString warriorType) = 0;
virtual Sword* createSword(QString swordType) = 0;
};
#endif // ABSTRACTFACTORY_H
abstractfactory.cpp Abstract Factory implementation file
#include "abstractfactory.h"
AbstractFactory::~AbstractFactory(){}
Factory Producer Class
factoryproducer.h - Factory Producer header file
#ifndef FACTORYPRODUCER_H
#define FACTORYPRODUCER_H
#include "abstractfactory.h"
#include "warriorfactory.h"
#include "swordfactory.h"
#include <QString>
class FactoryProducer {
public:
// Public Methods
static AbstractFactory* createFactory(QString factoryType);
};
#endif // FACTORYPRODUCER_H
factoryproducer.cpp - Factory Producer implementation file
#include "factoryproducer.h"
AbstractFactory* AbstractFactory::createFactory(QString factoryType) {
if (factoryType == nullptr) {
return nullptr;
}
if (QString::compare(factoryType, "WARRIORFACTORY", Qt::CaseInsensitive) == 0) {
return new WarriorFactory();
}
if (QString::compare(factoryType, "SWORDFACTORY", Qt::CaseInsensitive) == 0) {
return new SwordFactory();
}
return nullptr;
}
Abstract Warrior Class
warrior.h - Abstract Warrior header file
#ifndef WARRIOR_H
#define WARRIOR_H
#include "tinywarrior.h"
#include "normalwarrior.h"
#include "largewarrior.h"
#include "giantwarrior.h"
#include <QString>
class Warrior {
public:
// Public Methods
~Warrior();
virtual QString getName() = 0;
virtual QString getPicture() = 0;
};
#endif // WARRIOR_H
warrior.cpp - Abstract Warrior implementation file
#include "warrior.h"
Warrior::~Warrior(){}
Abstract Sword Class
sword.h - Abstract Sword header file
#ifndef SWORD_H
#define SWORD_H
#include "tinysword.h"
#include "normalsword.h"
#include "largesword.h"
#include "giantsword.h"
#include <QString>
class Sword {
public:
// Public Methods
~Sword();
virtual QString getName() = 0;
virtual QString getPicture() = 0;
};
#endif // SWORD_H
sword.cpp - Abstract Sword implementation file
#include "sword.h"
Sword::~Sword(){}
Concrete TinySword Class
tinysword.h - Concrete Tiny Sword header file
#ifndef TINYSWORD_H
#define TINYSWORD_H
#include "sword.h"
class TinySword : public Sword {
public:
// Public Methods
TinySword();
~TinySword();
QString getName();
QString getPicture();
private:
// Private Member Variables
QString m_name;
QString m_picture;
};
#endif // TINYSWORD_H
tinysword.cpp - Concrete Tiny Sword implementation file
#include "tinysword.h"
TinySword::TinySword(){
m_name = "Tiny Sword";
m_picture = "";
}
TinySword::~TinySword(){}
QString TinySword::getName() {
return m_name;
}
QString TinySword::getPicture() {
return m_picture;
}
Concrete Normal Sword
normalsword.h - Concrete Normal Sword header file
#ifndef NORMALSWORD_H
#define NORMALSWORD_H
#include "sword.h"
class NormalSword : public Sword {
public:
// Public Methods
NormalSword();
~NormalSword();
QString getName();
QString getPicture();
private:
// Private Member Variables
QString m_name;
QString m_picture;
};
#endif // NORMALSWORD_H
normalsword.cpp - Concrete Normal Sword implementation file
#include "normalsword.h"
NormalSword::NormalSword() {
m_name = "Normal Sword";
m_picture = "";
}
NormalSword::~NormalSword(){}
QString NormalSword::getName() {
return m_name;
}
QString NormalSword::getPicture() {
return m_picture;
}
Concrete Large Sword Class
largesword.h - Concrete Large Sword header file
#ifndef LARGESWORD_H
#define LARGESWORD_H
#include "sword.h"
class LargeSword : public Sword {
public:
// Public Methods
LargeSword();
~LargeSword();
QString getName();
QString getPicture();
private:
// Private Member Variables
QString m_name;
QString m_picture;
};
#endif // LARGESWORD_H
largesword.cpp - Concrete Large Sword implementation file
#include "largesword.h"
LargeSword::LargeSword() {
m_name = "Large Sword";
m_picture = "";
}
LargeSword::~LargeSword(){}
QString LargeSword::getName() {
return m_name;
}
QString LargeSword::getPicture() {
return m_picture;
}
Concrete Giant Sword Class
giantsword.h - Concrete Giant Sword header file
#ifndef GIANTSWORD_H
#define GIANTSWORD_H
#include "sword.h"
class GiantSword : public Sword {
public:
// Public Methods
GiantSword();
~GiantSword();
QString getName();
QString getPicture();
private:
// Private Member Variables
QString m_name;
QString m_picture;
};
#endif // GIANTSWORD_H
giantsword.cpp - Concrete Giant Sword implementation file
#include "giantsword.h"
GiantSword::GiantSword() {
m_name = "Giant Sword";
m_picture = "";
}
GiantSword::~GiantSword(){}
QString GiantSword::getName() {
return m_name;
}
QString GiantSword::getPicture() {
return m_picture;
}
Concrete Tiny Warrior Class
tinywarrior.h - Concrete Tiny Warrior header file
#ifndef TINYWARRIOR_H
#define TINYWARRIOR_H
#include "warrior.h"
class TinyWarrior : public Warrior {
public:
// Methods
TinyWarrior();
~TinyWarrior();
QString getPicture();
private:
// Private Member Variables
QString m_name;
QString m_picture;
};
#endif // TINYWARRIOR_H
tinywarrior.cpp - Concrete Tiny Warrior implementation file
#include "tinywarrior.h"
TinyWarrior::TinyWarrior(){
m_name = "Tiny Warrior";
m_picture = ":/images/tiny-warrior.png";
}
TinyWarrior::~TinyWarrior(){}
QString TinyWarrior::getName() {
return m_name;
}
QString TinyWarrior::getPicture() {
return m_picture;
}
Concrete Normal Warrior Class
normalwarrior.h - Concrete Normal Warrior header file
#ifndef NORMALWARRIOR_H
#define NORMALWARRIOR_H
#include "warrior.h"
class NormalWarrior : public Warrior {
public:
// Public Methods
NormalWarrior();
~NormalWarrior();
QString getName();
QString getPicture();
private:
// Private Member Variables
QString m_name;
QString m_picture;
};
#endif // NORMALWARRIOR_H
normalwarrior.cpp Concrete Normal Warrior implementation
#include "normalwarrior.h"
NormalWarrior::NormalWarrior() {
m_name = "Normal Warrior";
m_picture = ":/images/normal-warrior.png";
}
NormalWarrior::~NormalWarrior(){}
QString NormalWarrior::getName() {
return m_name;
}
QString NormalWarrior::getPicture() {
return m_picture;
}
Concrete Large Warrior Class
largewarrior.h Concrete Large Warrior header file
#ifndef LARGEWARRIOR_H
#define LARGEWARRIOR_H
#include "warrior.h"
class LargeWarrior : public Warrior {
public:
// Methods
LargeWarrior();
~LargeWarrior();
QString getName();
QString getPicture();
private:
// Private Member Variables
QString m_name;
QString m_picture;
};
#endif // LARGEWARRIOR_H
largewarrior.cpp Concrete Large Warrior implementation file
#include "largewarrior.h"
LargeWarrior::LargeWarrior(){
m_name = "Large Warrior";
m_picture = ":/images/large-warrior.png";
}
LargeWarrior::~LargeWarrior(){}
QString LargeWarrior::getName() {
return m_name;
}
QString LargeWarrior::getPicture() {
return m_picture;
}
Concrete Giant Warrior Class
giantwarrior.h - Concrete Giant Warrior header file
#ifndef GIANTWARRIOR_H
#define GIANTWARRIOR_H
#include "warrior.h"
class GiantWarrior : public Warrior {
public:
// Methods
GiantWarrior();
~GiantWarrior();
QString getName();
QString getPicture();
void setXPosition(int x);
int getXPosition();
private:
// Private Member Variables
QString m_name;
QString m_picture;
};
#endif // GIANTWARRIOR_H
giantwarrior.cpp - Concrete Giant Warrior implementation file
#include "giantwarrior.h"
GiantWarrior::GiantWarrior(){
m_name = "Giant Warrior";
m_picture = ":/images/giant-warrior.png";
}
GiantWarrior::~GiantWarrior(){}
QString GiantWarrior::getName() {
return m_name;
}
QString GiantWarrior::getPicture() {
return m_picture;
}
A:
The given example from TutorialsPoint is misleading.
For example what does your WarriorFactory return if createSword is called? Returning nullptr is not an option because of this:
void doSomethingWithFactory(AbstractFactory* f)
{
Warrior* w = f->createWarrior();
Sword* s = f->createSword();
}
You actually need to know if you have been given a warrior or a sword factory and thus you are not abstracting anything away.
I coded an example which uses an abstract EnemyFactory which creates Monsters and Warriors. Depending on the concrete factory these enemies are either strong or weak.
EnemyFactory
This factory always creates enemies but their attributes differ depending on the concrete factory.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I limit an assume rule policy to a specific lambda, instead of lambda's in general?
I'm trying to get into the whole IAM setup. I have a role that I want a lambda to be able to assume.
So, I have my Trust Relationship policy setup like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
Now, as far as I understand, this would allow any lambda to assume this role.
Can I narrow this in a bit more, so it's only one specific lambda, that is allowed to assume it?
I've tried to replace "Service": "lambda.amazonaws.com" with the arn of the lambda, but it didn't really work out for me :/
A:
I think that it's actually the other way around...
When creating the Lambda function, you can specify the role for it to use. The ability to allow a function to use a Role requires the iam:PassRole permission. Anyone with this permission can configure a Lambda function to use a specific (or any) IAM Role.
Here's a sample policy from Granting a User Permissions to Pass a Role to an AWS Service - AWS Identity and Access Management that grants an IAM User the ability to pass a role:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": [
"iam:GetRole",
"iam:PassRole"
],
"Resource": "arn:aws:iam::<account-id>:role/EC2-roles-for-XYZ-*"
}]
}
iam:PassRole is a very important permission because it controls who can pass a role to a service. Used incorrectly, users might gain too much permission. For example, let's say that there is an Admin Role that has lots of permissions. Anyone who is granted permission to use PassRole could create a resource (eg Amazon EC2 instance or AWS Lambda function) that uses this role, thereby giving them Admin capabilities. For this reason, the ability to use PassRole should be strictly controlled.
Therefore, rather than the role trusting a Lambda function, you actually need a user with PassRole to assign the role to the function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android studio does not show a new created directory
When I create a new directory (example: values-da) in my "res" directory, it does not show my created directory. No matter what the directory is named. it just won't showing. I re-created the directory again and it says that the directory already exist. I closed the program and open it again but my created directory is still not showing.
A:
That is because you do not have any resources in that directory and you are using the Android project view.
Click on the "Android" drop-down that is shown in the upper-left corner of your screenshot. Change it to "Project". that will give you an accurate depiction of the directory structure of your project.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to only display First 3 items in a spinner and other items by scrolling?
So i have a spinner as you can see in the image
So what i want to do is that i only want to display the first 3 items and rest items should be scroll-able. Any Ideas?
A:
you can adjust you spinner popup menu height like below:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
try {
Field popup = Spinner.class.getDeclaredField("mPopup");
popup.setAccessible(true);
// Get private mPopup member variable and try cast to ListPopupWindow
ListPopupWindow popupWindow = (ListPopupWindow) popup.get(spinner);
popupWindow.setHeight(500);
}
catch (NoClassDefFoundError | ClassCastException | NoSuchFieldException | IllegalAccessException e) {
// silently fail...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why the convexity condition on the definition of a face of a convex set?
A face of a closed convex set $X\subseteq\mathbb{R}^n$ is defined to be a set $F\subseteq X$ such that:
$F$ is convex.
Every line segment from $X$ whose interior meets $F$ is contained in $F$.
Is condition 1 needed? Is there an example where condition 2 is satisfied but condition 1 is not? Thank you.
A:
Condition 1 is needed. Take a closed tetrahedron $X$, and let $F$ be the union of two faces of $X$. Then Condition 2 is satisfied, but Condition 1 is not.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to implement Async Task to fetch data from database using async and await?
I am doing this. It's working but is this a recommended way to do this. Please comments
public async void LoadData()
{
DataTable dtAdditionsDetails = await LoadReportData(importID,
InkeyCommon.ToInt32(cmbSellers.SelectedValue),
fromDate,
toDate);
if (dtAdditionsDetails != null)
dtaGrdAdditions.ItemSource = dtAdditionsDetails.DefaultView;
}
public async Task<DataTable> LoadReportData(int? importID,
int sellerID,
DateTime? fromDate,
DateTime? toDate)
{
DataTable dtAdditionsDetails = new DataTable();
//Get Report Data
await Task.Delay(1);
dtAdditionsDetails = ReportsData.GetRptAdditions(importID,
sellerID,
fromDate,
toDate);
return dtAdditionsDetails;
}
A:
In order to use the await keyword properly, the object being 'awaited' should really be an ...Async method, like the GetStringAsync method. As @ken2k has correctly pointed out, you cannot just await any method. Therefore, to answer your question is this a recommended way to do this?, the answer is no.
You can find out how to use the await and async keywords correctly in the Asynchronous Programming with Async and Await (C# and Visual Basic) page on MSDN, however, if you're just trying to run a synchronous method asynchronously, then you can do that like this:
public DataTable LoadData()
{
DataTable dtAdditionsDetails = ...
// Get your data here synchronously
return dtAdditionsDetails;
}
public async Task<DataTable> LoadDataAsync()
{
DataTable dtAdditionsDetails = LoadData();
return Task.Run(() => LoadData());
}
...
public async void GetDataAsynchronously()
{
DataTable dtAdditionsDetails = await LoadDataAsync();
}
Note that ...Async methods (usually) return Task<T> objects, rather than nothing and that their names end in the word Async. Also note that only the data is returned from ...Async methods and not the Task<T> and that we don't await when there is nothing to await.
| {
"pile_set_name": "StackExchange"
} |
Q:
Haskell: List comprehension of Glade entries
I want to make an entries :: Map(String -> Entry) so I can easily access each entry by name. To this end, I have the code
Just xml ← xmlNew "blah.glade"
...
entries ← fromList $ [(name,entry) | name <- entryList
, entry <- xmlGetWidget xml castToEntry name]
(where entryList is a list of entry names, e.g. ["name1","name2",...]).
However, the list comprehension comes up with the following error:
Couldn't match expected type `[t]' against inferred type `IO Entry'
In the expression: xmlGetWidget xml castToEntry name
In a stmt of a list comprehension:
entry <- xmlGetWidget xml castToEntry name
In the second argument of `($)', namely
`[(name, entry) |
name <- entryList, entry <- xmlGetWidget xml castToEntry name]'
I can't see why it's expecting a list of anything. Can anyone help with this?
A:
It's because <- in a list comprehension expects the right hand side to be a list. You're trying to use it to bind the result of an IO action, but that's only valid in do notation (without extensions, at least).
The problem is that xmlGetWidget returns IO Entry, but you want a map of Entry. That means you'll have to compose those IO actions into a larger one.
In the end, you'll want something like this:
let getEntry name = do entry <- xmlGetWidget xml castToEntry name
return (name, entry)
entries <- fromList <$> mapM getEntry entryList
Here, I've created a helper function getEntry :: String -> IO (String, Entry) to get the entry and pair it up with its name.
Next, I use mapM to map getEntry over the list of names. Note the difference between map and mapM. If I had used map, I would have gotten a list of actions, i.e. [IO (String, Entry)], when what I want is an action returning a list, i.e. IO [(String, Entry)].
Now, having constructed that IO action, I convert it to a Map using fromList with the operator <$>. Also known as fmap, <$> applies a pure function to the thing inside the IO, so the result is of type IO (Map String Entry).
Finally, the result of this IO action can be bound to entries.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find class in complex structure through jQuery
HTML structure is
<div class="menu_item cf">
<div class="menu_desc">
<h4><a href="#">Garlic Bread Sticks</a></h4>
<p>Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare.</p>
<div class="social_links cf">
<a href="#" class="fb">facebook</a>
<a href="#" class="tw">twitter</a>
</div>
<div class="menu_links">
<a class="btn_yellow">detail</a>
<a class="green_btn_right_arrow order_btn">order</a>
<p class="item_price">AED 18</p>
</div><!-- menu_links -->
</div><!-- menu_desc -->
<div class="img_cont">
<a href="#"><img src="images/menu_item_img1.png" alt=""></a>
</div><!-- img_cont -->
<div class="clear"></div>
<div class="order_cont cf">
<img src="images/order_arrow_up.png" alt="" class="menu_order_arrow" />
<form method="post" action="" name="">
<label>
<span>Quantity</span><br>
<input type="text" name="quantity" placeholder="Quantity" />
</label>
<div class="float-l">
<span>Quantity</span><br>
<div class="selc_cont">
<select>
<option>Small</option>
<option>Large</option>
</select>
</div>
</div>
<a href="#" class="black_btn_right_arrow">Add to Cart</a>
</form>
</div><!-- order_cont -->
</div><!-- menu_item -->
What I want is to find first div with class name order_cont when clicking on class order_btn button. As it will be listing, so I want only first div with class name order_cont.
What I tried is
$('.order_btn').nextAll('.order_cont:first');
Also
$('.order_btn').dblclick(function(e) {
$(this).closest('.order_cont').slideToggle('fast');
});
But no luck. Any help will be appreciated.
Thanks
A:
nextAll didn't work because the div isn't a sibling of the "button."
You need to go up to the sibling first. Unless the HTML indentation is misleading, it looks like menu_desc is the relevant sibling, so:
$(".order_btn").on("relevant-event", function() {
$(this).closest(".menu_desc").nextAll(".order_cont").first().slideToggle('fast');
});
(If the relevant event is dblclick, then replace relevant-event with dblclick above.)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use ListFragment in Android Swipe Tabs?
I have used this code before for a swipe tab view with two layouts and it works fine.
public class MainActivity extends FragmentActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_OBJECT, position);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 2 total pages.
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public static final String ARG_OBJECT = "object";
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
switch (position) {
case 0:
tabLayout = R.layout.tab_new;
break;
case 1:
tabLayout = R.layout.tab_summary;
break;
}
View rootView = inflater.inflate(tabLayout, container, false);
return rootView;
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
}
return true;
}
}
For that, I simply created 2 xml files and initialized them when the tabs are positioned correctly; however, now I want to have 2 tabs but the second one has to be a list. I'm not sure how to do that. I tried extending listFragment, but it crashed with resource not found. I've been stuck for a long time now, someone please help? I googled a lot and looked at all the examples but none of them show me how to make a list within a tab and how to call that.
Here's what I have right now
MainActivity
public class MainActivity extends FragmentActivity {
SimpleListFragment x = new SimpleListFragment();
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_OBJECT, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public static final String ARG_OBJECT = "object";
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
switch (position) {
case 0:
tabLayout = R.layout.tab_home;
break;
case 1:
SimpleListFragment simpleListFragment = new SimpleListFragment();
break;
}
View rootView = inflater.inflate(tabLayout, container, false);
return rootView;
}
}
}
A:
ATM you are creating your ListFragment in the DummySectionFragment. Thats not right.
Here is one way of doing it. Not the best but one thats good to understand.
Create the fragments in the main activity and pass them to the adapter. The DummyListFragment is a new class derived from ListFragment. Important here is that the XML layout that it uses contains a ListView that has the id @android:id/list. (so the fragment is able to understand which listview it has to / can use.
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
List<Fragment> mFragments;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragments = new ArrayList<Fragment>();
mFragments.add(new DummySectionFragment();
mFragments.add(new DummyListFragment();
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager(), mFragments);
...
public class SectionsPagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragmentList;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
fragmentList = fragments;
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public Fragment getItem(int position) {
Fragment fragment = fragmentList.get(position);
return fragment;
}
. .
public static class DummyListFragment extends ListFragment {
public DummyListFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_list_fragment, container, false);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Migrate VMware Server to ESXi
What's the recommended approach/tool to migrate VMs from VMware Server 1.0.7 (under Win2003 x64 Enterprise) to ESXi 4 ?
Some of the VMs are running Win2003 Enterprise x86, others run Ubuntu JeOS 8.04.
A:
vmware converter will be the simplest way to do it. Once you have ESXi built and the vms copied to a location, just launch converter, you will be asked for the source machine then to give it a destination, that will be your ESXi server, then follow the steps, even if the import fails it will not affect your source vm.
| {
"pile_set_name": "StackExchange"
} |
Q:
json php return nothing with ajax
hi guys i wrote this simple test for my php code and it's not working !!!
I want to get err value but it's not working
2.php
$error="abc";
$er=json_encode($error);
return $er;
my html :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<button>my btn</button>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "2.php",
success: function(result){
var er=JSON.parse(result);
$("res").html(er);
}
});
});
});
</script>
<div id="res"></div>
</body>
A:
In order for AJAX to work, you must echo your return from the PHP file:
$error="abc";
$er=json_encode($error);
echo $er;
What many fail to realize is that an HTTP request is made and when you use return you're only returning the function's output to the local script, not to the HTTP response.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.