source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0019503648.txt"
] | Q:
Is map > > slower than concatenating the strings to map?
I need to access some data according to three different criteria, like this:
my_map["string1"]["string2"]["string3"]
Now I wonder if it makes sense to concatenate the strings in this way:
my_map["string1|string2|string2"]
Would this save time for lookup operations?
Are there other important factors to consider?
A:
It's probably not a good idea to do that for two main reasons:
it makes things more inscrutable and complex for those who come behind you
in-band signalling opens you up to all sorts of fun security exploits when someone puts a separator character in one of the strings
You should probably look for data structures that do what you want with proper design, like tuples.
A:
The question should be preceded by looking at the use-cases you need to support. If your data is hierarchical and you need to access whole sub-parts of it (like passing my_map["criteria1"], you should stick with the first version.
If that is not the case and you only have one large set of data with three orthogonal criteria, you could optimize the access. Concatenating the strings is not the best approach as it creates certain overhead for copying and concatenating strings and you need to be careful about the separator, probably even requiring you to escape certain characters which introduces more overhead and more complexity, which mean: More bugs. Instead, you want to store the three criteria in a single, suitable key type: std::tuple.
Your map could look like (given is stores values of some type X):
using my_key_type = std::tuple<std::string,std::string,std::string>;
std::map< my_key_type, X > my_map;
Adding values works like this:
my_map.emplace( my_key_type( "A", "B", "C" ), x ); // x is a value of type X
And lookup can be done efficiently with:
X x = my_map[ std::tie( "A", "B", "C" ) ];
As pointed out by David Rodríguez, std::tie doesn't buy much efficiency when used with [], but it is shorter than std::make_shared. Anyways, you will have a benefit in the future with C++14 when you use my_map.find( std::tie( "A", "B", "C" ) ); which will allow the compiler to omit copying the strings for lookup.
|
[
"stackoverflow",
"0053339020.txt"
] | Q:
jackson polymorphic deserialization with a custom criteria
I need to know whether I can deserialize a generic object to it's defining type without having an additional property or without mentioning the type in an annotation.
Ex:-
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
In above I have to mention the @class property, and another way is
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
@JsonSubTypes.Type(value = Dog.class, name = "Dog"),
@JsonSubTypes.Type(value = Cat.class, name = "Cat")
})
in the above example, we are defining the subclasses and a custom type.
Using a custome deserializer StdDeserializer<T>
Is there any other way to do this please tell me.
A:
If you can figure out a way to determine the object subtype from the JSON data, you could write a custom TypeId resolver to handle it for you. See Jackson Custom TypeId Resolver.
|
[
"stackoverflow",
"0041703574.txt"
] | Q:
Execute TestNG.xml from Jenkins (Maven Project)
My Project dosnt have a bin folder
Have tried the following:
D:>java -cp "Pathtolibfolder\lib*;Pathtobinfolder\bin"
org.testng.TestNG testng.xml
Any Ideas?
A:
If you are using Maven then i would simply use the surefire plugin and run tests as part of the build:
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>RELEASE</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
...
</plugins>
Just specify the path to your testng.xml and take advantage of it if you can use this kind of configuration.
It allows for tons of parametrization and i have used it extensively in my projects.
Check out this tutorial to get a hang of it: http://maven.apache.org/surefire/maven-surefire-plugin/examples/testng.html
|
[
"math.stackexchange",
"0003763546.txt"
] | Q:
Example of nonnegative random variables $X_n$ such that $\sum\limits_{n\ge1}X_n$ converges a.s. but $\sum\limits_{n\ge1}EX_n$ diverges.
Utilize series of the form $\sum\limits_{n\ge1}\frac{1}{n^p}$ to construct independent, nonnegative random variables $X_n$ such that $\sum\limits_{n\ge1}X_n$ converges a.s. but $\sum\limits_{n\ge1}EX_n$ diverges.
I am quite stumped on this one. I know $X_n=n\cdot\mathbb{1}_{(0,\frac{1}{n})}$ is a typical example of random variables such that
\begin{align*}
\sum_{n\ge1}EX_n=\sum_{n\ge1}n\cdot P\big(\big(0,\frac{1}{n}\big)\big)=\sum_{n\ge1}(1)=\infty
\end{align*}
However these random variables are not independent and I am not sure that $\sum\limits_{n\ge1}X_n$ converges a.s. If we let $A_n$ be disjoint intervals of length $\frac{1}{n}$ and set $X_n=n\cdot\mathbb{1}_{A_n}$, then the $X_n$ are independent this time and $\sum_{n\ge1}EX_n=\infty$ again, as above. But I am not sure that $\sum\limits_{n\ge1}X_n$ converges a.s., if they do, is there an nice way to see this? Any help with this or any other example of $X_n$'s that will satisfy the required properties would be greatly appreciated.
A:
Let $X_n:= n^\alpha \mathbf{1}_{A_n}$, where $(A_n)_{n\geqslant 1}$ is a sequence of independent sets and $A_n$ has probability $p_n$, with $\alpha$ and $p_n$ specified later. If $\sum_{n\geqslant 1}p_n$ converges, so does $\sum_{n\geqslant 1}X_n$, by using Borel-Cantelli lemma. Note that $EX_n=n^\alpha p_n$ hence we can choose $p_n=n^{-2}$ and $\alpha =2$ for example.
For the construction of the sequence of sets, one can work on an infinite product of the unit interval endowed with the Lebesgue measure.
|
[
"stackoverflow",
"0028756734.txt"
] | Q:
Error importing a Play project into IntelliJ
First of all, i'm not familiar with Java. I have done some small projects, but never did anything with Play.
I'm using Windows 8.1.
I created a project using activator new prj and then tried to import it into IntelliJ, using its built-in functionality.
When it finally tries to import, it gives me this stack trace:
Error:Error while importing SBT project:
...
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:34)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
at scala.collection.AbstractTraversable.map(Traversable.scala:105)
at sbt.Classpaths$.appRepositories(Defaults.scala:1524)
at sbt.Classpaths$$anonfun$40.apply(Defaults.scala:1040)
at sbt.Classpaths$$anonfun$40.apply(Defaults.scala:1040)
at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
at sbt.EvaluateSettings$MixedNode.evaluate0(INode.scala:177)
at sbt.EvaluateSettings$INode.evaluate(INode.scala:135)
at sbt.EvaluateSettings$$anonfun$sbt$EvaluateSettings$$submitEvaluate$1.apply$mcV$sp(INode.scala:67)
at sbt.EvaluateSettings.sbt$EvaluateSettings$$run0(INode.scala:76)
at sbt.EvaluateSettings$$anon$3.run(INode.scala:72)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
[error] java.net.URISyntaxException: Illegal character in authority at index 7: file://${activator.home}/repository
[error] Use 'last' for the full log.
See complete log in C:\Users\Ricardo\AppData\Local\Temp\sbt13.log
Yeah, the error seems pretty obvious: Illegal character in authority at index 7: file://${activator.home}/repository, because ${activator.home} is, of course, invalid syntax in a path.
Well, ${activator.home} looks like a variable. So I may be missing something here. Do I need to set this variable somewhere? How do I do that? In my system variables?
I don't think I should set variables, because I have done this before (creating a project and successfully import it in IntelliJ).
If this is not the problem, how could I possibly solve it?
A:
I have the same problem. @codegasmer is right, try to do "activator idea" and then "open" the project.
It seems to work, until they fix it.
If you're using activator 1.3 make sure you edit project/build.properties for sbt 0.13.7
|
[
"stackoverflow",
"0034313023.txt"
] | Q:
I get 0x80070057 error code on certcreatecertificatechainengine func
I use visual studio 2013 and windows 7 32bit.
I want to verify digital signature by root and chain of certificate.
So I get 0x80070057 error code in certcreatecertificatechainengine().
bool result = false;
HCERTCHAINENGINE hChainEngine;
CERT_CHAIN_ENGINE_CONFIG ChainConfig;
PCCERT_CHAIN_CONTEXT pChainContext;
//PCCERT_CHAIN_CONTEXT pDupContext;
HCERTSTORE hCertStore;
//PCCERT_CONTEXT pCertContext = NULL;
CERT_ENHKEY_USAGE EnhkeyUsage;
CERT_USAGE_MATCH CertUsage;
CERT_CHAIN_PARA ChainPara;
DWORD dwFlags = 0;
//LPWSTR pszNameString;
//---------------------------------------------------------
// Initialize data structures.
EnhkeyUsage.cUsageIdentifier = 0;
EnhkeyUsage.rgpszUsageIdentifier = NULL;
CertUsage.dwType = USAGE_MATCH_TYPE_AND;
CertUsage.Usage = EnhkeyUsage;
ChainPara.cbSize = sizeof(CERT_CHAIN_PARA);
ChainPara.RequestedUsage = CertUsage;
ChainConfig.cbSize = sizeof(CERT_CHAIN_ENGINE_CONFIG) * 4;
ChainConfig.hRestrictedRoot = NULL;
ChainConfig.hRestrictedTrust = NULL;
ChainConfig.hRestrictedOther = NULL;
ChainConfig.cAdditionalStore = 0;
ChainConfig.rghAdditionalStore = nullptr;
ChainConfig.dwFlags = CERT_CHAIN_CACHE_END_CERT;
ChainConfig.dwUrlRetrievalTimeout = 0;
ChainConfig.MaximumCachedCertificates = 0;
ChainConfig.CycleDetectionModulus = 0;
ChainConfig.hExclusiveRoot = NULL;
ChainConfig.hExclusiveTrustedPeople = NULL;
ChainConfig.dwExclusiveFlags = 0;
//---------------------------------------------------------
// Create the non default certificate chain engine.
if (!CertCreateCertificateChainEngine(
&ChainConfig,
&hChainEngine))
{
DWORD err = GetLastError();
MessageBox(NULL, L"The engine creation function failed.", L"Error ", MB_OK);
return false;
}
Also I see this post:
similar problem
and other
but I can not find solution.
A:
I found the solution.
In the project property page, I change the platform toolset to:
|
[
"tex.stackexchange",
"0000466803.txt"
] | Q:
Intersection of a circle and a line "path"
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}[
plotmark/.style = {%
solid, fill = red, circle, inner sep = 0pt, minimum size = 6pt
}
]
\coordinate (A) at (0,0);
\coordinate (B) at (1,1);
\coordinate (C) at (3,1);
\coordinate (D) at (4,0);
\draw[->] (A)--(B);
\draw[->] (D)--(C);
\draw[dashed] (A) circle [radius=2];
\coordinate (I) at (intersection cs:first line={(A)--(B)}, second line={(C)--(D)});
\node[plotmark, label={below:$A$}] at (A) {};
\node[plotmark, label={below:$D$}] at (D) {};
\node[plotmark, label={above:$I$}] at (I) {};
\end{tikzpicture}
\end{document}
In the above code, even though the line segments (A)--(B) and (D)--(C) do not meet, \coordinate (I) at (intersection cs:first line={(A)--(B)}, second line={(C)--(D)}); calculates the intersection point, and outputs:
Is there a way to use the intersection cs syntax to locate the intersection of the path AB with the circle?
The following syntax requires that the line segment and the circle actually meet:
\path[name path=Circle] (A) circle [radius=2];
\path[name path=AB] (A)--(B);
\path [name intersections={of=Circle and AB}];
\coordinate (I) at (intersection-1);
A:
There also exists the command \tkzInterLC from the tkz-euclide package that calculates the intersection points between a line and a circle even if they don't meet:
\documentclass{standalone}
\usepackage{tikz,tkz-euclide}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}[
plotmark/.style = {%
solid, fill = red, circle, inner sep = 0pt, minimum size = 6pt
}
]
\coordinate (A) at (0,0);
\coordinate (B) at (1,1);
\coordinate (C) at (3,1);
\coordinate (D) at (4,0);
\draw[->] (A)--(B);
\draw[->] (D)--(C);
\draw[dashed] (A) circle [radius=2];
\coordinate (I) at (intersection cs:first line={(A)--(B)}, second line={(C)--(D)});
\node[plotmark, label={below:$A$}] at (A) {};
\node[plotmark, label={below:$B$}] at (B) {};
\node[plotmark, label={below:$D$}] at (D) {};
\node[plotmark, label={above:$I$}] at (I) {};
\tkzInterLC[R](A,B)(A,2cm) % line (A,B) and circle(A,2cm)
\tkzGetPoints{E}{F} % intersection points
\node[plotmark, label={below:$E$}] at (E) {};
\node[plotmark, label={below:$F$}] at (F) {};
\end{tikzpicture}
\end{document}
A:
This answer comes with two styles intersection 1 of line and intersection 2 of line, which can be used e.g. like this:
\coordinate[intersection 1 of line={from A to B with circle around A with
radius 2cm}] (aux1);
As the syntax suggests, this will find one intersection of the line that runs through A and B with the circle of radius 2cm around A. Of course, the circle does not have to be around a point that the line runs through, as the following illustrates. This updated version uses xfp to avoid `dimension too large errors. (I wish I had tried this earlier. ;-)
\documentclass{standalone}
\usepackage{xfp}
\usepackage{tikz}
% smuggling from https://tex.stackexchange.com/a/470979/121799
\newcounter{smuggle}
\DeclareRobustCommand\smuggleone[1]{%
\stepcounter{smuggle}%
\expandafter\global\expandafter\let\csname smuggle@\arabic{smuggle}\endcsname#1%
\aftergroup\let\aftergroup#1\expandafter\aftergroup\csname smuggle@\arabic{smuggle}\endcsname
}
\DeclareRobustCommand\smuggle[2][1]{%
\smuggleone{#2}%
\ifnum#1>1
\aftergroup\smuggle\aftergroup[\expandafter\aftergroup\the\numexpr#1-1\aftergroup]\aftergroup#2%
\fi
}
\usetikzlibrary{intersections,calc}
\begin{document}
\tikzset{intersection warning/.code={\pgfmathtruncatemacro{\mysign}{sign(#1)+1}
\ifcase\mysign
\typeout{The\space line\space and\space circle\space do\space not\space
intersect.\space The\space intersections\space returned\space are\space fake.}
\or
\typeout{The\space line\space and\space circle\space intersect\space
only\space once.}
\or
\fi},
fpeval/.code n args={2}{\edef#1{\fpeval{#2}}%\typeout{#1}%
\smuggle[2]{#1}},
intersection 1 of line/.style args={from #1 to #2 with circle around #3 with radius #4}{%
insert path={let \p1=(#1),\p2=(#2),\p3=(#3)
in [fpeval={\mydisc}{{-((\y1/10)*(\x2/10) - (\x1/10)*(\y2/10) - (\y1/10)*(\x3/10) + (\y2/10)*(\x3/10) + (\x1/10)*(\y3/10) - (\x2/10)*(\y3/10))^2 +
(((\x1/10) - (\x2/10))^2 + ((\y1/10) - (\y2/10))^2)*(#4/10)^2}},
fpeval={\myfactor}{((\x1/10)^2 + (\y1/10)^2 + (\x2/10)*(\x3/10) - (\x1/10)*((\x2/10) + (\x3/10)) + (\y2/10)*(\y3/10) -
(\y1/10)*((\y2/10) + (\y3/10)) -
sqrt(abs(\mydisc)))/
(((\x1/10) - (\x2/10))^2 + ((\y1/10) - (\y2/10))^2)},
intersection warning=\mydisc]($(#1)+\myfactor*($(#2)-(#1)$)$)} },
intersection 2 of line/.style args={from #1 to #2 with circle around #3 with radius #4}{%
insert path={let \p1=(#1),\p2=(#2),\p3=(#3)
in [fpeval={\mydisc}{-((\y1/10)*(\x2/10) - (\x1/10)*(\y2/10) - (\y1/10)*(\x3/10) + (\y2/10)*(\x3/10) + (\x1/10)*(\y3/10) - (\x2/10)*(\y3/10))^2 +
(((\x1/10) - (\x2/10))^2 + ((\y1/10) - (\y2/10))^2)*(#4/10)^2},
fpeval={\myfactor}{((\x1/10)^2 + (\y1/10)^2 + (\x2/10)*(\x3/10) - (\x1/10)*((\x2/10) + (\x3/10)) + (\y2/10)*(\y3/10) -
(\y1/10)*((\y2/10) + (\y3/10)) + sqrt(abs(\mydisc)))/
(((\x1/10) - (\x2/10))^2 + ((\y1/10) - (\y2/10))^2)}]
[intersection warning=\mydisc] ($(#1)+\myfactor*($(#2)-(#1)$)$)} }
}
\begin{tikzpicture}[
plotmark/.style = {%
solid, fill = red, circle, inner sep = 0pt, minimum size = 6pt
}
]
\coordinate (A) at (0,0);
\coordinate (B) at (1,1);
\coordinate (C) at (3,1);
\coordinate (D) at (4,0);
\coordinate (E) at (1,0);
\coordinate (F) at (2,-1);
\coordinate (G) at (2,1);
\coordinate (H) at (3,1);
\draw[->] (A)--(B);
\draw[->] (D)--(C);
\draw[dashed] (A) circle [radius=2];
\coordinate (I) at (intersection cs:first line={(A)--(B)}, second line={(C)--(D)});
\node[plotmark, label={below:$A$}] at (A) {};
\node[plotmark, label={below:$D$}] at (D) {};
\node[plotmark, label={below:$E$}] at (E) {};
\node[plotmark, label={above:$I$}] at (I) {};
\coordinate[intersection 1 of line={from A to B with circle around A with
radius 2cm}] (aux1);
\typeout{aux2}
\coordinate[intersection 2 of line={from A to B with circle around A with
radius 2cm}] (aux2);
\node[plotmark, label={below:$I_1$}] at (aux1) {};
\node[plotmark, label={below:$I_2$}] at (aux2) {};
\coordinate[intersection 1 of line={from E to B with circle around A with
radius 2cm}] (aux3);
\coordinate[intersection 2 of line={from E to B with circle around A with
radius 2cm}] (aux4);
\node[plotmark, label={below:$I_1'$}] at (aux3) {};
\node[plotmark, label={below:$I_2'$}] at (aux4) {};
\coordinate[intersection 1 of line={from F to G with circle around A with
radius 2cm}] (aux5);
\coordinate[intersection 1 of line={from F to H with circle around A with
radius 2cm}] (aux6);
\end{tikzpicture}
\end{document}
Warnings are issued if there is no intersection and the user gets told if the line and the circle only intersect once. The advantage of the analytic computation is that the determination of the intersections does not alter the bounding box.
ADDENDUM: Not tested very well because I feel you should write a new question.
\documentclass{article}
\usepackage{xfp}
% smuggling from https://tex.stackexchange.com/a/470979/121799
\newcounter{smuggle}
\DeclareRobustCommand\smuggleone[1]{%
\stepcounter{smuggle}%
\expandafter\global\expandafter\let\csname smuggle@\arabic{smuggle}\endcsname#1%
\aftergroup\let\aftergroup#1\expandafter\aftergroup\csname smuggle@\arabic{smuggle}\endcsname
}
\DeclareRobustCommand\smuggle[2][1]{%
\smuggleone{#2}%
\ifnum#1>1
\aftergroup\smuggle\aftergroup[\expandafter\aftergroup\the\numexpr#1-1\aftergroup]\aftergroup#2%
\fi
}
\usepackage{tikz}
\usetikzlibrary{intersections,calc,through}
\tikzset{intersection warning/.code={\pgfmathtruncatemacro{\mysign}{sign(#1)+1}
\ifcase\mysign
\typeout{The\space line\space and\space circle\space do\space not\space
intersect.\space The\space intersections\space returned\space are\space fake.}
\or
\typeout{The\space line\space and\space circle\space intersect\space
only\space once.}
\or
\fi},
fpeval/.code n args={2}{\edef#1{\fpeval{#2}}%\typeout{#1}%
\smuggle[2]{#1}},
intersection 1 of line/.style args={from #1 to #2 with circle around #3 with radius #4}{%
insert path={let \p1=(#1),\p2=(#2),\p3=(#3)
in [fpeval={\mydisc}{-((\y1/10)*(\x2/10) - (\x1/10)*(\y2/10) - (\y1/10)*(\x3/10) + (\y2/10)*(\x3/10) + (\x1/10)*(\y3/10) - (\x2/10)*(\y3/10))^2 +
(((\x1/10) - (\x2/10))^2 + ((\y1/10) - (\y2/10))^2)*(#4/10)^2},
fpeval={\myfactor}{((\x1/10)^2 + (\y1/10)^2 + (\x2/10)*(\x3/10) - (\x1/10)*((\x2/10) + (\x3/10)) + (\y2/10)*(\y3/10) -
(\y1/10)*((\y2/10) + (\y3/10)) -
sqrt(abs(\mydisc)))/
(((\x1/10) - (\x2/10))^2 + ((\y1/10) - (\y2/10))^2)}]
[intersection warning=\mydisc] ($(#1)+\myfactor*($(#2)-(#1)$)$)} },
intersection 2 of line/.style args={from #1 to #2 with circle around #3 with radius #4}{%
insert path={let \p1=(#1),\p2=(#2),\p3=(#3)
in [fpeval={\mydisc}{-((\y1/10)*(\x2/10) - (\x1/10)*(\y2/10) - (\y1/10)*(\x3/10) + (\y2/10)*(\x3/10) + (\x1/10)*(\y3/10) - (\x2/10)*(\y3/10))^2 +
(((\x1/10) - (\x2/10))^2 + ((\y1/10) - (\y2/10))^2)*(#4/10)^2},
fpeval={\myfactor}{((\x1/10)^2 + (\y1/10)^2 + (\x2/10)*(\x3/10) - (\x1/10)*((\x2/10) + (\x3/10)) + (\y2/10)*(\y3/10) -
(\y1/10)*((\y2/10) + (\y3/10)) +
sqrt(abs(\mydisc)))/
(((\x1/10) - (\x2/10))^2 + ((\y1/10) - (\y2/10))^2)}]
[intersection warning=\mydisc] ($(#1)+\myfactor*($(#2)-(#1)$)$)} },
circle through 3 points/.style n args={3}{%
insert path={let \p1=($(#1)!0.5!(#2)$),
\p2=($(#1)!0.5!(#3)$),
\p3=($(#1)!0.5!(#2)!1!-90:(#2)$),
\p4=($(#1)!0.5!(#3)!1!90:(#3)$),
\p5=(intersection of \p1--\p3 and \p2--\p4)
in },
at={(\p5)},
circle through= {(#1)}
},
circle radius/.style args={#1 of circle at #2 through #3}{
insert path={let \p1=($(#2)-(#3)$),\n1={veclen(\x1,\y1)}
in \pgfextra{\xdef#1{\n1}}}}
}
\begin{document}
\section*{Intersection of circle with line}
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (1,1);
\coordinate (C) at (3,1);
\coordinate (D) at (4,0);
\coordinate (E) at (1,0);
\coordinate (F) at (2,-1);
\coordinate (G) at (2,1);
\draw (A) circle[radius=2cm];
\foreach \X in {A,B,...,G}
{\fill[blue] (\X) circle (2pt) node[above]{\X};}
%
\coordinate[intersection 1 of line={from A to B with circle around A with
radius 2cm}] (aux1);
\coordinate[intersection 2 of line={from A to B with circle around A with
radius 2cm}] (aux2);
\coordinate[intersection 1 of line={from E to B with circle around A with
radius 2cm}] (aux3);
\coordinate[intersection 2 of line={from E to B with circle around A with
radius 2cm}] (aux4);
\coordinate[intersection 1 of line={from F to G with circle around A with
radius 2cm}] (aux5);
\foreach \X in {1,...,5}
{\fill[red] (aux\X) circle (2pt) node[below]{\X};}
\end{tikzpicture}
\section*{Define the circle by center and point on it}
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (1,1);
\coordinate (C) at (3,1);
\coordinate (D) at (4,0);
\coordinate (E) at (1,0);
\coordinate (F) at (2,-1);
\coordinate (G) at (2,1);
\path[circle radius={\myradius} of circle at A through G];
\draw (A) circle[radius=\myradius];
\foreach \X in {A,B,...,G}
{\fill[blue] (\X) circle (2pt) node[above]{\X};}
%
\coordinate[intersection 1 of line={from A to B with circle around A with
radius \myradius}] (aux1);
\coordinate[intersection 2 of line={from A to B with circle around A with
radius \myradius}] (aux2);
\coordinate[intersection 1 of line={from E to B with circle around A with
radius \myradius}] (aux3);
\coordinate[intersection 2 of line={from E to B with circle around A with
radius \myradius}] (aux4);
\coordinate[intersection 1 of line={from F to G with circle around A with
radius \myradius}] (aux5);
\foreach \X in {1,...,5}
{\fill[red] (aux\X) circle (2pt) node[below]{\X};}
\end{tikzpicture}
\section*{Define the circle by 3 points}
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (1,1);
\coordinate (C) at (3,1);
\coordinate (D) at (4,0);
\coordinate (E) at (1,0);
\coordinate (F) at (2,-1);
\coordinate (G) at (2,1);
\node[circle through 3 points={A}{F}{D},draw] (CN){};
\path[circle radius={\myradius} of circle at CN.center through D];
\draw[red,dashed] (CN.center) circle[radius=\myradius];
\foreach \X in {A,B,...,G}
{\fill[blue] (\X) circle (2pt) node[above]{\X};}
%
\coordinate[intersection 1 of line={from E to C with circle around CN.center with
radius \myradius}] (aux1);
\foreach \X in {1}
{\fill[red] (aux\X) circle (2pt) node[below]{\X};}
\end{tikzpicture}
\end{document}
ADDENDUM II: What can one do when dimension too large errors occur? The infamous dimension too large errors can occur with any coordinate computations, so they can occur here. One way to partly avoid them is to work with the fpu library. (Note, however, that you may have to switch off fpu (locally) if you work with the math library, say.) This alone does not (necessarily) fix the issue, but after rewriting the computations in such a way that a characteristic scale auxmax gets identified and all dimensions divided by it seems to work.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{intersections,calc}
\usetikzlibrary{fpu}
\begin{document}
\tikzset{declare
function={auxmax(\x,\y,\u,\v,\r,\s,\z)=sqrt(\x^2+\y^2+\u^2+\v^2+\r^2+\s^2+\z^2);
auxone(\x,\y,\u,\v,\r,\s,\z)=
-((\y/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\u/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\x/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\v/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\y/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\r/auxmax(\x,\y,\u,\v,\r,\s,\z)) + (\v/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\r/auxmax(\x,\y,\u,\v,\r,\s,\z)) + (\x/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\s/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\u/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\s/auxmax(\x,\y,\u,\v,\r,\s,\z)))^2 +
(((\x/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\u/auxmax(\x,\y,\u,\v,\r,\s,\z)))^2 + ((\y/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\v/auxmax(\x,\y,\u,\v,\r,\s,\z)))^2)*(\z/auxmax(\x,\y,\u,\v,\r,\s,\z))^2;
auxtwo(\x,\y,\u,\v,\r,\s,\z)=
((\x/auxmax(\x,\y,\u,\v,\r,\s,\z))^2 + (\y/auxmax(\x,\y,\u,\v,\r,\s,\z))^2 + (\u/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\r/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\x/auxmax(\x,\y,\u,\v,\r,\s,\z))*((\u/auxmax(\x,\y,\u,\v,\r,\s,\z)) + (\r/auxmax(\x,\y,\u,\v,\r,\s,\z))) + (\v/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\s/auxmax(\x,\y,\u,\v,\r,\s,\z)) -
(\y/auxmax(\x,\y,\u,\v,\r,\s,\z))*((\v/auxmax(\x,\y,\u,\v,\r,\s,\z)) + (\s/auxmax(\x,\y,\u,\v,\r,\s,\z))) -
sqrt(abs(\n1)))/
(((\x/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\u/auxmax(\x,\y,\u,\v,\r,\s,\z)))^2 + ((\y/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\v/auxmax(\x,\y,\u,\v,\r,\s,\z)))^2);
auxthree(\x,\y,\u,\v,\r,\s,\z)=-((\y/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\u/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\x/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\v/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\y/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\r/auxmax(\x,\y,\u,\v,\r,\s,\z)) + (\v/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\r/auxmax(\x,\y,\u,\v,\r,\s,\z)) + (\x/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\s/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\u/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\s/auxmax(\x,\y,\u,\v,\r,\s,\z)))^2 +
(((\x/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\u/auxmax(\x,\y,\u,\v,\r,\s,\z)))^2 + ((\y/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\v/auxmax(\x,\y,\u,\v,\r,\s,\z)))^2)*(\z/auxmax(\x,\y,\u,\v,\r,\s,\z))^2;
auxfour(\x,\y,\u,\v,\r,\s,\z)=((\x/auxmax(\x,\y,\u,\v,\r,\s,\z))^2 + (\y/auxmax(\x,\y,\u,\v,\r,\s,\z))^2 + (\u/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\r/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\x/auxmax(\x,\y,\u,\v,\r,\s,\z))*((\u/auxmax(\x,\y,\u,\v,\r,\s,\z)) + (\r/auxmax(\x,\y,\u,\v,\r,\s,\z))) + (\v/auxmax(\x,\y,\u,\v,\r,\s,\z))*(\s/auxmax(\x,\y,\u,\v,\r,\s,\z)) -
(\y/auxmax(\x,\y,\u,\v,\r,\s,\z))*((\v/auxmax(\x,\y,\u,\v,\r,\s,\z)) + (\s/auxmax(\x,\y,\u,\v,\r,\s,\z))) +
sqrt(abs(\n1))/
(((\x/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\u/auxmax(\x,\y,\u,\v,\r,\s,\z)))^2 + ((\y/auxmax(\x,\y,\u,\v,\r,\s,\z)) - (\v/auxmax(\x,\y,\u,\v,\r,\s,\z)))^2);
}}
\tikzset{intersection warning/.code={\pgfmathtruncatemacro{\mysign}{sign(#1)+1}
\ifcase\mysign
\typeout{The\space line\space and\space circle\space do\space not\space
intersect.\space The\space intersections\space returned\space are\space fake.}
\or
\typeout{The\space line\space and\space circle\space intersect\space
only\space once.}
\or
\fi},
intersection 1 of line/.style args={from #1 to #2 with circle around #3 with radius #4}{%
insert path={let \p1=(#1),\p2=(#2),\p3=(#3),
\n1={auxone(\x1,\y1,\x2,\y2,\x3,\y3,#4)},
\n2={auxtwo(\x1,\y1,\x2,\y2,\x3,\y3,#4)}
in [intersection warning=\n1]($(#1)+\n2*($(#2)-(#1)$)$)} },
intersection 2 of line/.style args={from #1 to #2 with circle around #3 with radius #4}{%
insert path={let \p1=(#1),\p2=(#2),\p3=(#3),
\n1={auxthree(\x1,\y1,\x2,\y2,\x3,\y3,#4)},
\n2={auxfour(\x1,\y1,\x2,\y2,\x3,\y3,#4)}
in [intersection warning=\n1] ($(#1)+\n2*($(#2)-(#1)$)$)} }
}
\begin{tikzpicture}[/pgf/fpu=true,/pgf/fpu/output format=fixed]
\pgfmathsetmacro{\myConstant}{5*sqrt(2)}
\coordinate (A) at (0,0);
\coordinate (B) at (0, \myConstant);
\coordinate (C) at (10, \myConstant);
\coordinate (D) at (10,0);
\coordinate (midBC) at (5, \myConstant);
\coordinate (midAD) at (5, 0);
\coordinate[intersection 1 of line={from midBC to A with circle around midAD with radius 5cm}] (aux1);
\foreach \X in {A,B,C,D,midBC,midAD,aux1}
{\fill (\X) circle(1pt) node[above]{\X};}
\end{tikzpicture}
\end{document}
|
[
"stackoverflow",
"0016151557.txt"
] | Q:
Android Spinner from a Directory - Only show part of filepath and only files with a certain extension?
I currently have a spinner that is populated using the following;
File sd = new File("sdcard/");
File[] sdDirList = sd.listFiles();
// String[] filenames = getApplicationContext().fileList();
List<File> list = new ArrayList<File>();
for (int i = 0; i < sdDirList.length; i++) {
// Log.d("Filename", filenames[i]);
list.add(sdDirList[i]);
}
ArrayAdapter<File> filenameAdapter = new ArrayAdapter<File>(this,
android.R.layout.simple_dropdown_item_1line, list);
spinSelected.setOnItemSelectedListener(this);
spinSelected.setAdapter(filenameAdapter);
// filename = spinSelected.toString();
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
filename = spinSelected.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
But I have two things I'd like to do with this spinner and can't work out either. The first is to only display files with a .txt extension. As is it displays everything on the sdcard, but I'm only interested in .txt.
In addition, the spinner currently displays the full path of sdcard/filename.extension whereas ideally I'd like it to just show filename - is that possible?
Thanks in advance.
A:
You're going to have to further process your sdDirList array by adding something like:
for(int x = 0; x < sdDirList.length; x++)
{
if(sdDirList[n].getName().endsWith(".txt"))
{
// add it to your array adapter
}
}
You may wish to review Java File object doc here: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
|
[
"stackoverflow",
"0013474611.txt"
] | Q:
Scope, method return
I been trying to write a program that can display the fibonacci sequence. However any number I input will output 0. I suspect that it has either to do with scope of the variable or something wrong with my return. could someone look at my code and figure out if it is really those problems? I'm sorta new to java, so even the basic is difficult for me.
public static void main(String args [])
{
Scanner in = new Scanner(System.in);
int number = 0;
do{
System.out.print("Which Fibonacci Number would you like? ");
fib = in.nextInt();
}while(number < 0 || number > 71);
System.out.print("Fibonacci #"+number+" is "+fibcalc(fib)+"\n");
}
public static double fibcalc(double number)
{
double prevNumber1 = 0;
double prevNumber2 = 1;
double fib = 0;
for(int i =0; i < number; i++){
fib = prevNumber1;
prevNumber1 = prevNumber2;
prevNumber2 = fib + prevNumber2;
}
return fib;
}
made some revisions, down to one error.
error: cannot find symbol
System.out.print("Fibonacci #"+number+" is "+fibcalc(fib)+"\n");
symbol: variable fib
I got a qucik question.
can one method call upon another method for a variable? the variable is inside of the curly braces. kind of what I have in my code.it seems like most of my errors were similar to this one.
A:
It's nothing to do with scope. Look at this code:
while(i < fib){
fib = prevNumber1;
...
}
You're using the fib variable as both "the number of iterations to execute" and "the current result". Those are two separate concepts, and should be stored in separate variables.
In particular, on the first iteration, fib will be set to 0 and i will be incremented to 1... so your loop will then terminate, returning 0.
I'd also suggest changing your parameter type to int and using long or BigInteger for the Fibonacci number variables (depending on what range you want to support). There's no part of this problem which needs non-integer values, so you shouldn't be using double at all.
Finally, I'd suggest using a for loop instead of a while loop - you want to perform a given number of iterations, and the idiomatic way of writing that in Java is:
for (int i = 0; i < count; i++) {
// whatever
}
|
[
"stackoverflow",
"0017717042.txt"
] | Q:
Overload Templated Function for All String Types
I have the following template:
template<class T>
void fn(T t){ }
and I'd like to override its behavior for anything that can be converted to std::string.
Both specifying an explicit template specialization and a non-template function overload with the parameter as an std::string only work for calls that pass in an std::string and not other functions, since it seems to be matching them to the template before attempting argument conversion.
Is there a way to achieve the behavior I want?
A:
Something like this case help you in C++11
#include <type_traits>
#include <string>
#include <iostream>
template<class T>
typename std::enable_if<!std::is_convertible<T, std::string>::value, void>::type
fn(T t)
{
std::cout << "base" << std::endl;
}
template<class T>
typename std::enable_if<std::is_convertible<T, std::string>::value, void>::type
fn(T t)
{
std::cout << "string" << std::endl;
}
int main()
{
fn("hello");
fn(std::string("new"));
fn(1);
}
live example
And of course, you can realize it manually, if you have no C++11, or use boost.
|
[
"stackoverflow",
"0051074564.txt"
] | Q:
PyZMQ ( ZeroMQ ) - How to get a subscription key from a SUB-socket?
I would like to get the subscription key of a subscriber ( SUB ) socket after it has been set.
Say I have the following socket :
import zmq
ctx = zmq.Context.instance()
sub_sock = ctx.socket(zmq.SUB)
sub_sock.bind("tcp://127.0.0.1:6667")
sub_sock.setsockopt(zmq.SUBSCRIBE, "foo1".encode('ascii'))
What I want to do is something like this ( pseudo-code ) :
sub_key = sub_sock.get_sub_key().decode("ascii")
sub_key = subkey[:-1] + "2" # "foo2"
# unsubscribe all keys
sub_sock.setsockopt(zmq.UNSUBSCRIBE, '')
# subscribe to new key
sub_sock.setsockopt(zmq.SUBSCRIBE, sub_key.encode('ascii'))
Question :
However, I cannot discover a function that can retrieve the key of the subscriber socket. How can I retrieve the socket's subscription key?
System :
Python 3.6
libzmq version: 4.2.5
pyzmq version: 17.0.0
A:
How can I retrieve the socket's subscription key ( ... after it has been set ) ?
Yes, one can, but only on PUB-side ( well, actually the XPUB clone of the PUB-behaviour archetype ) if that have been carefully configured with .setsockopt( { XPUB_VERBOSE | XPUB_VERBOSER }, 1 ) method so as to start serving channel-associated (X)SUB-s in this particular mode.
So, in an extreme need ( in a case of a SUB-side total loss of context or suffering from amnesia of it's own subscription-management ), one can setup the XSUB to also instantiate a utilitarian XPUB-instance with this additional .setsockopt( { XPUB_VERBOSE | XPUB_VERBOSER }, 1 ) configuration, { .bind() | .connect() } a link from-Home-Base to-Home-Base, and handle all the arrived (X)SUB-subscription details on-the-fly.
The native API documentation publishes all the details for doing this right.
A unique approach to learn one's own subscription details from a wire-tapping, yet doable.
Final remarks :
The ZeroMQ topic-filter is designed in a way more complex manner and optimised for speed ( high throughput, low latency ). It may handle units, hundreds, thousands, tens of thousands of subscriptions for each of the { .bind() | .connected() } peers.
These design-aspirations and focus on performance was the reason, there is no such function for ex-post asking a "librarian" for finding all "my own" subscription keys ( no matter if never remembered or plain forgotten ).
One may also realise, that since API v4.x, the ZeroMQ native handling started to manage topic-filtering on the (X)PUB-side, while older API versions reported this performance-critical operation to be deferred onto each of the (X)SUB-side(s), at the cost of the increased cummulative volumes of raw-network traffic, as all messages ( yes, indeed, ALL MESSAGES ) went from (X)PUB to all (X)SUB-s. Did anyone mention security concerns here?
# unsubscribe all keys // THIS WILL NOT FLY THAT WAY
The same reasoning stands behind a "missing" API call, asking for "forget all my own subscriptions", but one has to explicitly unsubscribe, in a one by one manner, or properly .close() the (X)SUB-side socket-instance and rather re-instantiate another one on a green field basis and re-{ .bind() | .connect() } it back to the infrastructure, so as to meet the set goal en-bloc.
|
[
"stackoverflow",
"0004837278.txt"
] | Q:
Filter out numbers in a string in php
assuming i have these texts 'x34' , '150px' , '650dpi' , 'e3r4t5' ... how can i get only numbers ? i mean i want 34 , 150 , 650 , 345 without any other character . i mean get the numbers this string has into one variable .
A:
$str = "e3r4t5";
$str_numbers_only = preg_replace("/[^\d]/", "", $str);
// $number = (int) $str;
A:
Sorry for joining the bandwagon late, rather than using Regex, I would suggest you use PHP's built in functions, which may be faster than Regex.
filter_var
flags for the filters
e.g. to get just numbers from the given string
<?php
$a = '!a-b.c3@j+dk9.0$3e8`~]\]2';
$number = str_replace(['+', '-'], '', filter_var($a, FILTER_SANITIZE_NUMBER_INT));
// Output is 390382
?>
To adhere to more strict standards for your question, I have updated my answer to give a better result.
I have added str_replace, as FILTER_SANITIZE_NUMBER_FLOAT or INT flag will not strip + and - chars from the string, because they are part of PHP's exception rule.
Though it has made the filter bit long, but it's now has less chance of failing or giving you unexpected results, and this will be faster than REGEX.
Edit:
1: Realized that with FILTER_SANITIZE_NUMBER_FLOAT, PHP won't strip these characters optionally .,eE, hence to get just pure numbers kindly use FILTER_SANITIZE_NUMBER_INT
2: If you have a PHP version less than 5.4, then kindly use array('+', '-') instead of the short array syntax ['+', '-'].
A:
You can use a regular expression to remove any character that is not a digit:
preg_replace('/\D/', '', $str)
Here the pattern \D describes any character that is not a digit (complement to \d).
|
[
"math.stackexchange",
"0002035258.txt"
] | Q:
Need help showing a map is a bijection between two linearly independent subsets of an R-module.
Let $M$ be a finitely generated $R$-module, where $R$ is an integral domain. Let $N$ be a submodule of $M$. Let $B'$ be a maximal linearly independent subset of $M/N$ and define $B=\{x\in M \mid x+N\in B'\}$. I want to show that $|B|=|B'|$.
Consider the following function: $f:B\rightarrow B', f(b)=b+N$. If $b\in B$, then by definition $b+N\in B'$. If $a=b$, then $a-b=0\in N$ so that $a-b+N=N$ and thus $a+N=b+N$. So we have shown that $f$ is well defined and defined everywhere.
Suppose $y\in B'$ then there exists $b\in B$ s.t. $b+N=y$ and so $f$ is surjective.
I am having problems showing that $f$ is injective. I tried to start it but I get nowhere fast. If $f(a)=f(b)$ then $a+N=b+N$ and so $a-b+N=0$. I am not sure what to do next. I am guessing that the linearly independence of $B'$ will come into play but I can't figure out how.
I would love some help.
A:
Your map $f$ is never injective if $N \neq 0$, since its fibres have cardinality $|N|$ by the virtue of $f(b)=f(b+n)$ for all $n \in N$. Thus $|B| = |B'| \cdot |N|$, which is greater than $|B'|$ whenever $N \neq 0$, since $|B'|$ is finite.
However, by picking a set of representatives of $B'$ in $M$, you can achieve the map to become injective without losing the surjectivity.
|
[
"drupal.stackexchange",
"0000024199.txt"
] | Q:
How does `drush features-update` work?
I have made changes to a Feature on a Drupal 7 site. I want the same feature to be updated in another website. How to do it using the drush features-update command? When I run it, it asks to overwrite the previous Feature, but nothing new comes in the Feature.
A:
Drush feature-update updates the feature code with overwritten settings. So the function is used to export changes to code.
If you want to take those changes to another site, you will have to copy the updated feature to the other site unless they share the same code (and then revert the feature and clear cache (not always needed)).
In code it could look like this
$ drush fu feature_module
$ cp -r feature_module ./DIR
$ cd DIR
$ drush fr feature_module
|
[
"stackoverflow",
"0024357112.txt"
] | Q:
Mongoose findOne not completing
After trying to debug myself and searching google, my mongoose findOne is not completing! it get's to the line and just does not end, until a timeout about 2 minutes later. Here is the code in order of which it is called
----------------Routing
// process the signup form
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/', // redirect back to the home page if there is an error
failureFlash : true // allow flash messages
}));
------------ Passport Processing
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback: true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function (req, email, password, done) {
// asynchronous
process.nextTick(function () {
// Whether we're signing up or connecting an account, we'll need
// to know if the email address is in use.
UserController.findUserByEmail(email, function (existingUser) {
console.log(existingUser);
// check to see if there's already a user with that email
if (existingUser)
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
// If we're logged in, we're connecting a new local account.
if (req.user) {
var user = req.user;
user.email = email;
user.password = encrypt.encrypt(password);
user.save(function (err) {
if (err)
throw err;
return done(null, user);
});
}
// We're not logged in, so we're creating a brand new user.
else {
console.log("there");
// create the user
User.createUser(req.body.username, email, req.body.username, password, "0", 1, function (result) {
return done(null, result);
});
}
});
});
}));
------------------Created Data Client (UserController)
exports.findUserByEmail = function(email, callback){
User.findOne({email : email}, function(err, result){
if(err){
throw err;
}else{
callback(result);
}
});
};
------------------User Schema
//user Schema
var userSchema = mongoose.Schema({
name : String,
email : String,
userName : String,
password : String,
IP : String,
//type of user. It can be a user admin 0, user student 1, user presentor (professor) 2, (user guest 3) ?.
type : Number
});
//instance of my schema
var User = mongoose.model('User', userSchema);
The code runs to right before User.findOne(); and then just hangs. Adding some debugging statements shows that everything up to that method is called, but it never enters the callback. It just sits waiting.
Other queries for other schema have worked fine, and return very quickly.
I've added an error event listener for mongoose and nothing comes up.
My express server also only runs once the connection is open, so that rules that out.
Any help you can provide would be greatly appreciated!
-Stephen
A:
I faced this same problem. The issue for me was that I was using mongoose.createConnection
let connection = mongoose.createConnection(url, ...)
but then trying to use mongoose to create the model
let Tank = mongoose.model('Tank', yourSchema);
When you use createConnection you need to use that connection - https://mongoosejs.com/docs/models.html#constructing-documents.
let Tank = connection.model('Tank', yourSchema);
A:
I have fixed the issue:
Controller File was part of another node project in the parent directory. I assume then node did not default to reading the current node process loaded modules, but tried to read the other node projects, which is not running at the time. Just moving the files into the same node project folder fixed the issue.
|
[
"tex.stackexchange",
"0000210778.txt"
] | Q:
Solutions involving random values in the probsoln package
Over the past few years, I have constructed a large number of math questions which are stored in various external files. I access them for my quizzes via the probsoln package.
I typically construct the questions using quite a few randomly-generated values. The trouble comes when I try to access the solutions using the "second-pass" suggestion (the first pass producing the quiz, the second the answer key).
Here is a very abbreviated MWE.
\documentclass{article}
\usepackage{probsoln}
\newcounter{firstNum}
\newcounter{secondNum}
\newcounter{answerNum}
\begin{document}
\hideanswers
\loadallproblems{MWEQuestions}
Quiz:
\begin{enumerate}
\foreachproblem{%
\item \thisproblem
}
\end{enumerate}
\medskip
Answer Key:
\showanswers
\begin{enumerate}
\foreachproblem{%
\item \thisproblem
}
\end{enumerate}
\end{document}
The question is stored in an external file, and has this format:
\newproblem{question1}{%
\random{firstNum}{1}{5}
\random{secondNum}{6}{10}
\defcounter{answerNum}{\thefirstNum+\thesecondNum}
\(\thefirstNum + \thesecondNum=\)
}{%
\thefirstNum+\thesecondNum = \theanswerNum
}
When run, the output looks like this:
Quiz:
2 + 9 =
Answer Key:
4 + 10 =
Solution: 4 + 10 = 14
Obviously the second iteration through has re-randomized the counter values. I need some way to preserve the selected values from being over-written so they can be accessed when the solutions are generated.
Another (possible) wrinkle is that most of my problems use the same counters over again. So the definition of question 2 would also assign random values to the counters. So it's not just a matter of preventing the solutions pass from overwriting the counter values, but the next question as well.
Thanks for any help you can give!
[EDIT]
I may have found a solution. It works with my MWE, but before I post it, I want to test it in a slightly more robust setting.
A:
The following code seems to work, for simple cases at least. The first block of code is the quiz itself. It opens a write stream and loads the questions from an external file. The second block of code is the file containing the questions, and this is where the actual writing and reading of the solution is done.
\documentclass{article}
\usepackage{probsoln}
\newwrite\answerfile %Going to store current values in an external file
%Counters to hold randomly generated values for the math questions
\newcounter{firstNum}
\newcounter{secondNum}
\newcounter{answerNum}
\begin{document}
\immediate\openout\answerfile=MWEAnswers.tex %Write to the files immediately
\loadallproblems{MWEQuestions} %Load all problems from external file
%Start typesetting the quiz questions
Quiz:
\begin{enumerate}
\foreachproblem{% %Iterates through the loaded problems
\item \thisproblem %Typesets the current problem
}
\end{enumerate}
\immediate\closeout\answerfile %Done writing to the answer file
\medskip
\immediate\openin\answerfile=MWEAnswers.tex %Now we want to read from the answer file
\showanswers %Boolean to allow typesetting the answers
% Start Answer Key
Answer Key:
\begin{enumerate}
\foreachproblem{ %Again, iterate through the loaded problems
\item \thisproblem
}
\end{enumerate}
\end{document}
Here is the code for the question file. Note that in order to see that multiple questions didn't cause problems the problem contains the definitions of two separate problems. In terms of code, these are identical (other than one is an addition question and the other a subtraction.
\newproblem{question1}{ %Define Question 1
\random{firstNum}{1}{5} %Randomly generate values
\random{secondNum}{6}{10}
\defcounter{answerNum}{\thefirstNum+\thesecondNum} %Calculate answer
\begin{onlyproblem} %This code only runs if the answers
%are NOT being typeset
\(\thefirstNum + \thesecondNum=\) %Typeset the question for the quiz
%Write question to external answer file
\immediate\write\answerfile{\thefirstNum+\thesecondNum=\theanswerNum}
\end{onlyproblem}
}{ %This reads in the solution.
\read\answerfile to \fileline
$\fileline$
}
%%% Second Question--Code Identical to the First
\newproblem{question2}{% % Define Question 2
\random{firstNum}{1}{5}
\random{secondNum}{6}{10}
\defcounter{answerNum}{\thefirstNum-\thesecondNum}
\begin{onlyproblem}
\(\thefirstNum - \thesecondNum=\) % Print the question
\immediate\write\answerfile{\thefirstNum-\thesecondNum=\theanswerNum}
\end{onlyproblem}
}{%
\read\answerfile to \fileline
$\fileline$
}
The output for this code is
|
[
"stackoverflow",
"0056617729.txt"
] | Q:
What is the use of : in Dart function?
I am testing some Flutter application and encounter : in a Dart Function, What is it used for?
I found it in Firebase for Flutter tutorial. I tried to search it in google, but can't find anything.
class Record {
final String name;
final int votes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['votes'] != null),
name = map['name'],
votes = map['votes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
@override
String toString() => "Record<$name:$votes>";
}
The Result is working fine, i just want to know what is the : used for.
A:
Got from https://dart.dev/guides/language/language-tour, section Constructor:
Superclass
Specify the superclass constructor after a colon (:), just before the constructor body (if any).
class Employee extends Person {
Employee() : super.fromJson(getDefaultData());
// ···
}
Instance variables
Besides invoking a superclass constructor, you can also initialize instance variables before the constructor body runs. Separate initializers with commas.
// Initializer list sets instance variables before
// the constructor body runs.
Point.fromJson(Map<String, num> json)
: x = json['x'],
y = json['y'] {
print('In Point.fromJson(): ($x, $y)');
}
Your example:
So in your case the fromMap-Method does some assertions (before running the constructor) and assigns the variables name and vote. As these variables are final, they have to be assigned before initializing a record instance!
fromSnapshot just uses fromMap as super constructor.
|
[
"serverfault",
"0000493348.txt"
] | Q:
Setting up Firewall in CentOS 6.4
I need to ask a general question about installing certain packages and the need to make iptable adjustments in centOS; When I installed the apache package and put a simple test page in /var/www/html, it didn't want to pull up until I actually went to the ipTables and added a line to open port 80. I have the same problem now with setting up ftp & vsftpd. They are being more stubborn though. I've added port 20 and 21 to the iptables and I was still getting refused. I stopped the iptables and was able to get FileZilla to connect.
One of my coworkers told me that I should not even have to do this. That just installing the packages should take care of all the configuration settings. Is he right? Is centOS6.4 still so new that it has bugs?
I have reviewed a few docs on setting up vsftpd but they vary.
help appreciated.
Here is my output from the iptables:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 ACCEPT tcp -- any any anywhere anywhere tcp dpt:ftp
0 0 ACCEPT tcp -- any any anywhere anywhere tcp dpt:ftp-data
0 0 ACCEPT tcp -- any any anywhere anywhere tcp dpt:https
6 725 ACCEPT tcp -- any any anywhere anywhere tcp dpt:http
20 1376 ACCEPT all -- any any anywhere anywhere state
RELATED,ESTABLISHED
0 0 ACCEPT icmp -- any any anywhere anywhere
0 0 ACCEPT all -- lo any anywhere anywhere
0 0 ACCEPT tcp -- any any anywhere anywhere state NEW tcp dpt:ssh
557 91720 REJECT all -- any any anywhere anywhere reject-with icmp-host-prohibited
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 REJECT all -- any any anywhere anywhere reject-with icmp-host-prohibited
Chain OUTPUT (policy ACCEPT 18 packets, 3833 bytes)
pkts bytes target prot opt in out source destination
0 0 ACCEPT tcp -- any any anywhere anywhere tcp dpt:ftp-data
0 0 ACCEPT tcp -- any any anywhere anywhere tcp dpt:ftp
A:
You're missing a rule to accept traffic based on existing traffic (the rule that makes iptables stateful). This should be your very first rule:
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
|
[
"mechanics.stackexchange",
"0000028003.txt"
] | Q:
Ford Econoline Van AC Failing
If the vents start putting out hot air when accelerating or driving up hills but are ice cold when idling, is that a sign of a failing blower pump or leak? I am dealing with a Ford Econoline E350.
Refrigerant is obviously not the problem because the air is cold when idling. The air usually stays cold in the front but the back half of the vehicle's vents are blowing out hot air.Any ideas?
A:
The air conditioner on this vehicle uses a vacuum powered HVAC controls. A leak anywhere in the vacuum system can cause this symptom. One way to test for leaks is to apply low pressure air (10psi) into the system and listen for leaks. Leaks at the vacuum reservoir are common. So is the line to the air recirculation valve because it is close to the passengers right foot.
|
[
"wordpress.stackexchange",
"0000222162.txt"
] | Q:
Creating adminable dynamic filtering on custom post type
My overall goal is to have a custom post type and on the archive page have several different filters in the sidebar, like on a lot of ecom sites. I think this would normally be done in Wordpress using several taxonomies. In my case I need these filters to be dynamic, meaning the client can log-in to the admin and add filters and options under those filters.
I am looking for any advice on how to achieve this, without a plugin.
I was thinking...Use advanced custom fields to dynamically create new taxonomies. Then I could use those taxonomies to filter my post type.
Any help would be appreciated!
FYI - I am in the early stages and trying to plan this out, I haven't coded anything.
A:
Recommended (CPT):
Easier option is to get a custom post type plugin that also has a feature to create custom taxonomies. It is very flexible and let's you configure it precisely you want it to behave like and in the end you can export the code that generates your custom taxonomies and add it to your functions.php so you would save db hits. You can also install ACF to add custom fields to your taxonomy terms.
Using only ACF:
Advanced custom fields itself do not let you create new taxonomies, it can only display your custom input fields on the admin page you want with ease. It also binds that field with the page/term/post/cpt/page/user depending on where you set the field to show up. Ex you create a custom field input named post_subtitle and set it to show up on post edit page, now that field is automatically bind with post type post and it will save field values to wp_postmeta table. If you would add that field to a user page it would save its data to wp_usermeta table.
What you can do with ACF is have a repeater field plugin for it and also options page plugin (they are all included in ACF 5 Pro). Create a repeater field called custom_taxonomies and set that field to show up on options page. That field data will be saved to wp_options table. Now in your functions.php (if you code in theme) loop through that repeater field and register your taxonomies using wp's register_taxonomy method. If your not familiar with wp actions and filters i suggest you get familiar with them, because you have to set your code blocks to run at correct actions for them to show up in wp admin.
Custom code:
If you want to code this yourself you have to keep in mind that taxonomies are not held in database by default but taxonomy terms are. I would go with same approach as woocommerce does, create a new database table where you hold your taxonomy info and load them up every time you need them. Create new admin page and display input field(s) where you can add new taxonomies, edit existing ones etc. It is all doable but this method takes a lot of time and code and is not usually worth it because there are very reliable plugins that can help you inventing the wheel part.
|
[
"stackoverflow",
"0017486152.txt"
] | Q:
Why am I receiving an exception on my server when creating a TIFF?
I only receive an exception on my Windows Server Datacenter 2007 SP 2 server, not on my local Windows 7 PC.
I have wrapped the problematic call in a try-catch-finally, so that the rest of the program may execute normally.
How do I resolve the exception and generate the TIFF correctly on the server?
Exception:
System.Runtime.InteropServices.ExternalException:
A generic error occurred in GDI+. at System.Drawing.Image.Save(String
filename, ImageCodecInfo encoder, EncoderParameters encoderParams) at
TSEmails.TaskScheduleSlippage.CreateTIFFImageReport(DataTable
dataOfManyProjects, String fileName) in
D:\TSEmail\TSEmails\TaskScheduleSlippage.cs:line 236 at
TSEmails.TaskScheduleSlippage.GenerateOrganizationalEmail(DataTable
dataOfManyProjects, DataTable emailSettings) in
D:\TSEmail\TSEmails\TaskScheduleSlippage.cs:line 92
Line of code throwing the exception:
tiffImage.Save(fileName, info, encoderparams);
Relevant code:
private static void CreateTIFFImageReport(DataTable dataOfManyProjects, string fileName)
{//Line:210
///The following code was originally taken from http://www.yoursearchbuddy.com/create-tiff-image-multiple-images
///on Thursday May 9, 2013
//Selecting the image encoder
System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;
ImageCodecInfo info = null;
info = (from ie in ImageCodecInfo.GetImageEncoders()
where ie.MimeType == "image/tiff"
select ie).FirstOrDefault();
EncoderParameters encoderparams = new EncoderParameters(2);
encoderparams.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
encoderparams.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 4L);
//Adding graphs of each project to TIFF image
Bitmap tiffImage = null;
Image img = null;
foreach (DataRow row in dataOfManyProjects.DefaultView.ToTable(true, "Project Code").Rows)
{
string projectCode = row["Project Code"].ToString();
img = Image.FromFile("C:\\LMS\\Logs\\" + masterTitleWS + "ReportOf" + projectCode.Replace(" ", string.Empty) + ".jpg", false);
if (row.Table.Rows.IndexOf(row) == 0)
{
//Saving the bitmap
tiffImage = new Bitmap(250, 250, PixelFormat.Format8bppIndexed);//This line was put which SEEMED to have solved the problem, according to a developer,but there is no prove that it ran correctly, and is still giving an exception
tiffImage = (Bitmap)img;
tiffImage.Save(fileName, info, encoderparams);
encoderparams.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
}
else
{
//Adding another image
tiffImage.SaveAdd(img, encoderparams);
}
//img.Dispose();
}
//close file
encoderparams.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
tiffImage.SaveAdd(encoderparams);
tiffImage.Dispose();
}//Line:250
A:
After a lot of struggle, the last parameter of line 222 was changed from 4L to 24L, and it worked! Thanks to my PM!
encoderparams.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 24L);
It seems that older versions of windows do not support some TIFF codecs. The older code was tested on Windows Server 2012 too, and it works.
|
[
"stackoverflow",
"0027050018.txt"
] | Q:
Spring file upload - getting Expected MultipartHttpServletRequest: is a MultipartResolver configured? error
I'm trying to incorporate multiple file upload functionality in my Angular web application using angular-file-upload. Currently, the front end functionality works, but each upload attempt throws a
java.lang.IllegalStateException,java.io.IOException]:
java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest:
is a MultipartResolver configured?
exception.
The Upload Controller is defined as
@Controller
@PropertySource("classpath:application.properties")
public class FileUploadController {
@Resource
private Environment env;
@RequestMapping(value = "/fileupload", method = RequestMethod.POST)
@ResponseBody
public List<String> fileUpload(@RequestParam("file") MultipartFile[] uploadFiles) throws IllegalStateException, IOException {
//file processing logic
}
}
In my AppConfig.java class, I declare the bean
@Bean
public CommonsMultipartResolver commonsMultipartResolver(){
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setDefaultEncoding("utf-8");
commonsMultipartResolver.setMaxUploadSize(50000000);
return commonsMultipartResolver;
}
and start the web application with
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
servletContext.addListener(new ContextLoaderListener(ctx));
ctx.setServletContext(servletContext);
ctx.refresh();
Dynamic servlet = servletContext.addServlet(SERVLET_NAME, new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
//servlet.setMultipartConfig(ctx.getBean(MultipartConfigElement.class));
}
I do not think it is due to the lack of a <form> element in my Angular view, because I can see that Content-Tyle is multipart/form-data and that the Request Payload is set appropriately.
Remote Address:192.168.33.10:80
Request URL:http://dev.jason.com/rest/fileupload
Request Method:POST
Status Code:500 Internal Server Error
Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:415235
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryBHlsldPQysTVpvwZ
Host:dev.jason.com
Origin:http://dev.jason.com
Pragma:no-cache
Referer:http://dev.jason.com/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36
Request Payload
------WebKitFormBoundaryBHlsldPQysTVpvwZ
Content-Disposition: form-data; name="file"; filename="IMG_5072.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryBHlsldPQysTVpvwZ--
Note that this issue still occurs when including
@Bean
public MultipartConfigElement multipartConfigElement(){
MultipartConfigFactory multipartConfigFactory = new MultipartConfigFactory();
multipartConfigFactory.setMaxFileSize("10MB");
multipartConfigFactory.setMaxRequestSize("50MB");
return multipartConfigFactory.createMultipartConfig();
}
in AppConfig.java and uncommenting the command
servlet.setMultipartConfig(ctx.getBean(MultipartConfigElement.class));
in my servlet initializer class.
Any help is appreciated!
A:
Spring's MVC stack requires that the MultipartResolver bean be called multipartResolver. Change your @Bean method to
@Bean
public CommonsMultipartResolver multipartResolver(){
or
@Bean(name = "multipartResolver")
public CommonsMultipartResolver commonsMultipartResolver(){
A:
Just add this to servler-context.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="268435456"/>
</bean>
Nothing else needed.
|
[
"stackoverflow",
"0046172633.txt"
] | Q:
Xcode variables view empty values while debugging
I cannot see the value of variables while debugging my app. I have already checked the build settings and optimization values are set to none, also my Scheme. See screenshots below:
A:
The idea is to remove things from your bridging-header one by one and see if you can narrow down the issue.
I think I read somewhere that if a library is causing many issues behind the scenes, this can stop your debugger working.
In my case
I was using Facebook Tweaks library
Once I got rid of it, I got my debugging back.
and in my AppDelegate.swift
import Tweaks into the AppDelegate file.
import Tweaks
|
[
"stackoverflow",
"0023211232.txt"
] | Q:
Android: Force close the app in Application class
I have a class which extends Application class. In this class I am checking Internet Connectivity and calling the web service.
Below is the method I am using to check:
public static boolean isInternetConnected(Context mContext) {
ConnectivityManager connec = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connec != null
&& (connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED)
|| (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)) {
return true;
}
return false;
}
When there is no Internet connection I want to force close the application. How to do it?
I have an alternative solution. If there is no Internet connection, I can skip calling api process and wait for the first activity to start and finish that activity as soon as it starts.
Is it possible to do it in Application class?
A:
Why do you wish to force close an application? Heard of such request for the first time.
When there is no internet, you can just close the activity like this:
if (!isInternetConnected(context)){
finish();
}
|
[
"stackoverflow",
"0061481367.txt"
] | Q:
Application is crashing Android
My application keeps crashing.
The app is crashing from the start. I attached the logcat and the code section related to the error. please help me:)
and the code for line 14
class UserAdapter(
mContext: Context,
mUsers: List<Users>,
isChatCheck: Boolean
) : RecyclerView.Adapter<UserAdapter.ViewHolder?>()
code for line 44
{
val user: Users? = mUsers[i]
holder.userNameTXT.text = user!!.getusername()
Picasso.get().load(user.getprofile()).placeholder(R.drawable.profile).into(holder.profileImageView)
}
A:
The error shows that
user.getprofile()
is either empty or null. please debug the application and check whether user.getProfile() returns empty string or null
or add an empty string validation
if(!user.getProfile().isEmpty())
Picasso.get().load(user.getprofile()).placeholder(R.drawable.profile).into(holder.profileImageView)
|
[
"stackoverflow",
"0015943734.txt"
] | Q:
Initializing C array without stange chars?
(I already know other languages but this exam I'm preparing require to know C which I never really looked into before.)
EDIT : WOAH SO MANY ANSWERS... Give me a few mins to read all of them, thank you so much !
Here is my code
int main(int argc, char *argv[]) {
char search_for[80]; // <----- I think the problem is either here
printf("Search for : ? \n");
fgets(search_for, 80, stdin); // <---- or here
int i;
for (i = 0; i < 80; i++) {
printf("Char i : %c - %p \n", search_for[i], &search_for[i]);
}
return 0;
}
And here is the output, see those weird chars in the end ? Why are they here ?
Search for : ?
New
Char i : N - 0x7fff52eb4ba0
Char i : e - 0x7fff52eb4ba1
Char i : w - 0x7fff52eb4ba2
Char i :
- 0x7fff52eb4ba3
Char i : � - 0x7fff52eb4ba4
Char i : � - 0x7fff52eb4ba5
Char i : � - 0x7fff52eb4ba6
Char i : � - 0x7fff52eb4ba7
Char i :
- 0x7fff52eb4ba8
Char i : � - 0x7fff52eb4ba9
Char i : � - 0x7fff52eb4baa
Char i : � - 0x7fff52eb4bab
Char i : - 0x7fff52eb4bac
Char i : � - 0x7fff52eb4bad
Char i : � - 0x7fff52eb4bae
Char i : � - 0x7fff52eb4baf
Char i : @ - 0x7fff52eb4bb0 <---- ??
Char i : ∑ - 0x7fff52eb4bb1 <---- ??
Char i : î - 0x7fff52eb4bb2 <---- ??
Char i : l - 0x7fff52eb4bb3 <---- ??
Char i : ˇ - 0x7fff52eb4bb4 <---- ??
... and other lines with weird chars ..
A:
They are there because search_for is not initialised:
char search_for[80]; /* Will contain random characters. */
and fgets() will not necessarily write to every element in the buffer.
The for loop though accesses every element in search_for. To not examine the unitialised elements of search_for use search_for[i] instead of i < 80 as the terminating condition:
for (int i = 0; search_for[i]; i++)
This loop will then terminate when the null terminating character is encountered in search_for, which fgets() always writes (and does not write anything after, hence the junk characters):
Reads at most count - 1 characters from the given file stream and stores them in str. The produced character string is always NULL-terminated. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.
|
[
"money.stackexchange",
"0000004345.txt"
] | Q:
What kind of Quicken account should I use to track an adjustable complife policy?
I have an Adjustable CompLife policy that I want to track in Quicken. What kind of Quicken account should I use?
A:
Seems like you could shoehorn this into an investment account.
You make purchases similar to what you would make in a money market account ($1 per share) via your premium payments.
You see appreciation in those shares.
You incur expenses on your "purchases" via cost of insurance and possibly monthly payment fees.
|
[
"gis.stackexchange",
"0000240917.txt"
] | Q:
What are properties of tile geometry of Sentinel data?
I have downloaded sample tile from
http://sentinel-s2-l1c.s3-website.eu-central-1.amazonaws.com/#tiles/10/S/DG/2015/12/7/0/
and found tileInfo.json file with the following information
"tileGeometry" : {
"type" : "Polygon",
"crs" : {
"type" : "name",
"properties" : {
"name" : "urn:ogc:def:crs:EPSG:8.8.1:32610"
}
},
"coordinates" : [ [ [ 399960.0, 4200000.0 ], [ 509760.0, 4200000.0 ], [ 509760.0, 4090200.0 ], [ 399960.0, 4090200.0 ], [ 399960.0, 4200000.0 ] ] ]
},
It appears, that tile is strictly rectangular in some coordinates, because corners contain duplicate values. Is this property constraint, i.e. true for all tiles?
What units are used for these coordinates? I tried to interpret them as lat-lon multiplied by some factor, but probably failed (was unable to identify any ground details with compre to google maps).
Also I can interpret it as meters, because they have 6 digits and meters should have 5.
UPDATE
I have plotted coordinates
Both height and width are 109800 of units, so it can't be meters, which would sum up to 100000. But it coincides with the number of pixels in tile.
A:
If you check this page, you will notice:
For Level-1C and Level-2A, the granules, also called tiles, are 100x100 km2 ortho-images in UTM/WGS84 projection.
I guess the easiest way to get insight in tiles is to download a tile KML and open it in Google Earth or similar.
|
[
"stackoverflow",
"0059364073.txt"
] | Q:
DialogFlow, how to build a general intent for Yes and No responses
I'm building a DialogFlow agent for use on the Google Assistant, and it is a conversational model that mainly uses Yes and No responses to navigate through a hierarchical story. I'm struggling to design the architecture using DialogFlow Intents because there doesn't seem to be a way to create a generic, global intent that uses the system Yes and No intents. I know you can add these as Followup Intents as a child of a parent intent, but these only trigger once.
I'm using Cloud Functions on Firebase as the webhook, and will use JSON to build the responses and handle the input. Do I need to use entities to capture the responses instead? I don't think there is a system entity for yes and no.
A:
There are a few ways to create global Yes/No intents:
Create global Yes intent and No intent. Add training phrases for the two intents.
Create a yes/no entity and then a Yes/No intent using the new yes/no entity
Make a follow up Yes intent and remove the context, which will make it a global intent. Do the same with No
Each of these will get you global Yes/No possibilities.
Since your story is hierarchical, a global Yes/No intent does mean that you'll need to keep track of where you are in the story (most likely with a flag in your code and adding/removing context).
|
[
"stackoverflow",
"0019489517.txt"
] | Q:
ASP.NET Web App hosting configuration requirements
We are finnishing with our Web application and looking for a good way to host it. We are offered VM and need to specify good configuration for it.
So, as i can say, we need IIS 8.0 and MS SQL Server 2008. But what else?
What is the "required configuration" ? We expect around 50,000 monthly visitors.
Thanks, if I was unclear about this please let me know, we need to handle this asap
A:
IMHO you should get at least 4/8 GB RAM and 2 HDD depending on your needs - one for backups and one with your server, aslo et one Plesk so to manage your server easier. If you have not any admin knowledge then it will much better to get managed VPS hosting.
|
[
"stackoverflow",
"0030410230.txt"
] | Q:
Android Application : Augmented Reality or Image Recognition
I am interested in developing an Android Application that employs the Android Devices Camera to detect moving "Targets".
The three types of targets I need to detect and distinguish between are pedestrians, runners (joggers) and cyclists.
The augmented realities SDK's I have looked at only seem to offer face recognition which doesn't sound like they can detect entire people.
Have i misunderstood what Augmented Realities SDK can provide?
A:
There is a big list of AR SDKs (also for Android platform):
Augmented reality SDKs
However, to be honest I strongly doubt that you will find any (doesn't matter free or payed) SDK for your task. It is to specific so you should probably write it by yourself using OpenCV.
OpenCV will allow you to detect objects (more or less) and then you will need to write some algorithm for classification. I would recommend classification based on object speed.
Then, when you have your object classified you can add any AR SDK to add something to your picture.
|
[
"stackoverflow",
"0035697094.txt"
] | Q:
How to convert Web service output(XMLNode) to Dataset in VB.NET?
I have written code as below
Dim xNode As XmlNode
xNode = proclaimService.ProClaim_Get_Exclusions(sSQL)
XmlData = New StringReader(xNode.OuterXml)
Dim xmlString As String
xmlString = xNode.OuterXml
Here in xmlString I am getting below
<NewDataSet xmlns="">
<Table>
<company />
<Policy>10163067</Policy>
<Rec_ty>Ex</Rec_ty>
<Seq_no xml:space="preserve"></Seq_no>
<Dt_last_updt>Dec 3 2003</Dt_last_updt>
<Coverage_no>All</Coverage_no>
<Client_no>65083406</Client_no>
<Document_name>Exclusion</Document_name>
<Print_ind />
<Retention_ind />
<Exclusion_type>Exclu</Exclusion_type>
<Comment01>blessure,maladie ou trouble d'un ou des deux genoux, y compr</Comment01>
<comment02>is les complications, traitements ou chirurgies connexes.</comment02>
<comment03 xml:space="preserve"></comment03>
<comment04 xml:space="preserve"></comment04>
<comment05 xml:space="preserve"></comment05>
<comment06 xml:space="preserve"></comment06>
<comment07 xml:space="preserve"></comment07>
<comment08 xml:space="preserve"></comment08>
<comment09 xml:space="preserve"></comment09>
<comment10 xml:space="preserve"></comment10>
</Table>
</NewDataSet>
I am using Below code to create dataset
XmlData = New StringReader(xmlString)
reader = New XmlTextReader(XmlData)
xmlDs.ReadXml(reader)
Dset = xmlDs
But in XmlData I am not getting anything.....
How to convert it to Dataset using VB.NET???
A:
Without some more info it is hard to know how to answer. Here is an example that works with a file. Note the comments.
Dim xmlStrm As New IO.StreamReader(pathToFile)
'xmlStrm could be a .GetResponseStream from a web response
'Dim xmlStrm As IO.Stream = someWebResp.GetResponseStream
Dim Dset As New DataSet
Using reader As Xml.XmlReader = Xml.XmlReader.Create(xmlStrm)
Dset.ReadXml(reader)
End Using
xmlStrm.Close()
xmlStrm.Dispose()
Debug.WriteLine(Dset.Tables.Count)
For Each rw As DataRow In Dset.Tables(0).Rows
'as example show first two columns
Debug.WriteLine(rw(0).ToString & " " & rw(1).ToString)
Next
edit: From a web site returning XML
Dim someReq As Net.WebRequest = Net.WebRequest.Create(someURL)
Dim someResp As Net.WebResponse = someReq.GetResponse()
Dim someStrm As IO.Stream = someResp.GetResponseStream()
Dim someDoc As New Xml.XmlDocument
someDoc.Load(someStrm)
Dim xe As XElement = XElement.Parse(someDoc.InnerXml)
Dim Dset As New DataSet
Using reader As Xml.XmlReader = xe.CreateReader
Dset.ReadXml(reader)
End Using
Debug.WriteLine(Dset.Tables.Count)
|
[
"stackoverflow",
"0054487492.txt"
] | Q:
What does "undefined" parameter signify in a function definition
I was reverse engineering a jQuery plugin and found a peculiar function definition.
function myFunction(value, undefined){
...
}
Of course, this works but similar declarations like
function myFunction(value, null) {
...
}
OR
function myFunction(value, 5) {
...
}
do not work.
The initial declaration where the parameter is undefined works like a default parameter value (refer the snippet below). Can someone point to this phenomenon in ECMA6 specification. I have clue on what to even search for.
function strange (value, undefined) {
document.getElementById("output").innerHTML += "<br/>" + "- " + arguments[1];
}
strange(5,6);
strange(5);
<div id="output"></div>
A:
Oddly, undefined is not a reserved keyword and its global value can be overridden (or could be in the past, in some runtime environments). Thus that trick provides a way to wrap code expecting undefined to really be undefined: when that function is called, if only one parameter is passed the second argument, called "undefined", will have the authentic undefined value inside the function.
Why would undefined be overwritten? Who knows. People who write code for pages that also have to host 3rd-party code (generally adverts and things like that) become paranoid and defensive after a while.
|
[
"stackoverflow",
"0058467020.txt"
] | Q:
Can't center the div element when the screen width changes
Hello everyone i was finishing the last touches on my simple math function plotter then when i used developer tools to see how it looks on mobiles i realized that the header text isn't centered like how it is on the normal version (pc screen) so i tried to add some media queries and still doesn't work.(it always goes to the left on the mobile version), by the way initial scale is set to 1.0 in the meta data.
So here is the code and hope u help me
HTML
<div id="header-container">
<p id="header">راسم منحنيات الدوال</P>
</div>
CSS
#header-container {
display: block;
margin-left: auto;
margin-right: auto;
margin-top: -35px;
width: 100%;
}
#header {
font-family: Font3;
font-size: 45px;
}
Also if you want to check the whole application source code visit this codepen post over here
Note: when u switch to phone view make it fullscreen by clicking twice to see that the text does't stay at the middle.
Thanks
A:
If you want your header to be centered above the graph at all times then put the graph and the header inside the same div. So that the width for your header is the same as the width for graph in all viewports.
var parameters = {
target: '#myFunction',
width: '834',
height: '540',
data: [{
fn: 'x*x',
color: '',
derivative: {
fn: '2*x',
updateOnMouseMove: true
}
},
{
fn: 'x*x',
color: 'red',
derivative: {
fn: '2*x',
updateOnMouseMove: true
}
}
],
grid: true,
yAxis: {
domain: [-9, 9]
},
xAxis: {
domain: [-7, 7]
}
};
function plot() {
let f = document.querySelector("#function").value;
let color = document.querySelector("#color").value;
let derivative = document.querySelector("#der").value;
let f2 = document.querySelector("#function2").value;
let color2 = document.querySelector("#color2").value;
let derivative2 = document.querySelector("#der2").value;
parameters.data[0].fn = f;
parameters.data[0].color = color;
parameters.data[0].derivative.fn = derivative;
parameters.data[1].fn = f2;
parameters.data[1].color = color2;
parameters.data[1].derivative.fn = derivative2;
functionPlot(parameters);
};
plot();
@font-face {
font-family: "Font";
src: url("Almarai-Regular.ttf");
}
@font-face {
font-family: "Font2";
src: url("Cairo-Regular.ttf");
}
@font-face {
font-family: "Font3";
src: url("MarkaziText-Regular.ttf");
}
#plot {
touch-action: none;
float: left;
}
.layer {
display: grid;
grid-template-columns: auto auto;
grid-gap: 0px;
}
#plotSettings {
float: right;
padding: 0px;
}
#func1 {
margin-top: 20px;
font-family: Font2;
font-size: 18px;
}
.input {
width: 110px;
float: left;
margin-right: 20px;
padding: 10px;
border: 1px rgb(15, 97, 74) solid;
border-radius: 7px;
}
table {
border-collapse: collapse;
}
table,
td,
th {
border: 1px solid black;
padding: 8px 15px;
}
.tableheads {
text-align: center;
font-family: Font;
height: 30px;
}
th {
font-family: Font;
font-size: 20px;
height: 50px;
}
#header-container {
display: block;
margin-left: auto;
margin-right: auto;
margin-top: -35px;
width: 100%;
}
#header {
font-family: Font3;
font-size: 45px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<script src="https://unpkg.com/d3@3/d3.min.js"></script>
<script src="https://unpkg.com/function-plot@1/dist/function-plot.js"></script>
<div class="container">
<div class="layer">
<section id="plot">
<div id="header-container">
<p id="header">راسم منحنيات الدوال</p>
</div>
<div id="myFunction"></div>
</section>
<div dir="rtl" id="plot-settings">
<table>
<tr>
<th>اعدادات المنحنيات</th>
</tr>
<tr>
<td class="tableheads">المنحنى الأول</td>
</tr>
<tr>
<td>
<section id="func1">
<label for="function"> دستور الدالة 1 : </label>
<input id="function" type="text" value="x*x" onchange="plot();" dir="ltr" class="input" />
<p></p>
<label for="derivative"> مشتقة الدالة 1 : </label>
<input type="text" id="der" value="2*x" onchange="plot();" dir="ltr" class="input" />
<p></p>
<p></p>
<label for="color">لون المنحني : </label>
<input type="color" id="color" onchange="plot();" dir="ltr" />
<p></p>
</section>
</td>
</tr>
<tr>
<td class="tableheads">المنحنى الثاني</td>
</tr>
<tr>
<td>
<section id="func1">
<label for="function"> دستور الدالة 2 : </label>
<input id="function2" type="text" value="x^3" onchange="plot();" dir="ltr" class="input" />
<p></p>
<label for="derivative"> مشتقة الدالة 2 : </label>
<input type="text" id="der2" value="3*x^2" onchange="plot();" dir="ltr" class="input" />
<p></p>
<label for="color">لون المنحني : </label>
<input type="color" id="color2" onchange="plot();" dir="ltr" value="Red" />
<p></p>
</section>
</td>
</tr>
</table>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
|
[
"stackoverflow",
"0046538969.txt"
] | Q:
Multiple after_update callbacks with attribute change conditions are triggering only the first one
Multiple after_update callbacks with attribute change conditions are triggering only the first one.
class Article < ActiveRecord::Base
after_update :method_1, :if => proc{ |obj| obj.status_changed? && obj.status == 'PUBLISHED' }
after_update :method_2, :if => proc{ |obj| obj.status_changed? && obj.status == 'PUBLISHED' && obj.name == 'TEST' }
...
end
method_1 is triggered when a model object is updated:
Article.last.update_attributes(status: 'PUBLISHED', name: 'TEST')
While method_2 is not triggered.
A:
You can just use one callback with an if...end block to filter operations you want to perform in each cases.
class Article < ActiveRecord::Base
after_update :method_1, :if => proc{ |obj| obj.status_changed? && obj.status == 'PUBLISHED' }
...
def method_1
if self.name == 'TEST'
# stuff you want to do on method_2
else
# stuff you want to do on method_1
end
end
end
|
[
"stackoverflow",
"0038000264.txt"
] | Q:
Waiting for a file to exist in a directory C#
I am creating a Visual C# application and part of its functionality is to extract a .gz file once it appears in a directory. The .gz file appears in the specified directory once a command line argument is executed.
Unfortunately, I receive an error saying something along the lines of "this file cannot be found" and this is due to the reason that it reads the line to extract the .gz file too quickly.
In other words, it is trying to execute a .gz file before the command line argument executes and actually places the file into the directory.
I want to find a way for my program to wait for the file to appear in the directory before it continues to read the next line.
Below is my code, any help will be appreciated! Thanks!
else if (ddlDateType.Text == "Monthly" || ddlDateType.Text == "")
{
//Check if Monthly date entered is valid
if (DateTime.TryParseExact(txtDate.Text, MonthlyFormat, null,
System.Globalization.DateTimeStyles.None, out Test) != true)
{
MessageBox.Show("Enter a valid date.\nFormat: yyyyMM");
}
else
{
//Method that executes an arugment into the command prompt
ExecuteCommand();
//Method that extracts the file after it has already appeared in the directory
ExtractFile();
/*
Goal is to wait for the file to appear in the directory before it executes
the ExtractFile() method.
*/
}
}
A:
you can use FileSystemWatcher. https://msdn.microsoft.com/it-it/library/system.io.filesystemwatcher(v=vs.110).aspx
in this example, the callback OnChanged, is called every time a file was added to the monitored folder.
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public static void RunWathcer()
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "PATH TO WATCH GOES HERE!!";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
}
|
[
"stackoverflow",
"0032226926.txt"
] | Q:
QtDBus Simply Example With PowerManager
I'm trying to use QtDbus to communicate with interface provided by PowerManager in my system. My goal is very simple. I will be writing code which causes my system to hibernate using DBus interface.
So, I installed d-feet application to see what interfaces DBus is available on my system, and what I saw:
As we see, I have a few interfaces and methods from which I can choose something. My choice is Hibernate(), from interface org.freedesktop.PowerManagment
In this goal I prepared some extremely simple code to only understand mechanism. I of course used Qt library:
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtDBus/QtDBus>
#include <QDBusInterface>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
if (!QDBusConnection::sessionBus().isConnected()) {
fprintf(stderr, "Cannot connect to the D-Bus session bus.\n"
"To start it, run:\n"
"\teval `dbus-launch --auto-syntax`\n");
return 1;
}
QDBusInterface iface("org.freedesktop.PowerManagement" ,"/" , "" , QDBusConnection::sessionBus());
if(iface.isValid())
{
qDebug() << "Is good";
QDBusReply<QString> reply = iface.call("Methods" , "Hibernate");
if(reply.isValid())
{
qDebug() << "Hibernate by by " << qPrintable(reply.value());
}
qDebug() << "some error " << qPrintable(reply.error().message());
}
return 0;
}
Unfortunately I get error in my terminal:
Is good
some error Method "Methods" with signature "s" on interface "(null)" doesn't exist
So please tell me what's wrong with this code? I am sure that I forgot some arguments in function QDBusInterface::call() but what ?
A:
When creating interface you have to specify correct interface, path, service. So that's why your iface object should be created like this:
QDBusInterface iface("org.freedesktop.PowerManagement", // from list on left
"/org/freedesktop/PowerManagement", // from first line of screenshot
"org.freedesktop.PowerManagement", // from above Methods
QDBusConnection::sessionBus());
Moreover, when calling a method you need to use it's name and arguments (if any):
iface.call("Hibernate");
And Hibernate() doesn't have an output argument, so you have to use QDBusReply<void> and you can't check for .value()
QDBusReply<void> reply = iface.call("Hibernate");
if(reply.isValid())
{
// reply.value() is not valid here
}
|
[
"stackoverflow",
"0016361297.txt"
] | Q:
Routing with Zend Framework 2 Restful Webservice
I want to implement a RESTful webservice by using Zend Framework 2, more precisely 2.1.5. I got a 404 if I visit http://ehcserver.localhost/rest, the corresponding message is 'rest(resolves to invalid controller class or alias: rest)'. What went wrong?
You can see my source code in my github-repository:
https://github.com/Jochen1980/EhcServer/blob/master/module/Application/config/module.config.php
The route is defined like this:
return array(
'router' => array(
'routes' => array(
'rest' => array(
'type' => 'ZendMvcRouterHttpSegment',
'options' => array(
'route' => '/:controller[.:formatter][/:id]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'formatter' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[a-zA-Z0-9_-]*'
),
),
),
'home' => array(
...
A:
Your route doesn't define a namespace to which the controller belongs, you need to add a __NAMESPACE__ to route defaults
'rest' => array(
'type' => 'ZendMvcRouterHttpSegment',
'options' => array(
'route' => '/:controller[.:formatter][/:id]',
'defaults' => array(
// tell the router which namespace :controller belongs to
'__NAMESPACE__' => 'Application\Controller',
),
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'formatter' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[a-zA-Z0-9_-]*'
),
),
),
|
[
"stackoverflow",
"0057823904.txt"
] | Q:
Swift: How to find Realm database contains custom string
I had a problem to filter realm database. I search movie name and wrote values to realm database from Json. After written, I assign to tableview cell to show results. At the second search, I always get same values because of the getting all result from the database. I need to filter new values from the database and set to tableview. Please help me !
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.counter = 0
aranacak_kelime = searchBar.text!
let url = URL(string: "https://www.omdbapi.com/?s=" + aranacak_kelime + "&apikey=c6e----")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if(error != nil)
{
print("error")
}
else{
if let content=data
{
do
{
let json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableLeaves) as AnyObject
if let search = json["Search"] as? [NSDictionary]
{
DispatchQueue(label: "background").async {
autoreleasepool {
let realm = try! Realm()
print(Realm.Configuration.defaultConfiguration.fileURL)
for result in search
{
let movie = Movie()
movie.name = result["Title"] as! String
movie.type = result["Type"] as! String
movie.year = result["Year"] as! String
movie.poster = result["Poster"] as! String
try! realm.write {
realm.add(movie)
}
self.counter += 1
DispatchQueue.main.async {self.tableView.reloadData()}
}
}
}
}
}
catch{
print("error in JSONSerialization")
}
}
}}task.resume()}
and tableview
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "textCell", for: indexPath) as! TableViewCell
let row = indexPath.row
let realm = try! Realm()
//let results = realm.objects(Movie.self).filter("ANY name.contains('aranacak_kelime')")
let results = realm.objects(Movie.self)
cell.movieName.text = results[row].name
cell.movieYear.text = results[row].year
cell.movieType.text = results[row].type
let imageUrl = results[row].poster
}
and my Movie class
class Movie: Object{
@objc dynamic var name:String = ""
@objc dynamic var type:String = ""
@objc dynamic var year:String = ""
@objc dynamic var poster:String = ""
}
A:
As I understand, you have a couple of issues. If you search for the same movie twice, you will be saving the same result to your realm DB. So maybe use some sort of ID and when saving use realm.add(movie, update: true) this will prevent from storing the same movie twice.
The other issue is that you are not filtering the results you load on the tableview.
You should have an auxiliar method where you use the search bar text to filter your results before reloading your table view, something like:
func reloadContent() {
self.data = realm.objects(Movie.self).filter("ANY name.contains(YOUR_SEARCHBAR.text)")
self.tableView.reloadData()
}
You should change this line DispatchQueue.main.async {self.tableView.reloadData()} for DispatchQueue.main.async {self.reloadContent()}
and finally have a property of var data: Results<Movie>? where you will store the filtered movies. You will have to change your table view datasource delegate methods to use this data instead.
Hope it helps.
|
[
"stackoverflow",
"0027381083.txt"
] | Q:
Why array_multisort doesn't sort in my case?
Why array_multisort doesn't sort in my case ?
The case is simple i followed many of examples manuals and i have no idea why it doesnt work. Teoretical it should work 100%. Maybe i have spend to many time trying to fix it over and over again and i cant see samething obvious now.
Here is the case:
I want to sort my array $this->array over defined sort dirrection for columns in other array $order
simple sorting function:
$preSort = [];
foreach ($order as $column => $direction) {
$valueArray = [];
foreach ($this->array as $key => $row) {
$valueArray[] = $row[$column];
}
$preSort[] = $valueArray;
$preSort[] = $this->getSortDirection($direction) | $this->getSortType(key($valueArray), $column);
}
$preSort[] = $this->array;
call_user_func_array('array_multisort', $preSort);
And here it is how data looks like:
$order
array ('id' => 'asc', 'name' => 'desc',)
$this->array
array ( 0 => array ( 'id' => 1, 'name' => 'samsonasik', 'description' => 'aaaaaaa', ), 1 => array ( 'id' => 2, 'name' => 'abdul malik ikhsan', 'description' => 'bbbbbb', ), 2 => array ( 'id' => 3, 'name' => 'superman', 'description' => 'cccccccc', ), )
here you have extra functions used by me:
protected function getSortDirection($string)
{
return mb_strtolower($string) == 'asc' ? SORT_ASC : SORT_DESC;
}
protected function getSortType($key, $column)
{
return is_numeric($this->array[$key][$column]) ? SORT_NUMERIC : SORT_STRING;
}
A:
the array_multisort signature looks like this:
bool array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC
[, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] )
$sort_order and $sort_flags are two parameters, so instead of
$array, SORT_ASC | SORT_STRING
you need
$array, SORT_ASC, SORT_STRING
|
[
"stackoverflow",
"0001623147.txt"
] | Q:
Core Data Classes vs Model
I've recently started down the road of programming in Objective-C, and I'm now looking into Core Data. However, I am confused about exactly what defines the model itself in Core Data.
Here's what I mean: Say I create an entity with some set of attributes using the graphical model builder. I then have Xcode generate code for the corresponding class. Next, I want to create a property in the class that will be used only during run-time and does not need to be stored or retrieved by Core Data. So, I add a variable and a corresponding property to the class (synthesizing it in the implementation)
The new property is not defined in the model builder, but it is defined in the class derived from NSManagedObject. How is it treated in Core Data? Do the properties listed in the class define attributes in the "model" or do only the attributes defined in the model builder define the model?
Similarly, I wanted to add a enum-based property to the class file that, when get or set, accesses or changes an NSNumber attribute in the model. Can I do that without Core Data treating the property as an attribute to be stored and retrieved?
THANKS!
A:
You can add custom properties (and variables) to the code generated for your NSManagedObjects, as you would any other class. These won't become part of the model, but instead will be temporary in memory. It's worth noting that if the managed object were to be dealloc'ed the value in memory would too.
A tip I would suggest if you are just implementing custom accessors to the underlying data is to create a category on the managed object in question. In the accessors, you access the underlying NSNumber and convert it into your enum, defined in the header for the category.
If you need to regenerate the code for the managed object, because say the model changes, you can just delete the class generated for the managed object and regenerate it without needing to merge with any custom code you've added. The category you've added will work all the same as long as the underlying storage property has stayed the same.
You can find out more about categories in the Objective-C Programming Language guide at the ADC.
|
[
"stackoverflow",
"0026037830.txt"
] | Q:
Replace sys_extract_utc in MySQL
I'm using the following query in Oracle, I need the same in MySQL also.
select sys_extract_utc(systimestamp) into currGMTDate from dual;
I tried with CURRENT_TIMESTAMP instead of systimestamp
but the output that I got was a different one. How can I get the same result in MySQL for the above Oracle query?
A:
I tried with the below query and it worked for me
select date_format(CONVERT_TZ( current_timestamp, @@session.time_zone, '+00:00' ),'%d-%m-%Y %r')
|
[
"stackoverflow",
"0039739250.txt"
] | Q:
Mapbox touchlistner for map
Hi I am using mapbox to display map in android app. I'm stuck in a situation where I need to get radius of a map that is visible to the user. if user zoom-in or zoom-out the radius of the map changes. Can anyone tell me how do I do this or suggest me any reference link regarding this
A:
To detect when the map scale has changed you need to add a listener to the MapboxMap. Here's an example of a class that extends MapView to add a scale bar at the bottom that dynamically resizes as the map is zoomed or panned (panning will change the scale in distance, but not in degrees.) This is what it looks like:
A couple of points: the only way to get the MapboxMap from the MapView is to request it asynchronously. The Activity or Fragment hosting the map should do that. This class overrides getMapAsync() to allow it to also get a reference to the MapboxMap but the hosting Activity still needs to call that method.
Camera change events are reported to a listener, and only one can be set at at time on the MapboxMap so if the hosting activity has a listener, it should call ScaledMapView#onCameraChange() in that listener's similarly named method.
The MapView itself must be contained in a FrameLayout to enable the scale view to be added.
Obviously you could simply incorporate the same basic code in your Activity or Fragment, and include the scale TextView in the layout rather than adding it programmatically.
The extended class:
package com.controlj.test;
import android.content.Context;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.MapboxMapOptions;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import java.util.Locale;
/**
* Created by clyde on 2/10/2016.
* This class extends the Mapbox Mapview to add a scale at the bottom
*/
public class ScaledMapview extends MapView implements MapboxMap.OnCameraChangeListener, OnMapReadyCallback {
private TextView scaleText;
private MapboxMap mapboxMap;
private OnMapReadyCallback callback;
private ScaleUnit scaleUnit = ScaleUnit.KM;
private float labelWidth = 0.33f;
public float getLabelWidth() {
return labelWidth;
}
public void setLabelWidth(float labelWidth) {
if(labelWidth > 1f)
labelWidth = 1f;
else if(labelWidth < 0.1f)
labelWidth = 0.1f;
this.labelWidth = labelWidth;
}
public ScaleUnit getScaleUnit() {
return scaleUnit;
}
public void setScaleUnit(ScaleUnit scaleUnit) {
this.scaleUnit = scaleUnit;
}
enum ScaleUnit {
MILE("mile", 1609.344f),
NM("nm", 1852.0f),
KM("km", 1000.0f);
ScaleUnit(String unit, float ratio) {
this.unit = unit;
this.ratio = ratio;
}
String unit;
float ratio;
}
public ScaledMapview(@NonNull Context context) {
super(context);
}
public ScaledMapview(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ScaledMapview(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public ScaledMapview(@NonNull Context context, @Nullable MapboxMapOptions options) {
super(context, options);
}
@Override
public void getMapAsync(OnMapReadyCallback callback) {
this.callback = callback;
super.getMapAsync(this);
}
/**
* To ensure this is called when the camera changes, either this ScaledMapview must be passed
* to mapboxMap.setOnCameraChangeListener() or whatever is listening must also call this method
* when it is called.
*
* @param position The CameraPosition at the end of the last camera change.
*/
@Override
public void onCameraChange(CameraPosition position) {
if (scaleText == null) {
ViewParent v = getParent();
if (v instanceof FrameLayout) {
scaleText = (TextView)inflate(getContext(), R.layout.mapscale, null);
((FrameLayout)v).addView(scaleText);
}
}
if (scaleText != null) {
// compute the horizontal span in metres of the bottom of the map
LatLngBounds latLngBounds = mapboxMap.getProjection().getVisibleRegion().latLngBounds;
float span[] = new float[1];
Location.distanceBetween(latLngBounds.getLatSouth(), latLngBounds.getLonEast(),
latLngBounds.getLatSouth(), latLngBounds.getLonWest(), span);
float totalWidth = span[0] / scaleUnit.ratio;
// calculate an initial guess at step size
float tempStep = totalWidth * labelWidth;
// get the magnitude of the step size
float mag = (float)Math.floor(Math.log10(tempStep));
float magPow = (float)Math.pow(10, mag);
// calculate most significant digit of the new step size
float magMsd = (int)(tempStep / magPow + 0.5);
// promote the MSD to either 1, 2, or 5
if (magMsd > 5.0f)
magMsd = 10.0f;
else if (magMsd > 2.0f)
magMsd = 5.0f;
else if (magMsd > 1.0f)
magMsd = 2.0f;
float length = magMsd * magPow;
if (length >= 1f)
scaleText.setText(String.format(Locale.US, "%.0f %s", length, scaleUnit.unit));
else
scaleText.setText(String.format(Locale.US, "%.2f %s", length, scaleUnit.unit));
// set the total width to the appropriate fraction of the display
int width = Math.round(getWidth() * length / totalWidth);
LayoutParams layoutParams =
new LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
layoutParams.bottomMargin = 4;
scaleText.setLayoutParams(layoutParams);
}
}
@Override
public void onMapReady(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
// if the owner of this view is listening for the map, pass it through. If not, we must
// listen for camera events ourselves.
if (callback != null)
callback.onMapReady(mapboxMap);
else
mapboxMap.setOnCameraChangeListener(this);
onCameraChange(null);
}
}
The Activity:
package com.controlj.test;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.mapbox.mapboxsdk.MapboxAccountManager;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
ScaledMapview mapView;
@Override
protected void onStart() {
Log.d(TAG, "OnStart()");
super.onStart();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate()");
MapboxAccountManager.start(this, getString(R.string.mapbox_access_token));
setContentView(R.layout.activity_main);
mapView = (ScaledMapview)findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(null);
}
@Override
public void onDestroy() {
Log.d(TAG, "OnDestroy()");
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onPause() {
Log.d(TAG, "OnPause()");
mapView.onPause();
super.onPause();
}
@Override
public void onResume() {
Log.d(TAG, "OnResume()");
super.onResume();
mapView.onResume();
}
@Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG, "OnSaveInstanceState()");
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
The activity layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/activity_main"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.controlj.test.MainActivity">
<com.controlj.test.ScaledMapview
android:id="@+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:access_token="@string/mapbox_access_token"
mapbox:center_latitude="-31.42166667"
mapbox:center_longitude="152.75833333"
mapbox:style_url="@string/mapbox_style"
mapbox:zoom="4"/>
</FrameLayout>
And the layout for the scale widget itself. The image resource @drawable/scale is a 9-patch image file.
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="@+id/scale_text"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|bottom"
android:textAlignment="center"
android:background="@drawable/scale"
android:paddingBottom="2dp"
android:layout_marginBottom="6dp"
android:layout_marginTop="0dp"
android:paddingTop="0dp"
android:text="100km"/>
|
[
"stackoverflow",
"0062854371.txt"
] | Q:
How does the Spring Boot Project generate release notes?
Here are the release notes for Spring Boot 2.3.1
https://github.com/spring-projects/spring-boot/releases/tag/v2.3.1.RELEASE
I've searched everywhere in the Wiki, in Issues and in the code, but I can't find where these are being created.
Is this a manual process or automated in some way?
I'd love to take a similar approach in my projects but prefer not to do it manually if possible.
Does anyone know of any resources that describe how to generate release notes in this format with some level of automation?
A:
hello if you look carefully in spring boot github repo, you will have this
spring-boot/ci/pipeline.yml
this is where they have their build/release workflow
and the file below is the script use to generate the github release note
https://github.com/spring-projects/spring-boot/blob/master/ci/scripts/generate-release-notes.sh
|
[
"ru.stackoverflow",
"0001133263.txt"
] | Q:
Удаление элементов списка python
lst = [['54:35:000000:10155', '54:35:000000:22622', '54:35:000000:23040', '54:35:000000:24117'], ['54:35:031135:24', '54:35:031355:300']]
как удалить все элементы чтобы получилось так: lst = ['54:35:000000:10155', '54:35:031135:24']
A:
lst = [item[0] for item in lst]
Смею предположить что так
|
[
"stackoverflow",
"0005997563.txt"
] | Q:
When receiving an incoming call, recorded video is corrupted and AVFoundation methods are giving errors
I have a video recording app. Everything works fine. Except when a phone call is received while recording.
When a phone call is received, I try to end the recording, however, any of my calls to write to an AVAssetWriter are denied. audioWriterInput appendSampleBuffer returns no, appendPixelBuffer errors out. I try to call avAssetWriter finishWriting but that returns AVAssetWriterStatusFailed.
Nothing works, my video is corrupted because it seems that my usual methods to finish up a recording session are not being allowed once a call is received.
What could I listen for to properly end a recording session when a phone call is received? The only thing I can currently do is listen for applicationWillResignActive and stop everything, but that prevents recording while a user receives a text message, etc. which would make my app work differently than the native Camera app.
A:
Take a look at the Core Telephony framework, and specifically the CTCallCenter class. You can register an callEventHandler which is a block that accepts a CTCall object. This object describes the call state. Try to end recording when the call object indicates it's an incoming call.
|
[
"stackoverflow",
"0019597607.txt"
] | Q:
Differentiating between mouseup mousedown and click
I know that mousedown happens when a user depresses the mouse button, mouseup happens when the release the mouse and click is of course two events mousedown and mouseup. I have three different events each dealing with these three events mouseup down and click. My question is how to differentiate between the three, now my mouse down has a timer, so I was thinking of adding a boolean in that timer and testing it within the click I tried this and it didn't work to my standards.
Mousedown- timer checks for certain classes then if none of these classes exist within the targeted element proceed
Mouseup- clear the timer
Click- open a module
I may have not made the boolean a global variable that each can read or not, or I am missing something completely. Here is an example quick code of my full code:
var isDown = false;
ee[i].addEventListener('click',function(){
if(isDown===false){
openModule();
}
},false);
ee[i].addEventListener('mousedown',function(){
var timer;
var $this = this;
timer = setTimeout(function(){
if($this.className == "class"){
isDown=true;
createActive();
}
},500);
},true);
ee[i].addEventListener('mouseup',function(){
clearTimeout(timer);
},false);
That is just a quick example. I may have missed some coding but I hope you catch my drift in the code above. Anyone know of a good way to differentiate between the three events?
A:
I've rewritten your code utilizing jQuery...
var isDown = false;
var timer;
$('.class').mousedown(function(){
isDown = false;
timer = setTimeout(function(){
isDown = true;
//createActive();
console.log('MOUSE DOWN');
}, 500);
}).mouseup(function(){
if(isDown === false){
//openModule();
console.log('CLICK');
}else{
console.log('MOUSE UP');
}
clearTimeout(timer);
});
If you simply add jQuery to your page, my code will automatically attach itself to any element in your document with a class of 'class'.
I've commented out your createActive(); and openModule(); calls so that you can play around with it (viewing your javascript console at runtime will show you the script in action - remove the console.log() stuff when you're done playing). This code could be optimised a bit more but it will give you the general idea.
Your timer variable needed to be created globally (I moved it out of the function).
In this case (declaring a mousedown time barrier) the click function will be rendered useless so I've improvised it into the mouseup function.
It's good to know core javascript, but jQuery is just too easy and powerful to ignore.
|
[
"mathoverflow",
"0000310625.txt"
] | Q:
On the upper bound of $\sum_{i=1}^{n}x^m_{i}$ subject to the conditions $\sum_{i=1}^{n}x_{i}=0$ and $\sum_{i=1}^{n}x^2_{i}=n$
The following question has been posted on mathematics stackexchange: inequalities problem, perhaps arising from a question on expectations.
Let $x_{1},x_{2},\cdots,x_{n}$ are real numbers, and such
$$\begin{cases}
x_{1}+x_{2}+\cdots+x_{n}=0\\
x^2_{1}+x^2_{2}+\cdots+x^2_{n}=n
\end{cases}$$
Let $\alpha_{m}=\displaystyle\dfrac{1}{n}\sum_{i=1}^{n}x^m_{i}$
See Mitrinovic D.S Analytic inequalities (Springer 1970) Page 347.
M.LAKSHMANAMURTI proved that
$$\alpha_{m}\le\dfrac{(n-1)^{m-1}+(-1)^m}{n(n-1)^{(m/2)-1}}.$$
I am interested in the details of the proof or a published reference.
A:
This is addressed in the following paper:
Rivin, Igor, Counting cycles and finite dimensional $L^{p}$ norms, Adv. Appl. Math. 29, No. 4, 647-662 (2002). ZBL1013.05042.
|
[
"stackoverflow",
"0006780246.txt"
] | Q:
why are multiple re-search-foward / replace-match calls not replacing allmatches?
I want to do a set of search and replace operations in emacs, so I wrote this function:
defun untwist ()
(interactive)
(while (re-search-forward "yield " nil t) (replace-match ""))
(while (re-search-forward "@defer.inlineCallbacks" nil t) (replace-match ""))
(while (re-search-forward "defer.returnValue" nil t) (replace-match "return "))
(while (re-search-forward "@inlineCallbacks" nil t) (replace-match ""))
(while (re-search-forward "returnValue" nil t) (replace-match "return "))
(while (re-search-forward "^from twisted\.+\n" nil t) (replace-match ""))
(while (re-search-forward "(session," nil t) (replace-match "("))
(while (re-search-forward "session\.log(\(.*\))" nil t) (replace-match "print \1"))
)
However, only some of the substitutions get done. I ran it on:
@defer.inlineCallbacks
yield x
and got:
@defer.inlineCallbacks
x
What am I doing wrong?
A:
Your problem is that, after the first "while" statement successfully replaces the "yield" statement, the "point" is positioned to the end of the buffer. Therefore, all subsequent RE searches don't find anything to replace because their searches start at the end of the buffer! You can easily fix this by re-positioning to the beginning of the buffer after each search:
(defun untwist ()
(interactive)
(while (re-search-forward "yield " nil t) (replace-match ""))
(beginning-of-buffer)
(while (re-search-forward "@defer.inlineCallbacks" nil t) (replace-match ""))
(beginning-of-buffer)
(while (re-search-forward "defer.returnValue" nil t) (replace-match "return "))
(beginning-of-buffer)
(while (re-search-forward "@inlineCallbacks" nil t) (replace-match ""))
(beginning-of-buffer)
(while (re-search-forward "returnValue" nil t) (replace-match "return "))
(beginning-of-buffer)
(while (re-search-forward "^from twisted\.+\n" nil t) (replace-match ""))
(beginning-of-buffer)
(while (re-search-forward "(session," nil t) (replace-match "("))
(beginning-of-buffer)
(while (re-search-forward "session\.log(\(.*\))" nil t) (replace-match "print \1"))
)
|
[
"stackoverflow",
"0022405541.txt"
] | Q:
How do you select a range of tr from a table using jQuery
I find myself frequently in need of selecting a range of tr's from a table. For example, often times, the first tr is the headers of a table and the last tr is the footer/paging numbers of a table, and I don't want to select either of these two. I know I can do
$("#mytable>tbody>tr:gt(0)")
to skip the first tr, but that will include the last tr, which is the paging number row in my case.
What is the most efficient way to get tr's whose indices are greater than 0 and less than the length of the collection? In other words, I want all tr's except the first and the last in the collection.
Any idea? Thanks.
A:
try
$('#mytable > tbody > tr').not(':first').not(':last')
A:
:gt (greater than) and :lt (lower than) can be used with negative numbers to count backwards
$('#mytable tr:gt(0):lt(-1)')
FIDDLE
As a sidenote, there are thead and tfoot elements specifically for headers and footers in a table
A:
You can use slice :
$('#mytable > tbody > tr').slice(1, -1);
Negative index goes to the end.
http://jsfiddle.net/VpC2V/
|
[
"stackoverflow",
"0056532828.txt"
] | Q:
GridBagLayout: Elements shrink at a very specific panel height
I'm using GridBagLayout to create a panel consisting of 4 sub-panels. The 4 sub-panels are colored magenta, blue, red, and cyan, while the master panel is green. The goal is to arrange these 4 sub-panels in a certain fashion and theoretically, no green should show. Fortunately, I have a working example of exactly what I want to achieve:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int width = d.width;
int height = 1046;
JFrame frame = new JFrame("4.5 test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel masterPanel = new JPanel(new GridBagLayout());
masterPanel.setBackground(Color.GREEN);
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1.0;
c.weighty = 1.0;
// 1
JPanel leftUpper = new JPanel();
leftUpper.setBackground(Color.MAGENTA);
leftUpper.setPreferredSize(new Dimension(width/3, height/7));
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTH;
masterPanel.add(leftUpper, c);
// 2
JPanel leftLower = new JPanel();
leftLower.setBackground(Color.BLUE);
leftLower.setPreferredSize(new Dimension(width/3, height - height/7));
c.gridheight = 2;
c.anchor = GridBagConstraints.SOUTH;
masterPanel.add(leftLower, c);
// 3
JPanel rightUpper = new JPanel();
rightUpper.setBackground(Color.RED);
rightUpper.setPreferredSize(new Dimension(width - width/3, height - height/5));
c.gridx = 1;
c.gridheight = 1;
masterPanel.add(rightUpper, c);
// 4
JPanel rightLower = new JPanel();
rightLower.setBackground(Color.CYAN);
rightLower.setPreferredSize(new Dimension(width - width/3, height/5));
c.gridy = 1;
masterPanel.add(rightLower, c);
frame.add(masterPanel);
frame.pack();
frame.setVisible(true);
}
}
When run, this gives
this correct result. In fact, every height under 1046 works as intended.
However, the moment one changes Line 16 to this:
int height = 1047;
All goes to hell and we get this instead. This holds true for every height above 1047 as well. The panels are in the right positions, but are far from the right sizes. Note that unlike height, changing the width has no (unintended) effect.
I wouldn't be so surprised by this behavior if it wasn't caused by such a small (arbitrary?) limit in size. For context, I am using the 1.8 Java RunTime environment. My computer screen resolution is 1920x1080. Why is this happening, how can one remedy this, and if this is an atrocious practice, what detailed alternative can you provide?
A:
When a GridBagLayout cannot accommodate all child components’ preferred sizes, it “gives up” and sets every single child component to its minimum size. So, one solution is to set each component’s minimum size to its preferred size.
However, rather than trying to mathematically account for every pixel on your screen, you have more robust options.
One solution is to only set the size of one panel, in any particular dimension, so the other one always takes up the remaining space. This way, you can never “overflow” the available space. BorderLayout is well suited to this, since its center component is stretched to take up all available space that the side components don’t use.
So, for your magenta and blue panels, you would set the height of the magenta panel only:
JPanel leftPanel = new JPanel(new BorderLayout());
// 1
JPanel leftUpper = new JPanel();
leftUpper.setBackground(Color.MAGENTA);
leftUpper.setPreferredSize(new Dimension(1, height/7));
leftPanel.add(leftUpper, BorderLayout.NORTH);
// 2
JPanel leftLower = new JPanel();
leftLower.setBackground(Color.BLUE);
leftPanel.add(leftLower, BorderLayout.CENTER);
And similarly for the red and cyan ones:
JPanel rightPanel = new JPanel(new BorderLayout());
// 3
JPanel rightUpper = new JPanel();
rightUpper.setBackground(Color.RED);
rightPanel.add(rightUpper, BorderLayout.CENTER);
// 4
JPanel rightLower = new JPanel();
rightLower.setBackground(Color.CYAN);
rightLower.setPreferredSize(new Dimension(1, height/5));
rightPanel.add(rightLower, BorderLayout.SOUTH);
And then you do something similar to those two panels themselves, to put them together:
JPanel masterPanel = new JPanel(new BorderLayout());
masterPanel.setBackground(Color.GREEN);
leftPanel.setPreferredSize(new Dimension(width / 3,
leftPanel.getPreferredSize().height));
masterPanel.add(leftPanel, BorderLayout.WEST);
masterPanel.add(rightPanel, BorderLayout.CENTER);
And since reporting of the borders given to windows by the system’s window manager is unreliable, you avoid doing any explicit math and just maximize the window:
frame.add(masterPanel);
frame.pack();
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setVisible(true);
If you absolutely need to maintain the ratio among the panels (for instance, magenta_height : blue_height :: 1 : 6), you can do that with a SpringLayout, but SpringLayout is more complicated and usually isn’t worth the trouble. It allows you to specify size ranges which can be multiples of other size ranges:
SpringLayout layout = new SpringLayout();
JPanel masterPanel = new JPanel(layout);
masterPanel.setBackground(Color.GREEN);
// 1
JPanel leftUpper = new JPanel();
leftUpper.setBackground(Color.MAGENTA);
masterPanel.add(leftUpper);
// 2
JPanel leftLower = new JPanel();
leftLower.setBackground(Color.BLUE);
masterPanel.add(leftLower);
// 3
JPanel rightUpper = new JPanel();
rightUpper.setBackground(Color.RED);
masterPanel.add(rightUpper);
// 4
JPanel rightLower = new JPanel();
rightLower.setBackground(Color.CYAN);
masterPanel.add(rightLower);
Spring leftUpperHeight = Spring.height(leftUpper);
Spring leftLowerHeight = Spring.scale(leftUpperHeight, 6);
Spring rightLowerHeight = Spring.scale(leftUpperHeight, 7 / 5f);
Spring leftWidth = Spring.width(leftUpper);
Spring rightWidth = Spring.scale(leftWidth, 3);
layout.getConstraints(leftLower).setHeight(leftLowerHeight);
layout.getConstraints(rightLower).setHeight(rightLowerHeight);
layout.getConstraints(rightUpper).setWidth(rightWidth);
layout.getConstraints(rightLower).setWidth(rightWidth);
// Place leftLower beneath leftUpper.
layout.putConstraint(
SpringLayout.NORTH, leftLower, 0,
SpringLayout.SOUTH, leftUpper);
// Make leftLower's width match leftUpper's width.
layout.putConstraint(
SpringLayout.WEST, leftLower, 0,
SpringLayout.WEST, leftUpper);
layout.putConstraint(
SpringLayout.EAST, leftLower, 0,
SpringLayout.EAST, leftUpper);
// Make container high enough to hold both leftLower and leftUpper.
layout.putConstraint(
SpringLayout.SOUTH, masterPanel, 0,
SpringLayout.SOUTH, leftLower);
// Place rightUpper and rightLower to the right of leftUpper.
layout.putConstraint(
SpringLayout.WEST, rightLower, 0,
SpringLayout.EAST, leftUpper);
layout.putConstraint(
SpringLayout.WEST, rightUpper, 0,
SpringLayout.WEST, rightLower);
// Make container wide enough to accommodate rightUpper and rightLower.
layout.putConstraint(
SpringLayout.EAST, masterPanel, 0,
SpringLayout.EAST, rightLower);
// Align bottom of rightLower with bottom of leftLower.
layout.putConstraint(
SpringLayout.SOUTH, rightLower, 0,
SpringLayout.SOUTH, leftLower);
// Place rightUpper above rightLower.
layout.putConstraint(
SpringLayout.SOUTH, rightUpper, 0,
SpringLayout.NORTH, rightLower);
// Stretch rightUpper to reach to the top of the container.
layout.putConstraint(
SpringLayout.NORTH, rightUpper, 0,
SpringLayout.NORTH, masterPanel);
|
[
"stackoverflow",
"0022611775.txt"
] | Q:
Storing a list of data temporarily future use
I have a search box on my website where a user can search songs. My website shows a list of all possible songs matched to users search string. Now i want to store the list of those songs into buffer or temporary storage memory so that even if user refreshes/changes a page the list stays there.
Now after some research i found the possible ways are-:
creating a file and storing that data into it
Creating a session for storing data.
Creating a cookie for storing list.
I don't know any other way. So what according to you is possible way to store data temporarily in PHP
A:
This is most definitly a job for PHP sessions.
The requirements are:
temporary storage that survives page reload/change: sessions do just that
per user cache: sessions are per-user
Of course cookies can do that as well, but they are pretty limited in size, and are always exchanged between the client and the server at each request, so it could be argued they are more suited to long surviving data, for example per-browser user preferences for a website.
Creating files should be avoided, since, for example by using a file store for sessions, PHP will do just that by itself, with an automated system able to handle session expiration that would be more tedious to implement manually.
|
[
"stackoverflow",
"0025869955.txt"
] | Q:
Helvetica Font is Showing Up in Italic
For some reason with a regular font tag like: ("www.hookandshell.com") I'm talking about The text links in the upper right that say "Join for FREE | Create a Listing | Sign in". Sorry I should have been more clear.
body {
font-family: Helvetica, Arial, sans-serif;
color:#029FC6;
background-color: #FFFFFF;
width: 100%;
height: 100%;
margin:0;
}
It shows up as italic in Google Chrome and Internet Explorer 11. But not Firefox. Any ideas?
A:
This literally took me five seconds to debug. In your CSS file (site.css line 276, 314, 383, 403, 427...) you have:
#footer .aboutLink and #footer .aboutLink and #footer .featured > p and #footer .featured span p and .headerText
which contains:
font-style:italic
|
[
"superuser",
"0000275500.txt"
] | Q:
Deep Freeze can't be removed
I have already installed Deep Freeze and now I cannot see its icon in taskbar. It's hidden
now; I can't thaw it and remove it.
A:
You need the original setup file (exe) to remove Deep Freeze. Run that file and choose the uninstall option.
This web page has also useful info about your problem: How to Remove Faronics Deep Freeze 6 in Three Different Ways.
|
[
"stackoverflow",
"0026221316.txt"
] | Q:
Unable to listUserMessages() - 500 Backend Error
When using the below code to attempt to list messages received by a brand new gmail account I just set up, I get
[Google_Service_Exception] Error calling GET https://www.googleapis.com/gmail/v1/users/myGmailAccount%40gmail.com/messages: (500) Backend Error
I know the validation portion is working correctly because I'm able to make minor modifications and query the books api as shown in this example. Below is the code I'm using to attempt to query recent messages received...
const EMAIL = '[email protected]';
private $permissions = [
'https://www.googleapis.com/auth/gmail.readonly'
];
private $serviceAccount = '[email protected]';
/** @var Google_Service_Gmail */
private $gmail = null;
/** @var null|string */
private static $serviceToken = null;
public function __construct()
{
$client = new Google_Client();
$client->setApplicationName($this->applicationName);
$this->gmail = new Google_Service_Gmail($client);
//authentication
if (isset(self::$serviceToken)) {
$client->setAccessToken(self::$serviceToken);
}
$credentials = new Google_Auth_AssertionCredentials(
$this->serviceAccount,
$this->permissions,
$this->getKey()
);
$client->setAssertionCredentials($credentials);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($credentials);
}
self::$serviceToken = $client->getAccessToken();
}
public function getMessages()
{
$this->gmail->users_messages->listUsersMessages(self::EMAIL);
}
I have granted API access to gmail:
The 500 makes me believe this is an internal error with the gmail API or I'm missing something the PHP client isn't validating.
A:
This one work for me. My understanding is service account doesn't have a mailbox and it's not too sure which mailbox it should work on. So you can't use listUsersMessages() function to get all messages.
So you will need to specify which email address that the service account need to work on.
Make sure that the scope has been allowed on Web App API to
1. Add this line:
$credentials->sub = self::EMAIL;
Before:
$client->setAssertionCredentials($credentials);
2. Then Update your getMessages() to:
$this->gmail->users_messages->listUsersMessages("me");
Hope this helps!
|
[
"stackoverflow",
"0012190290.txt"
] | Q:
CodeIgniter - Write file names to database from multiple images
I have an upload form with two file upload fields. I am trying to upload the files, and then write the file names to the same row in a database. I have everything working except the file names get written to their own row. I am guessing it's because I am making two separate calls to the model, but I am not sure how to go about doing it in one call since they each have their own "if" statement.
To make my question clear. How do I write the names of two uploaded files to the same row in the database?
Any ideas would be great. This is the code I am working with. Thanks.
View:
<?php echo form_open_multipart('upload_controller'); ?>
<p>
<input type="file" name="userfile">
</p>
<p>
<input type="file" name="userfile1">
</p>
<p><?php echo form_submit('submit', 'Upload them files!') ?></p>
<?php form_close() ?>
Controller:
if (isset($_POST['submit'])) {
$this->load->library('upload');
if (!empty($_FILES['userfile']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->upload->initialize($config);
// Upload file 1
if ($this->upload->do_upload('userfile')) {
$img = $this->upload->data();
$file_name = $img['file_name'];
$this->load->model('upload_file', 'upload_model');
$this->upload_model->upload_file1($file_name);
}
}
if (!empty($_FILES['userfile1']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->upload->initialize($config);
// Upload file 2
if ($this->upload->do_upload('userfile1')) {
$img = $this->upload->data();
$file_name = $img['file_name'];
$this->load->model('upload_file', 'upload_model');
$this->upload_model->upload_file2($file_name);
} else {
echo $this->upload->display_errors();
}
}
} else {
$this->load->view("upload_form");
}
Model:
public function upload_file1($file_name) {
$data = array('file1' => $file_name);
$this->db->insert('images_table', $data);
}
public function upload_file2($file_name) {
$data = array('file2' => $file_name);
$this->db->insert('images_table', $data);
}
Database row:
| id | file1 | file2 |
A:
Try like this(if you have the number of files....in your case it is "2" )
$this->load->model('upload_file', 'upload_model');
for($i=1;$i<=$numimg;$i++) //in your case $numimg = 2;
{
if($this->upload->do_upload('File'.$i)) //File1,File2 are filenames
{
$img_data = $this->upload->data();
$images[$i] = $img_data['file_name'];
}
}
$data['Image'] = implode(',',$images);
$this->upload_model->upload_file($data);
at your model:
public function upload_file2($data)
{
$data = array('file_name' => $data['Image']);
$this->db->insert('images_table', $data);
}
That's it.If you want to retrive it from database use
$images = explode(',',$data->file_name);
it will give you an array of image names.
|
[
"stackoverflow",
"0056494250.txt"
] | Q:
How can I get the value of a localStorage array item using a variable?
I have a few localStorage keys that look something like this in dev tools -> storage...
panel_1 {"name":"test_name", "item_1":"test_item", "link_1":"test_link"})
...each panel I have has multiple items and links with a number in its name that increases. I am trying to go through each panel and for the panel I want to get the first item and link to display on a web page then keep looping through until there's no more items or links before doing the same with the next panel. At the moment when I try this it says "undefined". How can I get the correct value? Right now my code looks like this...
var total_keys = localStorage.length;
var panels = [];
var key;
var location = $('#panels .wrapper article:first-child()');
for($i = 0; $i < total_keys; $i++) {
key = localStorage.key($i);
if(key.slice(0, 6) === 'panel_') {
panels.push(key);
};
};
var total_panels = panels.length;
for(var $i = 0; $i < total_panels; $i++) {
var panel = JSON.parse(localStorage.getItem(panels[$i]));
var items = function() {
for(var $x = 1; $x <= 5; $x++) {
var item = 'item_'+$x;
alert(panel.item);
};
};
location.after(items);
};
A:
I think you mean panel[item] instead of panel.item (which means panel["items"]). It would explain the "undefined" value.
The most inner loop should look like
for(var $x = 1; $x <= 5; $x++) {
var item = 'item_'+$x;
alert(panel[item]);
};
|
[
"stackoverflow",
"0042630479.txt"
] | Q:
Build heartbeat service with RxJS
I want to build a heatbeat service for my angular2 website. A remote device is the host of the website and the client should be able to detect if the device is not reachable/offline.
The service should poll periodically the (webserver) remote device.
I know that a failed HTTP-Call cannot be directly equated with the online/offline status of the whole device, but for my requirements that should be enough.
Currently I'm using the following Observable which is placed inside of an angular service:
public getStatus() {
return this.http.get(this.config.apiEndpoint + this.fileName)
.map(() => { return '1'; })
.timeout(500)
.catch(() => {return '0';})
.retry()
.delay(1500)
.repeat();
}
The target of the observable is just an almost empty file on the webserver.
A component subscribes to the observable/service and then shows a notification if the device status changes.
In principle the Observable works, but it provides a continuous stream of ones (online) and zeros (offline) to the component which subscribed to it. Now I have to add some logic to the component (and every other component which uses this service) to handle for example two successive zeros, that a notification is only shown once.
It would be much cleaner and a better separation of concerns if the service could do this extra work and only provide a result (to the component) when the status of the device changed. I also tried to use a Observable.timer with a flatMap but failed to get it working, but I expect rxjs provides a solution to this problem.
A:
you may use distinctUntilChanged operator, it will ensure to pass only distinct values.
Hope this helps!!
|
[
"stackoverflow",
"0063306647.txt"
] | Q:
Various forms of looping and iteration in Elisp
I am trying to understand all the looping constructs in Emacs Lisp.
In one example I am trying to iterate over a list of symbols and print them to the *message* buffer like so:
(let* ((plist package-activated-list) ;; list of loaded packages
(sorted-plist (sort plist 'string<)))
(--map (message (format "%s" it)) sorted-plist))
--map is a function from the package dash.el.
How to do this in pure Elisp?
Now how do I iterate over a list in Elisp, without using other packages.
I have seen some examples using while and dolist macro, for example here:
https://www.gnu.org/software/emacs/manual/html_node/elisp/Iteration.html
But those are destructive, non-functional ways to express a loop.
Coming from Scheme (having worked with it and with SICP some twenty years ago!), I tend to prefer functional, non destructive (does that always lead to recursive?) ways to express ideas.
So what are idiomatic ways to loop over a list of items in Emacs Lisp?
Also: Are there ways to express loops in a functional fashion in Emacs Lisp?
What I have found so far
Loop Macros (from Common Lisp?) prefixed with "cl-*"
https://www.gnu.org/software/emacs/manual/html_node/cl/Loop-Facility.html
Iteration Clauses
https://www.gnu.org/software/emacs/manual/html_node/cl/Iteration-Clauses.html#Iteration-Clauses
Dash.el
https://github.com/magnars/dash.el
Magnar Sveen's excellent package marketed as "A modern list api for Emacs. No 'cl required."
What else is there? Any recommended reading?
A:
dolist is not destructive, and that is probably the most idiomatic way in Emacs Lisp, or Common Lisp for that matter, to loop over a list when you just want to do something with each member in turn:
(setq *properties* '(prop1 prop2 prop3))
(dolist (p *properties*)
(print p))
The seq-doseq function does the same thing as dolist, but accepts a sequence argument (e.g., a list, vector, or string):
(seq-doseq (p *properties*)
(print p))
If a more functional style is desired, the seq-do function applies a function to the elements of a sequence and returns the original sequence. This function is similar to the Scheme procedure for-each, which is also used for its side effects.
(seq-do #'(lambda (p) (print p)) *properties*)
|
[
"superuser",
"0000444210.txt"
] | Q:
Odd Apple AirPort Express behaviour
I've been using a rather old AirPort Express for home Wi-Fi for a number of years. (It's old enough that it only supports WPA, not WPA2 -- perhaps this is an indication that I should upgrade!)
In the last week I've been experiencing very slow internet over the Wi-Fi. Suspecting that someone outside my home was leeching from me (despite a reasonable password and MAC address filtering turned on) I decided to change some settings: I changed the SSID, turned off broadcast of the SSID and changed the password.
After these changes, I managed to connect using the new password on my iPad. But on the other devices I tried (iPhone, PS3) I was not able to connect. In fact, I only succeeded in connecting when I entered my OLD password!
Is this a known issue with ancient AirPort Express units? Is my unit cracked and unrecoverable?
A:
Wow, you must have purchased that 802.11g AirPort Express during the first few months of its availability in the summer of 2004, and never upgraded the firmware. I believe a firmware update supporting WPA2 for that model was released before the end of 2004. What firmware version are you running, 6.0? I believe 6.3 is the latest for that model.
Could it be that you changed the base station's administrator password, but not its wireless network password? Or that your change didn't "stick" for some reason? (Edit: Never mind, I re-read your question and realized you'd connected from your iPad with the new password.)
Try power-cycling your Express to make sure the change had a chance to take effect. Then go back into the AirPort Utility and tell it to show you your network password, and see what it says.
You might also want to take this opportunity to update to firmware 6.3. Or buy the new 2012 AirPort Express, which seems to be getting good reviews.
|
[
"stackoverflow",
"0060737998.txt"
] | Q:
Stacked Area Plot with ggplot in R: How to only only use the highest of y per corresponding x?
I'm trying to create a stacked area plot but it looks bad (see link below).
Below is my data. The dates should be x-axis, and the cases should be the y-axis. However, the same date occurs multiple times with different number of cases. When this happens, I want the date to be represented once with the sum of the cases for that particular date (and for that particular type).
Note also that the stacked area plot must be split into the 3 types ("type" column in the data below).
My data looks like this:
# Groups: type [3]
Province.State Country.Region Lat Long date cases type loc total cumsum
<chr> <chr> <dbl> <dbl> <date> <int> <chr> <chr> <int> <int>
1 "" France 47 2 2020-01-24 2 confirmed Europe 2 2
2 "" France 47 2 2020-01-25 1 confirmed Europe 1 3
3 "" Germany 51 9 2020-01-27 1 confirmed Europe 1 4
4 "" France 47 2 2020-01-28 1 confirmed Europe 4 5
5 "" Germany 51 9 2020-01-28 3 confirmed Europe 4 8
6 "" Finland 64 26 2020-01-29 1 confirmed Europe 2 9
7 "" France 47 2 2020-01-29 1 confirmed Europe 2 10
8 "" Germany 51 9 2020-01-31 1 confirmed Europe 6 11
9 "" Italy 43 12 2020-01-31 2 confirmed Europe 6 13
10 "" Sweden 63 16 2020-01-31 1 confirmed Europe 6 14
# ... with 378 more rows
Here's how the plot looks so far:
Ugly stacked area plot so far
A:
With the example data given and the description of the desired plot ...
For type = "death" I simply replicated the given data. Just as an example.
From the desciption it was not totally clear how the final plot should like, e.g. would your show different countries or locations.
Therefore I just made a stacked are plot of cumulated cases by date and time. Try this:
library(ggplot2)
library(dplyr)
dataset <- structure(list(
id = c(
"1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"
),
Province.State = c(
"\"\"", "\"\"", "\"\"", "\"\"", "\"\"",
"\"\"", "\"\"", "\"\"", "\"\"", "\"\"", "\"\"", "\"\"", "\"\"",
"\"\"", "\"\"", "\"\"", "\"\"", "\"\"", "\"\"", "\"\""
),
Country.Region = c(
"France", "France", "Germany", "France",
"Germany", "Finland", "France", "Germany", "Italy", "Sweden",
"France", "France", "Germany", "France", "Germany", "Finland",
"France", "Germany", "Italy", "Sweden"
), Lat = c(
47L, 47L,
51L, 47L, 51L, 64L, 47L, 51L, 43L, 63L, 47L, 47L, 51L, 47L,
51L, 64L, 47L, 51L, 43L, 63L
), Long = c(
2L, 2L, 9L, 2L, 9L,
26L, 2L, 9L, 12L, 16L, 2L, 2L, 9L, 2L, 9L, 26L, 2L, 9L, 12L,
16L
), date = structure(c(
18285, 18286, 18288, 18289, 18289,
18290, 18290, 18292, 18292, 18292, 18285, 18286, 18288, 18289,
18289, 18290, 18290, 18292, 18292, 18292
), class = "Date"),
cases = c(
2L, 1L, 1L, 1L, 3L, 1L, 1L, 1L, 2L, 1L, 2L, 1L,
1L, 1L, 3L, 1L, 1L, 1L, 2L, 1L
), type = c(
"confirmed", "confirmed",
"confirmed", "confirmed", "confirmed", "confirmed", "confirmed",
"confirmed", "confirmed", "confirmed", "death", "death",
"death", "death", "death", "death", "death", "death", "death",
"death"
), loc = c(
"Europe", "Europe", "Europe", "Europe",
"Europe", "Europe", "Europe", "Europe", "Europe", "Europe",
"Europe", "Europe", "Europe", "Europe", "Europe", "Europe",
"Europe", "Europe", "Europe", "Europe"
), total = c(
2L, 1L,
1L, 4L, 4L, 2L, 2L, 6L, 6L, 6L, 2L, 1L, 1L, 4L, 4L, 2L, 2L,
6L, 6L, 6L
), cumsum = c(
2L, 3L, 4L, 5L, 8L, 9L, 10L, 11L,
13L, 14L, 2L, 3L, 4L, 5L, 8L, 9L, 10L, 11L, 13L, 14L
)
), class = c(
"tbl_df",
"tbl", "data.frame"
), row.names = c(NA, -20L))
dataset_plot <- dataset %>%
# Number of cases by date, type
count(date, type, wt = cases, name = "cases") %>%
# Cumulated sum over time by type
group_by(type) %>%
arrange(date) %>%
mutate(cumsum = cumsum(cases))
ggplot(dataset_plot, aes(date, cumsum, fill = type)) +
geom_area()
Created on 2020-03-18 by the reprex package (v0.3.0)
|
[
"stackoverflow",
"0048806986.txt"
] | Q:
What are the consequences of mutating state in a reducer?
The redux guide states:
We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead.
I happened to catch myself writing the following snippet of working code:
[actions.setSelection](state, {payload}) {
state[payload.key] = payload.value;
return state;
},
I had a bad vibe about it, and revisited the guide for wisdom. I have since rewritten it as this:
[actions.setSelection](state, {payload}) {
const result = Object.assign({}, state);
result[payload.key] = payload.value;
return result;
},
I am fairly sure I have offended the commandment noted above elsewhere in my code. What kind of consequence am I looking at for not tracking them down with diligence?
(Note: The reducer syntax above is via redux-actions. It would otherwise be the block of code in a reducer fn switch/case.)
A:
Mutating state is an anti-pattern in React. React uses a rendering engine which depends on the fact that state changes are observable. This observation is made by comparing previous state with next state. It will alter a virtual dom with the differences and write changed elements back to the dom.
When you alter the internal state, React does not know what's changed, and even worse; it's notion of the current state is incorrect. So the dom and virtual dom will become out of sync.
Redux uses the same idea to update it's store; an action can be observed by reducers which calculate the next state of the store. Changes are emitted and for example consumed by react-redux connect.
So in short: never ever, mutate state. Instead of Object.assign you can use the stage-3 spread syntax:
{...previousState,...changes}
Also please note, this is true for arrays as well!
|
[
"stackoverflow",
"0025730163.txt"
] | Q:
How to save custom ListFragment state with orientation change
I am being more thorough with hope the question will actually be easier to understand.
Activity purpose: allow users to select images from gallery; display thumbnail of image in ListFragment along with title user gave the image; when user is finished save each image's uri and title, and the name user gave this collection of images.
Problem: When device is rotated the FragmentList is losing all the images and titles the user already chose, ie, all the rows of the list are missing.
Attempted problem solving:
Implemented the RetainedFragment to save the List collection on device rotation. Previously I had not done this and figured "Ah, the adapter is fed a blank List collection on creation. I'll save the state of the List and then when Activity's onCreate is called I can feed the retained List to the Adapter constructor and it'll work." But it didn't.
Then I thought, "Of course it is not working, you haven't notified the adapter of the change!" So I put the adapter.notifyDataSetChanged() in the onCreate. This didn't work.
Then I moved the adapter.notifyDataSetChanged() to onStart thinking I might need to notify the adapter later in the activity's lifecycle. Didn't work.
Note: I have another activity in this same app that use this same custom ListViewFragment and the state of the ListFragment is being preserved with device orientation changes. That activity has two principle differences: the fragment is hard coded into the .xml (I don't think that would make a difference, other than perhaps maybe Android's native saving of .xml fragments is different than programmatically added ones); and that activity uses a Loader and LoaderManager and gets its data from a Provider that I built (which gathers data from my SQLite database). Looking at the differences between these two activities is what caused me to think "you're not handling the data feeding the adapter appropriately somehow" and inspired me to use the RetainedFragment to save the List collection when the device is rotated.
...which is prompting me to think about figuring out how to, as Android says on their Loader page about LoaderManager:
"An abstract class associated with an Activity or Fragment for managing one or more Loader instances. This helps an application manage longer-running operations in conjunction with the Activity or Fragment lifecycle; the most common use of this is with a CursorLoader, however applications are free to write their own loaders for loading other types of data."
It is the "loading other types of data" part that has me thinking "Could I use a LoaderManager to load the List data? Two reasons I shy from this: 1) what I have already, at least conceptually, ought to work; 2) what I'm doing currently isn't really a "longer-running operation" at all, I don't think.
Research:
StackOverflow Fool proof way to handle Fragment on orientation change
save state of a fragment.
I think the RetainedFragment I am using saves what needs to be saved.(?)
Once for all, how to correctly save instance state of Fragments in back stack?
Save backstack fragments.
Not shown in my code pasted below, but my activity dynamically creates three other fragments and I use the following if savedInstanceState !=null and those fragments' states are saved without doing any work in onSaveInstanceState() (this is partly why it feels like my problem isn't with doing something in onSaveInstanceState because Android handles the saving my other fragments state so shouldn't it do it, too, with the ListFragment? Seems like it should).
if(savedInstanceState.containsKey(AddActivity_Frag1.F1_TAG)){
frag1 = (AddActivity_Frag1)getFragmentManager().getFragment(savedInstanceState, AddActivity_Frag1.F1_TAG);
}
Understanding Fragment's setRetainInstance(boolean)
Many of the StackOverflow questions surrounding my query seem to be mostly about how to save the scroll position of the ListFragment with orientation change but I don't need to do that (though I did read them looking for tips that might help).
Android Fragments
Android Loaders
Android Caching Bitmaps (RetainFragment stuff)
Activity - with many, hopefully unrelated things, removed:
public class AddActivity extends Activity{
// data collection
List<ImageBean> beanList;
// adapter
AddCollectionAdapter adapter;
// ListViewFragment tag
private static final String LVF_TAG = "list fragment tag";
// fragment handles
ListViewFragment listFrag;
// Handles images; LruCache for bitmapes
ImageHandler imageHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add2);
// Create ImageHandler that holds LruCache
imageHandler = new ImageHandler(this, getFragmentManager());
// Obtain retained List<ImageBean> or create new List<ImageBean>.
RetainedFragment retainFragment = RetainedFragment.findOrCreateRetainFragment(getFragmentManager());
beanList = retainFragment.list;
if(beanList == null){
beanList = new ArrayList<ImageBean>();
retainFragment.list = beanList;
}
// create fragments
if(savedInstanceState == null){
listFrag = new ListViewFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.add_fragFrame, listFrag, LVF_TAG);
ft.commit();
}else{
listFrag = (ListViewFragment)getFragmentManager().findFragmentByTag(LVF_TAG);
}
// create adapter
adapter = new AddCollectionAdapter(this, beanList);
// set list fragment adapter
listFrag.setListAdapter(adapter);
}
@Override
protected void onStart() {
// TESTING: If device orientation has changed List<ImageBean> was saved
// with a RetainedFragment. Seed the adapter with the retained
// List.
adapter.notifyDataSetChanged();
super.onStart();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// Android automatically saves visible fragments here. (?)
super.onSaveInstanceState(outState);
}
/*
* ImageBean.
*/
public static class ImageBean{
private String collectionName; // Title of image collection
private String imageUri; // Image URI as a string
private String imageTitle; // Title given to image
public ImageBean(String name, String uri, String title){
collectionName = name;
imageUri = uri;
imageTitle = title;
}
public String getCollectionName() {
return collectionName;
}
public String getImageUri() {
return imageUri;
}
public String getImageTitle() {
return imageTitle;
}
}
/*
* Called when user is finished selecting images.
*
* Performs a bulk insert to the Provider.
*/
private void saveToDatabase() {
int arraySize = beanList.size();
final ContentValues[] valuesArray = new ContentValues[arraySize];
ContentValues values;
String imageuri;
String title;
int counter = 0;
for(ImageBean image : beanList){
imageuri = image.getImageUri();
title = image.getImageTitle();
values = new ContentValues();
values.put(CollectionsTable.COL_NAME, nameOfCollection);
values.put(CollectionsTable.COL_IMAGEURI, imageuri);
values.put(CollectionsTable.COL_TITLE, title);
values.put(CollectionsTable.COL_SEQ, counter +1);
valuesArray[counter] = values;
counter++;
}
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... arg0) {
getContentResolver().bulkInsert(CollectionsContentProvider.COLLECTIONS_URI, valuesArray);
return null;
}
@Override
protected void onPostExecute(Void result) {
// End this activity.
finish();
}
};
task.execute();
}
public ImageHandler getImageHandler(){
return imageHandler;
}
}
class RetainedFragment extends Fragment{
private static final String TAG = "RetainedFragment";
// data to retain
public List<AddActivity.ImageBean> list;
public static RetainedFragment findOrCreateRetainFragment(FragmentManager fm){
RetainedFragment fragment = (RetainedFragment)fm.findFragmentByTag(TAG);
if(fragment == null){
fragment = new RetainedFragment();
fm.beginTransaction().add(fragment, TAG);
}
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}
ListFragment:
public class ListViewFragment extends ListFragment {
ListFragListener listener;
public interface ListFragListener{
public void listFragListener(Cursor cursor);
}
@Override
public void onCreate(Bundle savedInstanceState) {
// Retain this fragment across configuration change
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Set listener
if(activity instanceof ListFragListener){
listener = (ListFragListener)activity;
}else{
//Instantiating activity does not implement ListFragListener.
}
}
@Override
public void onListItemClick(ListView listView, View v, int position, long id) {
// no action necessary
}
}
Adapter:
public class AddCollectionAdapter extends BaseAdapter {
// data collection
List<ImageBean> beanList;
// layout inflator
private LayoutInflater inflater;
// context
Context context;
public AddCollectionAdapter(Context context, List<ImageBean> beanList){
this.context = context;
this.beanList = beanList;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return beanList.size();
}
@Override
public Object getItem(int position) {
return beanList.get(position);
}
@Override
public long getItemId(int arg0) {
// collection not from database nor is going directly to database; this is useless.
return 0;
}
// holder pattern
private class ViewHolder{
ImageView imageView;
TextView titleView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View xmlTemplate = convertView;
if(xmlTemplate == null){
//inflate xml
xmlTemplate = inflater.inflate(R.layout.frag_listview_row, null);
// initilaize ViewHolder
holder = new ViewHolder();
// get views that are inside the xml
holder.imageView = (ImageView)xmlTemplate.findViewById(R.id.add_lvrow_image);
holder.titleView = (TextView)xmlTemplate.findViewById(R.id.add_lvrow_title);
// set tag
xmlTemplate.setTag(holder);
}else{
holder = (ViewHolder)xmlTemplate.getTag();
}
// Get image details from List<ImageBean>
ImageBean bean = beanList.get(position);
String imageUri = bean.getImageUri();
String title = bean.getImageTitle();
// Set Holder ImageView bitmap; Use parent activity's ImageHandler to load image into Holder's ImageView.
((AddActivity)context).getImageHandler().loadBitmap(imageUri, holder.imageView, Constants.LISTVIEW_XML_WIDTH, Constants.LISTVIEW_XML_HEIGHT);
// Set Holder's TextView.
holder.titleView.setText(title);
// return view
return xmlTemplate;
}
}
A:
Solved. After putting log statements in strategic places I discovered the RetainedFragment's list was always null. After some head scratching noticed this in RetainedFragment:
fm.beginTransaction().add(fragment, TAG);
I'm missing the commit()!
After I added that the state is being preserved now with configuration changes.
More information related to saving ListFragment state that I discovered during my trials and tribulations:
If you add a fragment via:
if(savedInstanceState == null){
listFrag = new ListViewFragment();
// programmatically add fragment to ViewGroup
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.add_fragFrame, listFrag, LVF_TAG);
}
Then either of these will work in the else:
1) This one works because Android takes care of saving the Fragment:
listFrag = (ListViewFragment)getFragmentManager().findFragmentByTag(LVF_TAG);
2) This one works because the fragment was specifically saved into bundle in
onSaveInstanceState:
listFrag = (ListViewFragment)getFragmentManager().getFragment(savedInstanceState, LVF_TAG);
For number 2 to work, this happens in onSaveInstanceState():
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getFragmentManager().putFragment(outState, LVF_TAG, listFrag);
}
|
[
"stackoverflow",
"0062384927.txt"
] | Q:
MySQL: Define data type for CONCAT with alias
This question is about the possibility to define a capacity/max-length when calling CONCAT and storing it as an alias.
I have a rather complex MySQL query using Common Table Expressions (CTE) used to model comments. It creates a new variable path consisting of a comment's score (# of votes) and id seperated by a comma and concatenated with its parent path using CONCAT. This allow sorting comments within threads by their score.
A path looks like e.g. 000010,000005,000014,000008, which means that the comment with id 8 has a score of 14 and its parent, which itself does not have a parent, has id 5 and a score of 10. With all comments having path of this format allows sorting them how I want.
The bottom line is that initially the path only consists of a single score with id, and in the recursive call we will continue concatenating into longer and longer paths when visiting the children.
However, it seems that the initial call to CONCAT immediately limits the size to 15 of all subsequent concatenations to the longest initial concatenation, so they are just cut after 15 characters. Making the initial concatenation longer than 15, will limit the subsequent concatenations to exactly the longest initial concatenation (so effectively doesn't concatenate anything).
Currently I have worked around this issue by initially padding a lot of zeros to the right and remove them in the recursive call. However, this uses regular expression and even though it is fairly simply I am afraid it is not good for performance.
Is there any way to define with the initial call of CONCAT what the capacity/maximum-length of the created alias variable should be?
This is the query that is made:
WITH RECURSIVE first_comments (id, content, parent_id, user_id, created, votes, path) AS (
(
SELECT r.id, r.content, r.parent_id, r.user_id, r.created, r.votes, CONCAT_WS(",", LPAD(r.votes,6,0), LPAD(r.id,6,0), LPAD(0,243,0)) as path
FROM (
SELECT c.id, c.content, c.parent_id, c.user_id, c.created, COUNT(DISTINCT v.id) AS votes
FROM comments AS c
LEFT JOIN comment_votes AS v ON c.id = v.comment_id
WHERE c.post_id = ? AND c.parent_id IS NULL
GROUP BY c.id
) as r
)
UNION ALL
(
SELECT r.id, r.content, r.parent_id, r.user_id, r.created, r.votes, CONCAT_WS(",", REGEXP_REPLACE(fle.path, ",[0]+$", ""), LPAD(r.votes,6,0), LPAD(r.id,6,0)) as path
FROM first_comments AS fle
JOIN (
SELECT c.id, c.content, c.parent_id, c.user_id, c.created, COUNT(DISTINCT v.id) AS votes
FROM comments AS c
LEFT JOIN comment_votes AS v ON c.id = v.comment_id
WHERE c.post_id = ?
GROUP BY c.id
) AS r ON fle.id = r.parent_id
)
)
SELECT id, content, parent_id, user_id, path, created, votes FROM first_comments
ORDER BY pat
(Inspired by: Order comments by thread path and by number of total votes)
Initially I create path with CONCAT_WS(",", LPAD(r.votes,6,0), LPAD(r.id,6,0), LPAD(0,243,0)) as path, which creates the path containing the score and id of top-most comments (without parents), and pads 243 zeros to the right. So e.g. 000010,000005,0...0 for the top-most comment with id 5.
Then recursively (but effectively only with the first recursive call, as thereafter the pattern never matches), we use regular expressions to remove all the trailing zeros including the last comma and add the score and id of this comment: CONCAT_WS(",", REGEXP_REPLACE(fle.path, ",[0]+$", ""), LPAD(r.votes,6,0), LPAD(r.id,6,0)) as path.
It would therefore be nice to just add something to the initial definition of path instead of this work-around. But I don't know what other way could be possible and better?
Any help and idea is appreciated!
// Edit: Problem was solved (and simplified) with GMB's help and a small addition, see my comment under the accepted answer.
A:
How about appending the paths into a JSON array instead of a string? This seamlessly overcomes the problem that you are having, and you can still order by.
So:
WITH RECURSIVE first_comments (id, content, parent_id, user_id, created, votes, js_path) AS (
SELECT
c.id,
c.content,
c.parent_id,
c.user_id,
c.created,
COUNT(DISTINCT v.id) AS votes,
JSON_ARRAY(LPAD(COUNT(DISTINCT v.id), 6, 0), LPAD(c.id, 6, 0)) as js_path
FROM comments AS c
LEFT JOIN comment_votes AS v ON c.id = v.comment_id
WHERE c.post_id = ? AND c.parent_id IS NULL
GROUP BY c.id
UNION ALL
SELECT
r.id,
r.content,
r.parent_id,
r.user_id,
r.created,
r.votes,
JSON_ARRAY_APPEND(
fle.js_path,
'$', LPAD(r.votes, 6, 0),
'$', LPAD(r.id, 6, 0)
) as js_path
FROM first_comments AS fle
JOIN (
SELECT
c.id,
c.content,
c.parent_id,
c.user_id,
c.created,
COUNT(DISTINCT v.id) AS votes
FROM comments AS c
LEFT JOIN comment_votes AS v ON c.id = v.comment_id
WHERE c.post_id = ?
GROUP BY c.id
) AS r ON fle.id = r.parent_id
)
SELECT id, content, parent_id, user_id, js_path, created, votes
FROM first_comments
ORDER BY js_path
Note that I simplified the query as follows:
there is no need for a subquery in the anchor of the recursive query
union all does not require parentheses around the two queries
|
[
"stackoverflow",
"0051564028.txt"
] | Q:
Check rows from all columns that matches specific value
If I have a data.table:
d <- data.table("ID" = c(1, 2, 2, 4, 6, 6),
"TYPE" = c(1, 1, 2, 2, 3, 3),
"CLASS" = c(1, 2, 3, 4, 5, 6))
I know I can remove values greater than a specific value like this:
r <- d[!(d$TYPE > 2), ]
However, if I want to apply this to all of the columns in the entire table instead of just TYPE (basically drop any rows that have a value > 2 in the entire table), how would I generalize the above statement (avoiding using a for loop if possible).
I know I can do d > 2 resulting in a boolean index table, but if I put that into the above line of code it give me an error:
d[!d>2, ]
Results in a invalid matrix type
Note
It was brought up that this question is similar to Return an entire row if the value in any specific set of columns meets a certain criteria.
However, they are working with a data.frame and I am working with a data.table the notation is different. Not a duplicate question due to that.
A:
Using apply with any
d[!apply(d>2,1,any)]
ID TYPE CLASS
1: 1 1 1
2: 2 1 2
Or rowSums
d[rowSums(d>2)==0,]
ID TYPE CLASS
1: 1 1 1
2: 2 1 2
|
[
"stackoverflow",
"0035122806.txt"
] | Q:
Using Chart.js 2.0, display line chart values
I am trying to get Chart.js 2.0 to display point values in a line chart using the animation onComplete function. I found a post making it work using 1.02, how to display data values on Chart.js, but I am unable to make it work in v2.
My failing fiddle is at Line Chart v2. Any help would be appreciated.
var chartData = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [{
label: "Buttons",
strokeColor: "#79D1CF",
tension: 0,
fill: false,
data: [60, 80, 81, 56, 55, 40]
}, {
label: "Zipppers",
strokeColor: "rgba(255,255,0,1)",
tension: 0,
fill: false,
data: [50, 75, 42, 33, 80, 21]
}]
};
var options = {
animation: {
onComplete: function() {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
//alert(ctx.font);
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
var datasetName = chartData.data.datasets[0].label;
alert(chartData.data.datasets[0].label)
myLine.data.datasets.forEach(function(dataset) {
ctx.fillStyle = dataset.strokeColor;
dataset.points.forEach(function(points) {
ctx.fillText(points.value, points.x, points.y - 10);
});
})
}
}
};
Chart.defaults.global.responsive = true;
Chart.defaults.global.maintainAspectRatio = true;
Chart.defaults.global.title.display = true;
Chart.defaults.global.title.text = "My Chart";
Chart.defaults.global.title.fontSize = 30;
Chart.defaults.global.legend.position = "bottom";
Chart.defaults.global.hover.mode = "label";
Chart.defaults.global.tooltips.enabled = true;
var ctx = document.getElementById("myChart1").getContext("2d");
var myLine = new Chart(ctx, {
type: 'line',
data: chartData,
options: options
});
A:
I can only assume there is a better way, but for now try this:
var options = {
animation: {
onComplete: function() {
var ctx = this.chart.ctx;
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.chart.config.data.datasets.forEach(function(dataset) {
ctx.fillStyle = dataset.strokeColor;
dataset.metaDataset._points.forEach(function(p) {
ctx.fillText(p._chart.config.data.datasets[p._datasetIndex].data[p._index], p._model.x, p._model.y - 10);
});
})
}
}};
|
[
"stackoverflow",
"0032017049.txt"
] | Q:
Clear an arbitrary 2D array
I am working on some embedded code for which I can't use the STL containers. I have several 2D arrays whose size is known at compile time and want to write a template function to clear them. However, I can't get it to work. Here's what I tried:
template <std::size_t sizeA, std::size_t sizeB>
void clearArray(float a[sizeA][sizeB])
{
float* begin = &a[0][0];
std::fill_n(begin, sizeA * sizeB, 0.0);
}
int main()
{
float f[5][6];
clearArray(f);
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 6; ++j)
cout << f[i][j] << " ";
}
However, the compiler can't successfully perform argument lookup:
test.cpp(22): error C2784: 'void clearArray(float [sizeA][sizeB])' : could not deduce template argument for 'float [sizeA][sizeB]' from 'float [5][6]'
1> test.cpp(13) : see declaration of 'clearArray'
Is there a way to do this? I know I could use sizeof(f)/sizeof(float) to get the number of elements, or I could specify the dimensions manually, but I was hoping to make it as simple as possible.
Also, I tested this in VS2012 but the compiler for this embedded system does not support C++11.
A:
When you pass array to function, it will decay to pointer (in this case it will become float (*a)[sizeB], the infomation about size will be lost, that's why the compiler could not deduce template argument. You can change it from pass by value to pass by reference, which will keep the size of array:
template <std::size_t sizeA, std::size_t sizeB>
void clearArray(float (&a)[sizeA][sizeB])
LIVE
|
[
"salesforce.stackexchange",
"0000111278.txt"
] | Q:
Package with web-services to integrate Salesforce with a 3rd party
I`m going to create a package that other Salesforce users can install to integrate with a 3rd party system. When package is installed 3rd party knows nothing about new system where that package was installed for example login details to connect to that new environment.
Is there a good way of providing such information, or each time the package is installed someone will need to do it manually i.e. Visualforce page or button press to send login details to a 3rd party? Also are there any best-practices for that?
Thanks
A:
You can implement InstallHandler interface and add this class to a package. You can make an async callout and pass required data to third party service
|
[
"stackoverflow",
"0059694797.txt"
] | Q:
create a file name with the current date & time in python
I used datedime to create a directory name in Python like this:
Code:
import os
from datetime import datetime
os.mkdir(f"{datetime.now()}")
os.listdir()
And when I use ls command in terminal, I got the following result:
And when I got dir names with Python:
Code:
os.listdir()
Output:
['.gitlab-ci.yml',
'public',
'AUTHORS',
'.dockerignore',
'requirements',
'.git',
'Dockerfile',
'manage.py',
'.editorconfig',
'2020-01-11 12:53:08.425169',
'logs',
'.idea',
'branch.sh',
'initial_media',
'README.md',
'__pycache__',
'setup.cfg',
'.gitignore',
'venv']
Solution:
I solved it with strftime() method:
Code:
import os
from datetime import datetime
os.mkdir(f'{datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")}')
TL;DR
Why single quotes appear in dir name? Is it a problem from datetime __str__ or __repr__ functions?
A:
Your directory name probably doesn't have quotes. It's just displayed that way. Try adding a space to your strftime example and see what happens:
os.mkdir(f'{datetime.now().strftime("%Y-%m-%d_%I %M-%S_%p")}')
See Why is 'ls' suddenly wrapping items with spaces in single quotes?
|
[
"outdoors.stackexchange",
"0000024669.txt"
] | Q:
How do you overcome a preventative fear of dangerous wildlife
I live in Colorado and love hiking alone, it's quiet and peaceful. I want to be more 'free' to hike in early morning or late evening when it's dark or backpack in remote places, but at this point I still get a bit nervous about dangerous wildlife (bears and mountain lions). I don't want to lose a healthy fear of these animals but I also want to find that 'freedom' to hike in remote areas and in the dark.
How can I gain a confidence to hike in these ways with a healthy, and not preventative, fear of dangerous wildlife?
A:
A lot of it is just by doing it.
Both species are quite low density, and the number of wild animal deaths/injuries are very small. Regions that are dangerous for bears are those where they are very familiar with human presence and associate it with snacks, and very remote areas where they haven't seen humans at all, and have no fear of them.
Wolves are very shy of people. I've seen one once at a distance in the arctic tundra, and tracks are fairly common in Willmore Wilderness.
Bear tracks too:
On the coast here, almost all of the animal injuries are racoons. I think second place goes to rats.
I ran into a trapper. We got to talking. The boys with me asked if he'd ever been attacked. "No, neve... Wait: Once I had a muskrat come up to me and try to bite my ankle."
My only attack has been a muskrat. I've almost stepped on a beaver once. They are FAST.
I don't hike at twilight in the wild. My eyes are night eyes, so I'm running a sense short. Too easy to startle someone. And usually I've had a long day. I generally stop about 2 hours before dark, set up camp.
I don't regard predators nearly as serious a threat as large herbavores. Male moose aren't sane when in rut. Mule deer aren't much better, but they aren't as big.
I have dogsledded into the night on several occasions. Mushing under moonlight is magic, but requires a good trail (snowmobile trails are ideal) But winter the bears are asleep.
|
[
"stackoverflow",
"0006241275.txt"
] | Q:
Move a large instance method to shared, and create an instance stub -- good idea?
Quick question: If I have a very large function/sub in a class that is an instance method (i.e., not Shared), do I gain or lose anything by moving that to a shared method and then declaring a small stub method for the instance use?
I.e., I go from this:
Public Sub MyBigMethod(ByVal Foobar As String)
If String.IsNullOrWhitespace(Foobar) Then
Throw New ArgumentNullException("Foobar")
End If
' Lots and lots of ugly code.
' Really. There is lots of ugly code here.
'
' Lorem ipsum dolor sit amet, consectetur adipiscing
' elit. Aliquam vel erat sit amet massa ultricies
' adipiscing. Mauris eu est ligula, a pharetra lorem.
End Sub
To This:
Private Shared Sub MyBigMethod(ByVal Obj as MyObj, ByVal Foobar As String)
' Lots and lots of ugly code.
' Really. There is lots of ugly code here.
'
' Lorem ipsum dolor sit amet, consectetur adipiscing
' elit. Aliquam vel erat sit amet massa ultricies
' adipiscing. Mauris eu est ligula, a pharetra lorem.
End Sub
Public Sub MyBigMethod(ByVal Foobar As String)
If String.IsNullOrWhitespace(Foobar) Then
Throw New ArgumentNullException("Foobar")
End If
Call MyClass.MyBigMethod(Me, Foobar)
End Sub
My thinking is I save on memory size per each instance of the object. Because each instance only has to lug around the stub method which handles calling the shared version and passing an instance of itself to the shared method so that it can do whatever it needs to do. But I'll wager that I sacrifice a very teensy amount of speed because of the added function call overhead.
Correct?
A:
My thinking is I save on memory size per each instance of the object.
This is incorrect, because each instance does not store the method in memory. Instance methods are only stored in memory once. Function instructions are different than class members (which are stored per instance).
Furthermore, you gain a bit of a penalty by adding a function call, because the state of the stub method must be saved when calling the shared method. Then, it has to be loaded back when the shared method terminates. (Note: This is the same penalty you take when making any non-inline function call; the penalty becomes more stiff as the quantity and size of parameters increase)
You went down a logical line of thinking, but it was based upon the assumption that each instance gets its own logic instructions -- when they are actually used across all instances of a class.
|
[
"stackoverflow",
"0030108089.txt"
] | Q:
how to set action property in a form to go to another form in same html page and how to get values in first form into second form?
I have 2 forms in same html page.one form get the values and then these values must be pass to the second form.But I don't know how to go to the second form through the first form.
when using action="#" , I can go to same page. but how to go to the second form after get values from first form?Can someone please help me?
A:
Form’s action property is to be used when you are sending your form data to server. In your case you can do the copying client-side (by using JavaScript) and you can omit the first form tag altogether.
See the example below.
document.getElementById('first_form_submit').addEventListener('click', function(event){
event.preventDefault();
document.getElementById('second_form_input').value = document.getElementById('first_form_input').value;
// do the same for other form fields that you need to copy
});
.form {
padding: 1em;
background-color: #eee;
margin-bottom: 1em;
}
<div id="first_form" class="form">
<input type="text" id="first_form_input" />
<button id="first_form_submit">Send values to second form</button>
</div>
<form method="post" action="some-url" class="form">
<input type="text" id="second_form_input" name="some_name" />
</form>
|
[
"stackoverflow",
"0028324469.txt"
] | Q:
How to correctly inherit class from another file
I have 2 files. driver.py and stack.py. I would like to inherit the base class stack.py's 2 functions into driver.py, but I am having issues with actually creating the class (encounter attribute errors while running). The code is supposed to ask for user input until 'end' is received and the program should output all the input.
Please disregard the ill-formatting, I had issues including the 'import' lines in the snippets.
stack.py
class Stack:
def __init__(self):
'''A new empty stack'''
self.items = []
def push(self, o):
'''Make o the new top item in this Stack.'''
self.items.append(o)
def pop(self):
'''Remove and return the top item.'''
return self.items.pop()
def peek(self):
'''Return the top item.'''
return self.items[-1]
def isEmpty(self):
'''Return whether this stack is empty.'''
return self.items == []
def size(self):
'''Return the number of items in this stack.'''
return len(self.items)
class UpStack:
def __init__(self):
'''A new empty stack'''
self.stack = []
def push(self, o):
'''Make o the new top item in this Stack.'''
self.stack.insert(0, o)
def pop(self):
'''Remove and return the top item.'''
return self.stack.pop(0)
def peek(self):
'''Return the top item.'''
return self.stack[0]
def isEmpty(self):
'''Return whether this stack is empty.'''
return self.stack == []
def size(self):
'''Return the number of items in this stack.'''
return len(self.stack)
driver.py
from stack import *
if __name__ == '__main__':
#-----------------------------------Stack Code-----------------------------------
s = Stack()
s.push('Hello')
print(s.pop())
data = ""
while data.lower() != 'end':
data = input("Enter Command: ")
if data.lower() != 'end':
s.push(data)
while not s.isEmpty():
print(s.pop())
#-----------------------------------UpStack Code-----------------------------------
u = UpStack()
u.push('Hello')
print(u.pop())
data = ""
while data.lower() != 'end':
data = input("Enter Command: ")
if data.lower() != 'end':
u.push(data)
while not u.isEmpty():
print(u.pop())
driver.py attempted class version
from stack import *
class Test:
#-----------------------------------Stack Code-----------------------------------
def stacker(self):
s = Stack()
s.push('Hello')
print(s.pop())
data = ""
while data.lower() != 'end'
data = input("Enter Command: ")
if data.lower() != 'end':
s.push(data)
while not s.is_empty():
print(s.pop())
#-----------------------------------UpStack Code-----------------------------------
def upstacker(self):
u = UpStack()
u.push('Hello')
print(u.pop())
data = ""
while data.lower() != 'end':
data = input("Enter Command: ")
if data.lower() != 'end':
u.push(data)
while not u.is_empty():
print(u.pop())
Since I don't see anything when I actually run the code, I make an instance of it and this is what I get.
>>> s = Stack()
>>> s
<stack.Stack object at 0x103bb3a58>
>>> s.push(2)
>>> s.stacker()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
s.stacker()
AttributeError: 'Stack' object has no attribute 'stacker'
A:
That is because Stack() instance does not have stacker() method.
stacker method belongs to your Test class.
instead of typing
>>> s = Stack()
>>> s.stacker()
you should use
>>> t = Test()
>>> t.stacker()
|
[
"stackoverflow",
"0007477486.txt"
] | Q:
Use clock() to count program execution time
I'm using something like this to count how long does it takes my program from start to finish:
int main(){
clock_t startClock = clock();
.... // many codes
clock_t endClock = clock();
printf("%ld", (endClock - startClock) / CLOCKS_PER_SEC);
}
And my question is, since there are multiple process running at the same time, say if for x amount of time my process is in idle, durning that time will clock tick within my program?
So basically my concern is, say there's 1000 clock cycle passed by, but my process only uses 500 of them, will I get 500 or 1000 from (endClock - startClock)?
Thanks.
A:
This depends on the OS. On Windows, clock() measures wall-time. On Linux/Posix, it measures the combined CPU time of all the threads.
If you want wall-time on Linux, you should use gettimeofday().
If you want CPU-time on Windows, you should use GetProcessTimes().
EDIT:
So if you're on Windows, clock() will measure idle time.
On Linux, clock() will not measure idle time.
A:
clock on POSIX measures cpu time, but it usually has extremely poor resolution. Instead, modern programs should use clock_gettime with the CLOCK_PROCESS_CPUTIME_ID clock-id. This will give up to nanosecond-resolution results, and usually it's really just about that good.
|
[
"emacs.stackexchange",
"0000050543.txt"
] | Q:
Insert date using a calendar - where other language rather than english is desired
I am interested in inserting custom dates using the calendar, I found Insert date using a calendar which turned out to be quite useful. Org calendar : change date language? seems to have no effect (I would also like to avoid setting the variable via seq)
While this code works fine for English dates.
(defun my/org-insert-date-english ()
"Insert a date at point using `org-read-date' with its optional argument
of TO-TIME so that the user can customize the date format more easily."
(interactive)
(require 'org)
(let ((time (org-read-date nil 'to-time nil "Date: ")))
(insert (format-time-string "(W%W) (%a) %d %b %Y"
time))))
;; Inserts: (W19) (Thu) 16 May 2019
I was trying to modify it to get it work to insert dates in a different laguage than english.
My modifications below don't work but I am not sure why, could someone pin point what am I doing wrong?
(defun my/org-insert-date-german ()
"Insert a date at point using `org-read-date' with its optional argument
of TO-TIME so that the user can customize the date format more easily."
(interactive)
(require 'org)
(letf ((time (org-read-date nil 'to-time nil "Date: "))
(calendar-week-start-day 1)
(calendar-day-name-array ["Montag" "Dienstag" "Mittwoch" "Donnerstag"
"Freitag" "Samstag" "Sonntag"])
(calendar-month-name-array ["Januar" "Februar" "März" "April" "Mai" "Juni"
"Juli" "August" "September" "Oktober" "November"
"Dezember"]))
(insert (format-time-string "(KW%W) (%a) %d. %b %Y"
time))))
;; Inserts: (KW19) (Thu) 16. May 2019
;; Desired: (KW19) (Donnerstag) 16. Mai 2019
Notes:
- Using Emacs 26.2
A:
What you're trying to do won't work with format-time-string. Here's a time string formatter using calendar-* functions which you can use in place of format-time-string. I haven't thought about how the offsetting is done with calendar-week-start-day so for now you have to start the name array with "Sonntag".
(defun calendar-format-time-string (format-string time)
(let* ((date (org-date-to-gregorian (format-time-string "%F" time)))
(week (car (calendar-iso-from-absolute (time-to-days time))))
(week-day (calendar-day-name date))
(day (calendar-extract-day date))
(month (calendar-month-name (calendar-extract-month date)))
(year (calendar-extract-year date))
(specs (format-spec-make ?W week ?a week-day ?d day ?b month ?Y year)))
(format-spec format-string specs)))
Here's a more flexible approach which formats %B (January), %b (Jan), %A (Sunday), and %a (Sun) using calendar functions. All other specs are passed to format-time-string.
(defun calendar-format-time-string (format-string time)
(let* ((case-fold-search nil)
(date (org-date-to-gregorian (format-time-string "%F" time)))
(week (calendar-day-name date))
(week-abbrev (calendar-day-name date t))
(month (calendar-month-name (calendar-extract-month date)))
(month-abbrev (calendar-month-name (calendar-extract-month date) t))
(specs (format-spec-make ?A week
?a week-abbrev
?B month
?b month-abbrev))
time-string)
(with-temp-buffer
(insert format-string)
(goto-char (point-min))
(while (re-search-forward (mapconcat (lambda (char)
(concat "%" (char-to-string char)))
(mapcar #'car specs) "\\|")
nil t)
(let ((spec (format-spec (match-string 0) specs)))
(delete-char -2)
(insert spec)))
(setq time-string (buffer-substring (point-min) (point-max))))
(format-time-string time-string time)))
BTW you can also use format-time-string directly by changing the time locale:
$ sudo emacs /etc/locale.gen
uncomment the de_DE.UTF-8 UTF-8 line and save the file
$ sudo locale-gen
M-x set-locale-environment RET de_DE.UTF-8 RET
restart emacs
Now set system-time-locale as a local variable and you're done:
(let ((system-time-locale "de_DE.UTF-8")
(time (org-read-date nil 'to-time nil "Date: ")))
(insert (format-time-string "(KW%W) (%A) %d. %B %Y" time)))
;; => (KW19) (Samstag) 18. Mai 2019
|
[
"stackoverflow",
"0028491683.txt"
] | Q:
Search for specific strings of data from a binary .dat file, only extract text
Sub ReadEntireFileAndPlaceOnWorksheet()
Dim X As Long, Ys As Long, FileNum As Long, TotalFile As String, FileName As String, Result() As String, Lines() As String, rng As Range, i As Long, used As Range, lc As Long
FileName = "C:\Users\MEA\Documents\ELCM2\DUMMY_FILE.dat"
FileNum = FreeFile
Open FileName For Binary As #FileNum
TotalFile = Space(LOF(FileNum))
Get #FileNum, , TotalFile
Close #FileNum
Lines = Split(TotalFile, vbNewLine)
Ys = 1
lc = Sheet3.Cells(1, Columns.Count).End(xlToLeft).Column
For X = 1 To UBound(Lines)
Ys = Ys + 1
ReDim Preserve Result(1 To Ys)
Result(Ys) = "'" & Lines(X - 1)
Set used = Sheet1.Cells(Sheet1.Rows.Count, lc + 1).End(xlUp).Rows
Set rng = used.Offset(1, 0)
rng.Value = Result(Ys)
Next
End Sub
I am trying to find some data in a .dat (binary file). The data should look like this:
MiHo14.dat
MDF 3.00 TGT 15.0
Time: 06:40:29 PM
Recording Duration: 00:05:02
Database: DB
Experiment: Min Air take
Workspace: MINAIR
Devices: ETKC:1,ETKC:2
Program Description: 0delivupd2
Module_delivupd2
WP: _AWD_5
RP: _AWD
§@
Minimum intake - + revs - Downward gear
The code I have currently extracts all data from .dat file and places in Excel file looks like this:
MiHo14.dat
MDF 3.00 TGT 15.0
Time: 06:40:29 PM
Recording Duration: 00:05:02
Database: DB
Experiment: Min Air take
Workspace: MINAIR
Devices: ETKC:1,ETKC:2
Program Description: 0delivupd2
Module_delivupd2
WP: _AWD_5
RP: _AWD
§@
Minimum intake - + revs - Downward gear
Bã|ŽA…@@,s~?
B{À¿…@@@Ý‚Iá
Á<
"@²n¢”N@ÇÿÈÿj
Ð=“SØ•N@ÇÿÈÿj
à¨. —N@ÇÿÈÿj
8²œg˜N@ÇÿÈÿj
0NI,¯™N@ÈÿÈÿj
Ðä$öšN@ÈÿÈÿj
@Q›=œN@ÈÿÈÿj
Пe…N@ÇÿÈÿj
GàÍžN@ÇÿÈÿj"
etc....
I need to know how to use instr function to extract the information by identifying lines that include ":", the other challenge is there is a final line in the data that is a user comment this user comment can basically be any text, I need to be able to extract it without extracting the whole file because as you can see there is a lot of symbols (gibberish) that comes with it.
A:
I don't think you want to copy all the HD/PR/TX blocks to get the output you are looking for.
Examining at your file, one difference I can see between valid and invalid data (from your perspective) is that the invalid data either does not end with CR-LF combination, or contains a null character. If that characteristic is consistent throughout your files, you may be able to use it to advantage:
Below is the code I used, and the results. You can modify the variables for your own routine and see if it works consistently.
Option Explicit
Sub ProcessDAT()
Const sFN As String = "D:\Users\Ron\Desktop\DUMMY_FILE.dat"
Const sEND As String = vbCrLf
Dim S As String, COL As Collection, V As Variant, I As Long
Dim R As Range
Open sFN For Binary Access Read As #1
S = Space(LOF(1))
Get #1, , S
Close #1
V = Split(S, sEND)
Set COL = New Collection
For I = 0 To UBound(V)
If InStr(V(I), Chr(0)) = 0 Then COL.Add V(I)
Next I
ReDim V(1 To COL.Count, 1 To 1)
For I = 1 To UBound(V)
V(I, 1) = COL(I)
Next I
Set R = Range("a1").Resize(UBound(V))
R = V
End Sub
Results
Time: 11:47:42 AM
Recording Duration: 00:01:09
Database: Testproject
Experiment: Measurement_Dummy
Workspace: Workspace
Devices: ETKC:1
Program Description: LPOOPL14
WP: LPOOPL14d2_1
RP: LPOOPL14d2
§@
Dummy test data
|
[
"stackoverflow",
"0062804576.txt"
] | Q:
How to enable request metrics for S3 bucket using Cloudformation or CDK
I am able to enable (request metrics for S3 bucket, apid option) in the AWS console manually by checking the checkbox(https://ibb.co/bWDLcNT). But I am trying to do that via code. I tried finding solutions that uses CloudFormation / CDK(nodeJs) / AWS CLI. But no luck. I found solutions only about creating metrics with the filters etc and not much about enabling it.. Any suggestions?
A:
You can use MetricsConfiguration:
Specifies a metrics configuration for the CloudWatch request metrics (specified by the metrics configuration ID) from an Amazon S3 bucket.
The example would be:
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: somey-bucket-3344-name
MetricsConfigurations:
- Id: EntireBucket
Note EntireBucket. This is the required Id to enable the paid metrics.
|
[
"russian.stackexchange",
"0000017425.txt"
] | Q:
Difference in usage between "наоборот" and "напротив"
Она его не упрекала, потому что знала, что сложись все наоборот, если бы её парень упал, а она бы продолжала идти, она бы тоже не остановилась.
I assume that "наоборот" cannot be replaced with "напротив" here, while in the following context, they seem to be interchangeable, even if "напротив" is a better choice. I wonder when I should choose one over the other.
– Причащать? Нет, душа моя. Совершенно лишнее.
– Почему? Я, напротив/наоборот, нахожу, что для ребёнка необходимо.
A:
In the first example, adverb наоборот is a modifier, or, as Russian grammar usually calls it, circumstance of manner of action (обстоятельство образа действия): it is part of the syntactic structure of the sentence, we can put a question to it: сложись как? — наоборот.
In the second example, adverb наоборот/напротив is an introductory word (answers no question, is not part of the syntactic structure of the sentence).
Here's the difference. As introductory words, наоборот and напротив are interchangeable. As modifiers, they aren't. Note that unlike наоборот, напротив may also be a preposition.
|
[
"stackoverflow",
"0003566690.txt"
] | Q:
Best way to manage date objects?
I have some date objects that are Date of the Date class, and others that are Time.
The trouble is is that when I parse them to load them chronologically, they list first as the Times, followed by the Dates.
This is the code that loads them :
query.any_of do |any_of|
any_of.with(:date).greater_than((params[:current_date] || DateTime.now))
any_of.with(:end_date).greater_than((params[:current_date] || DateTime.now))
any_of.with(:time).greater_than((params[:current_date] || DateTime.now))
end
Is there a way to combine both dates and times as one universal object to compare them? Ideally, it would be converting the Date Objects to Time since Time objects can hold dates and time.
A:
def universal_time
if self.date != nil
self.date.to_time
else
self.time
end
end
|
[
"stackoverflow",
"0036749401.txt"
] | Q:
Python Scheduled Log Rotating
EDIT:
Looks like other people are having a similar issue with TimedRotatingFileHandler.
Python TimedRotatingFileHandler not rotating at midnight till something new is written to the log file. How to fix this?
Why doesn't my TimedRotatingFileHandler rotate at midnight?
Apparently, the logs don't rotate unless there is some activity happening in the logs. Is there a way I can achieve the scheduled rotating functionality I want using the builtin Handlers without having to create a custom rotator?
ORIGINAL POST:
I'm using the TimedRotatingFileHandler of Python's logging module to rotate my logs regularly.
I've specified the configurations in logging.conf for my app's loggers and handlers as such:
[logger_worker]
level=DEBUG
propogate=0
qualname=worker
handlers=workerHandler
[handler_workerHandler]
class=handlers.TimedRotatingFileHandler
level=DEBUG
formatter=standardFormatter
args=("/var/log/app/worker.log","M",1,30,None,False,False)
Note: for testing purposes I've configured the handler to rotate the logs on every minute, but ideally the logs will be rotated on a daily basis at midnight.
In my app, I am creating the logger like this:
logging.config.fileConfig("logging.conf")
log = logging.getLogger("worker")
log.debug('Hello world')
It is not working as I expected it to work:
It is not rotating all the logs
It is not rotating every minute as it is configured to do
Observe the ls -l output of the log directory:
-rw-r--r-- 1 root root 0 Apr 19 18:22 dpv.log
-rw-r----- 1 root root 5092 Apr 20 11:47 emperor.log
-rw-r--r-- 1 root root 88939 Apr 20 11:47 uwsgi.log
-rw-r--r-- 1 root root 494 Apr 20 11:46 worker.log
-rw-r--r-- 1 root root 45906 Apr 20 02:08 worker.log.2016-04-20_02-08
-rw-r--r-- 1 root root 494 Apr 20 11:34 worker.log.2016-04-20_11-34
-rw-r--r-- 1 root root 494 Apr 20 11:36 worker.log.2016-04-20_11-36
-rw-r--r-- 1 root root 494 Apr 20 11:44 worker.log.2016-04-20_11-44
What am I doing wrong? Is it possible to rotate the logs on a scheduled term even when nothing is being written to the logs?
A:
Seems TimedRotatingFileHandler doesn't have the functionality that you need.
You can try the following function for rotating the log files at the certain time.
def log_rollover(folder_path):
# folder_path: the absolute path to your log folder
today = str(datetime.date.today()).replace('-', '')
list_of_files = os.listdir(folder_path)
for log_file in list_of_files:
file_path = folder_path + '/' + log_file
if log_file.endswith('.log') and os.stat(file_path).st_size > 0:
new_file_path = file_path.split('.')[-2] + '-' + today + '.log'
subprocess.check_call(['cp', file_path, new_file_path])
subprocess.check_call(['gzip', new_file_path])
subprocess.check_call(['cp', '/dev/null', file_path])
Also you need to use a cron job to run the function at the certain time.
APScheduler can be a good option. For example if you want to run the cron job at 3 AM, you can use:
folderPath = '/var/log/app' # The path to your log folder
scheduler = BlockingScheduler()
scheduler.add_job(log_rollover, trigger='cron', args=[folderPath], hour=3, minute=0)
scheduler.start()
Don't forget to set your timezone for APScheduler.
|
[
"math.stackexchange",
"0000172707.txt"
] | Q:
Solving a polynomial modulo an integer
Say I have a polynomial $F$ of degree $n$ with coefficients in $Z_m$ and I wish to find $x$ such that $F(x)=0$ (mod $m$). For instance if $F(x)=x^{2}-a$ the solution would be the modulo $m$ squareroot of $a$ (if there is a solution).
I'm primarily interested in solving the general case.
Without loss of generality we may assume $F$ is irreducible since otherwise we can just factor $F=f_0\cdots f_1$ with $f_i$ irreducible and the solutions of $F$ will be the union of the solutions for all of the $f_i$.
One method similar to Hensel lifting I've already considered roughly would involve factoring $m=p_0^{a_0}\cdots p_k^{a_k}$ and brute forcing $x$ (mod $p_i$) for each $i$ and lifting them to solutions mod $p_i^{a_i}$. This would be problematic if $m$ was a large prime though.
So any of the following would be very useful:
Fast solutions for when $m$ is prime
Methods to prove there are no solutions
Any relevant research
A:
There is a nice randomized algorithm for finding the roots when $m=p$ is prime, it goes roughly as follows: first compute $$G(x) = \operatorname{gcd}\bigl( x^p-x,F(x)\bigr)$$
then $G(x)$ is the product of all the roots of $F(x)$ that are in $\mathbb Z/p$. Now for several random values of $a$ compute
$$ \operatorname{gcd}\bigl( (x+a)^{(p-1)/2}-1,G(x)\bigr)$$
this will probably result on a non trivial factor of $G$, because it separates roots $\alpha$ for which $x+a$ is a quadratic residue from those which are not.
You can repeat with the resulting factors until all the factors have degree one. This algorithm is very fast. It is described here.
|
[
"stackoverflow",
"0008475943.txt"
] | Q:
How to match CSV value in column get images
My images column data is:
images
------
acdfdf.jpg, bachdh.jpg, asa.jpg
How can I get a sorted list of all images?
<img src="acdfdf.jpg">
<img src="bachdh.jpg">
<img src="asa.jpg">
A:
Assuming everything is in an array:
<?php
sort($images);
?>
<?php foreach($images as $image): ?>
<img src="<?php echo $image; ?>" />
<?php endforeach; ?>
|
[
"stackoverflow",
"0060884278.txt"
] | Q:
line breaks not working on UILabel in tableFooterView
I habe a tableView with a footerView. It should display a simple label.
In my ViewController, in viewDidLoad, I assign the tableFooterView like so:
let footerView = MyFooterView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 0))
tableView.tableFooterView = footerView
MyFooterView is a UIView with a single label. The label setup looks like so:
label.font = someFont
label.adjustsFontForContentSizeCategory = true
label.textColor = .black
label.numberOfLines = 0
label.text = "my super looooooong label that should break some lines but it doesn't."
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 40),
label.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -40),
label.topAnchor.constraint(equalTo: self.topAnchor, constant: 20),
label.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -20)
])
In order to get AutoLayout to work with MyFooterView, I call this method inside UIViewControllers viewDidLayoutSubviews:
func sizeFooterToFit() {
if let footerView = self.tableFooterView {
footerView.setNeedsLayout()
footerView.layoutIfNeeded()
let height = footerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
var frame = footerView.frame
frame.size.height = height
footerView.frame = frame
self.tableFooterView = footerView
}
}
Problem: The lines in the label do not break. I get the following result:
What can I do so that the label has multiple lines? AutoLayout is working thanks to the method sizeFooterToFit. The only thing is that the labels height is only as high as a single line.
A:
HERE is the way how you can achieve it for tableHeaderView and with your case you just need to add below code in your UIViewController class
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
tbl.updateHeaderViewHeight()
}
And Helper extension
extension UITableView {
func updateHeaderViewHeight() {
if let header = self.tableFooterView {
let newSize = header.systemLayoutSizeFitting(CGSize(width: self.bounds.width, height: 0))
header.frame.size.height = newSize.height
}
}
}
And remove
func sizeFooterToFit() {
if let footerView = self.tableFooterView {
footerView.setNeedsLayout()
footerView.layoutIfNeeded()
let height = footerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
var frame = footerView.frame
frame.size.height = height
footerView.frame = frame
self.tableFooterView = footerView
}
}
Above code.
And result will be:
|
[
"stackoverflow",
"0057720297.txt"
] | Q:
Unable to read properties of a property containing the object
I'm having an issue trying to access the properties of an object, which has a reference property of another object. In other words, an object contained in other object.
After fetching the data from API calls like this one for example:https://api.apixu.com/v1/current.json?key=2352219608ed457fb3a12903193008&q=Helsinki my code get the response's data and set the hook's value: capitalWeather.
Anyways, the object has two attributes: location and current, which are also object type. Everytime I try to access any value from a reference, like accessing value of capitalWeather.location.region what I get is=
Uncaught TypeError: Cannot read property 'region' of undefined
As expected, It also applies for any of the other attributes: name,country,lat,lon,tz_id,etc....
I don't understand why I'm getting a typeError, considering both are object types.
This is the code snippet where the error takes place:
const Displayer = ({ country }) => {
const [capitalWeather,setWeather]=useState([]);
useEffect(() => {
axios.get(`https://api.apixu.com/v1/current.json?key=2352219608ed457fb3a12903193008&q=${country.capital}`)
.then(response => {
console.log('Promise fullfiled, succesfully fetched data');
setWeather(response.data);
})
}, [country.capital]);
console.log(capitalWeather.location.region);
return (<div className='displayer'>
<h2>{country.name}</h2>
<p>Capital {country.capital}</p>
<p>Population {country.population}</p>
<h4>Languages</h4>
<ul>
{country.languages.map(lang => <li key={lang.name}>{lang.name}</li>)}
</ul>
<img src={country.flag} alt='this is the country flag'></img>
{/*<Weather weather={capitalWeather}/>*/}
</div>)
}
A:
capitalWeather is initialized as an array in this code.
const [capitalWeather,setWeather]=useState([]);
capitalWeather.location.region for sure will throw an error because it does not have a property location.
|
[
"3dprinting.stackexchange",
"0000004533.txt"
] | Q:
Printer/Material/Setup recommendation for printing mechanical parts
I'm interested in printing small machine parts (gears, linkages, structural components) so I'm looking for accuracy and mechanical strength over speed and volume.
I'm also somewhat concerned about harmful emissions so would like a solution with some sort of filtration, whether it's built into the machine or something added. I'm thinking I will run the machine in an unventilated garage, which is quite warm and humid during the summer in Texas.
My price range is \$1500-\$2000 USD. I've looked at several options but I didn't really come across any scenarios like I've described and would like some advice from the experts before committing.
Anyone in a similar boat have any suggestions?
A:
Your environmental conditions will preclude finding a machine suitable for your purposes in the budget specified.
Humidity is a problem with many material types, especially nylon, but also with PLA and ABS, the more common filaments used in 3D printing.
You can likely reject PLA for your mechanical needs, as it is brittle and weak compared to ABS. PLA releases virtually no gases of concern, while some find ABS fumes to be offensive and dangerous.
The humidity issue is forefront in your search. You may have to construct within the garage a chamber in which you would operate a portable or window air conditioner unit, to keep the humidity in check. If you can assign a different budget to such a construction, that will leave your printer funding intact and better able to address your goal.
Selective Laser Sintering using nylon powder, also susceptible to humidity, which is sintered by a laser, hence the name, making very detailed and strong parts. The process is also self-supporting, allowing for fairly intricate parts. Once the machine is calibrated, the part accuracy can be quite good. Unfortunately, SLS machines are also out of the budget range you've noted.
You can use an external service to print the parts you design, at least at first, to get a better indication of how the various materials will work for you. Start with PLA, then move to ABS for a set of test parts, and even perhaps have some printed using SLS.
If you find, for example, that ABS will be strong enough, you might find an affordable 3D printer which will generate parts on your budget and timeline. For printing ABS, the warmer temperatures are to your advantage, but the humidity has to be properly addressed in any home/shop/garage installation.
|
[
"stackoverflow",
"0036521971.txt"
] | Q:
Quick way to search strings in a dataframe in r
I have a vector contains some strings like this
f <- c("a","b","c")
And I have a data frame (df) that contains some columns:
h1 h2 ...
1 a 20 ...
2 a 50 ...
3 a 60 ...
4 e 70 ...
5 e 80 ...
...
Now I am trying to write code to find out the rows that contains same string as I have in the vector.
i.e: sample output
h1 h2 ...
1 a 20 ...
2 a 50 ...
3 a 60 ...
...
My solution is to use a for loop to go through every item in f then use grep to find the rows I want. And use rbind() to put the rows together.
for(item in f){
newdf <- rbind(newdf, df[grep(item, df$h1),])
}
However my dataset is really big and this takes forever to find all the rows I want.
I am wondering if anyone has a better solution.
A:
This should be much faster than a for loop:
df[df$h1 %in% f,]
# h1 h2
#1 a 20
#2 a 50
#3 a 60
|
[
"stackoverflow",
"0053014681.txt"
] | Q:
How to Count number of Non-Number Words in Excel using VBA Function
For Example,
I'd like a String such as, "This is a Bunch of Words in a sequence of 13 possible 1 words from a Dictionary or BookZZ or Libgen.io 1876" to give me a result of 19 (because "13", "1876" and "1" are numbers and should not be counted).
I created Two Functions which I'm trying to use within this Function I'm asking about:
The first one is the following:
' NthWord prints out the Nth Word of a String of Text in an Excel Cell such
' as A1 or B19.
Function NthWord(ActiveCell As String, N As Integer)
Dim X As String
X = ActiveCell
X = Trim(Mid(Replace(ActiveCell, " ", Application.WorksheetFunction.Rept("
", Len(ActiveCell))), (N - 1) * Len(ActiveCell) + 1, Len(ActiveCell)))
NthWord = X
' In the Excel SpreadSheet:
' Trim (Mid(Substitute(A1, " ", Rept(" ", Len(A1))), (N - 1) * Len(A1)
' + 1, Len(A1)))
End Function
The second one is the following:
'NumberOfWords returns the number of words in a String
Function NumberOfWords(ActiveCell As String)
Dim X As String
X = ActiveCell
Dim i As Integer
i = 0
If Len(Trim(X)) = 0 Then
i = 0
Else:
i = Len(Trim(X)) - Len(Replace(X, " ", "")) + 1
End If
NumberOfWords = i
' In the Excel SpreadSheet
' IF(LEN(TRIM(A1))=0,0,LEN(TRIM(A1))-LEN(SUBSTITUTE(A1," ",""))+1)
End Function
My Attempt at printing the NumberOfNonNumberWords
Function NumberOfNonNumberWords(ActiveCell As String)
Dim X As String
X = ActiveCell
Dim count As Integer
count = 0
Dim i As Integer
If NumberOfWords(X) > 0 Then
For i = 1 To NumberOfWords(X)
If Not (IsNumeric(NthWord(X, i).Value)) Then
count = count + 1
End If
Next i
End If
NumberOfNonNumberWords = count
End Function
However, when I apply this function in the Excel Worksheet, I get an output of
#VALUE!
and I'm not sure why. How do I fix this?
A:
Split the whole string then count non-numeric elements.
function abcWords(str as string) as long
dim i as long, arr as variant
arr = split(str, chr(32))
for i=lbound(arr) to ubound(arr)
abcWords = abcWords - int(not isnumeric(arr(i)))
next i
end function
A:
You could just use SPLIT() to split the text on a space delimiter, then count the non-numeric words:
Function num_words(ByVal text As String)
Dim txt_split
txt_split = Split(text, " ")
Dim total_words As Long
total_words = 0
Dim i As Long
For i = LBound(txt_split) To UBound(txt_split)
If Not IsNumeric(txt_split(i)) Then
total_words = total_words + 1
End If
Next i
num_words = total_words
End Function
|
[
"stackoverflow",
"0011876798.txt"
] | Q:
Having a listbox call the ToString method for all of its items
I have a list box that contains a set of of PathItems. I have overridden the ToString method with a couple different cases depending on the user's preferences.
It is basically a list of file names contained in custom objects.
class PathItem
{
public static bool show_ext { get; set; }
public static bool use_full_path { get; set; }
public string filepath { get; set; }
public override string ToString()
{
if (use_full_path)
return filepath;
else if (show_ext)
return Path.GetFileName(filepath);
else
return Path.GetFileNameWithoutExtension(filepath);
}
}
The GUI has two checkboxes. One checkbox will show file extensions, another checkbox will show the absolute path of the file. Checking any of these will update the static variables defined above.
Whenever I select a checkbox, I would like the listbox to be updated to reflect the user's selection.
I believe the solution is to have the listbox refresh all of its items by calling the ToString method again to get new values for each item, but I'm not sure how this would be done.
Also I am not sure if this is true, but if I said
PathItem.show_ext = true;
would this apply to all existing PathItem objects?
UPDATE:
After trying the Refresh method as suggested, the strings in the list box weren't updated even when the checkboxes were checked (they fire off a Refresh call on ClickChanged). Wrote a print statement inside the ToString method, but upon refreshing, no message was printed out.
Not sure if this is because I am using custom objects in my list box.
This is how I'm adding items to my list box
foreach (string filename in files)
listBox1.Items.Add(new PathItem { filepath = filename });
A:
Interestingly, calling
myListBox.Refresh()
does not cause the ListBox re-evaluate ToString() on the contained objects. Presumably the values are cached somewhere.
You can use the following method to force a ListBox to re-evaluate ToString(). I tested it with >100 items in my ListBox (on a fast computer) and saw no visual artifacts or delay.
private void UpdateToString(ListBox listBox)
{
int count = listBox.Items.Count;
listBox.SuspendLayout();
for (int i = 0; i < count; i++)
{
listBox.Items[i] = listBox.Items[i];
}
listBox.ResumeLayout();
}
Also,
PathItem.show_ext = true;
would immediately affect every PathItem instance that references *show_ext* from that point forward, because *show_ext* is a static variable. It only has one value at any point in time, which is shared between all instances of that class.
|
[
"eosio.stackexchange",
"0000005463.txt"
] | Q:
Multiple smart contracts with single account
I have three smart contracts (A, B, C) and one account (X). As the requirement is I just need only one authority (administrator) who is going to manage all these smart contracts data. So I deployed these smart contracts using the same account. Whenever I need to manage data from table I need to deploy the particular smart contract first. For eg.
A, B and C smart contracts are deployed using account X. Data in
multi-index tables are saved respectively. In Latest, C is deployed so
now X can only access multi-index table and Actions of C. Now, if I
want to manage data of A smart contract, at this level for accessing
the table and Actions of A I need to deploy A again. So, the table is
in X's abi and can access now. Similarly for B.
Otherwise it gives error as,
Error 3060003: Contract Table Query Exception
Most likely, the given table doesn't exist in the blockchain.
Error Details:
Table documents is not specified in the ABI
My question is every time I need to manage data of any table, do I need to deploy its smart contract first? I don't want three different accounts for A, B and C. Please guide and suggest.
A:
You can deploy only one contract per account. If you deploy new contract on your account, existing contract is removed, but its data saved via multi_index table are alive. You need to merge three contracts into one.
Easiest way to do this is putting all methods of three contracts into one class.
Second, you can use multiple contract classes in one wasm, but you need to write down your own apply() function to dispatch action correctly. apply() is an entry point of eosio contract like main(), and it would be generated automatically unless you declare it explicitly. Refer to here. This way requires advanced knowledge about eos contract compilation, or you will fail to generate ABI correctly.
Third, you don't like it, but you can make three accounts and set admin account's active to each account's active permission instead of key.
contract1:
permission:
active: 1 1 admin@active
1 1 EOS8BQAdzgacbacUjuUwYR1wEMUcEPLu1DpucmD4xNSLhtXuDSAHe
contract2:
permission:
active: 1 1 admin@active
...
|
[
"stackoverflow",
"0017117305.txt"
] | Q:
How to get a ancestor node with a specific tag name
How I get the ancestor of a Yahoo UI node of a specific kind? For example, if I have a input element...
var node = A.one('input#_new_WAR_localizededitorportlet_test1');
I want to get its enclosing form. I know how to get the parent node:
var parent = node.get('parentNode');
but not how to (elegantly) go through the tree until reaching the form. For now I am using this
while (node.get('tagName').toLowerCase() != 'form') {
node = node.get('parentNode');
}
but it is not a really succinct way of doing it.
Is there a better way of doing it?
A:
Just use the ancestor() method:
node.ancestor('form')
|
[
"tex.stackexchange",
"0000523260.txt"
] | Q:
Shortauthor and authoryear-icomp: Use full author name for first citation like apa style
I am using the authoryear-icomp biblatex style. For some publications by institutions with long names, I would like to use shortauthor. However, the style authoryear-icomp simply uses shortauthor from the first citation onwards, like so:
I would like it to work as it does in style=apa, which uses the full author name for the first citation and introduces the short name in square brackets, which it then uses for all further citations (even for other publications of the same author).
This is the output if I change the style to apa:
Is there any way to achieve this behaviour with authoryear-icomp?
This is the MWE:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage[style=authoryear-icomp, % alternatively: style=apa
bibstyle=authoryear,
autocite=inline,
backend=biber
]
{biblatex}
\usepackage{filecontents}
\begin{filecontents*}{testbib.bib}
@online{test1,
author = {{Institution Long Name}},
shortauthor = {ILN},
title = {Test title},
year = {2020}
}
@online{test2,
author = {{Institution Long Name}},
shortauthor = {ILN},
title = {Another test title},
year = {2020}
}
\end{filecontents*}
\addbibresource{testbib.bib}
\begin{document}
Citation number one \autocite{test1}.
Citation number two \autocite{test1}.
Third citation with a different publication by the same author \autocite{test2}.
\end{document}
A:
You can do something like this - I took some code from APA style. You may need to make this more in line with cite from the authoryear-icomp style for more general use but this gets you what you want as a start:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage[style=authoryear-icomp, % alternatively: style=apa
bibstyle=authoryear,
autocite=inline,
backend=biber
]
{biblatex}
\usepackage{filecontents}
\begin{filecontents*}{testbib.bib}
@online{test1,
author = {{Institution Long Name}},
shortauthor = {ILN},
title = {Test title},
year = {2020}
}
@online{test2,
author = {{Institution Long Name}},
shortauthor = {ILN},
title = {Another test title},
year = {2020}
}
\end{filecontents*}
\addbibresource{testbib.bib}
\makeatletter
\DeclareCiteCommand{\parencite}[\mkbibparens]
{\usebibmacro{cite:init}%
\usebibmacro{prenote}}
{\usebibmacro{citeindex}%
\usebibmacro{metacite}%
\usebibmacro{cite:post}}
{}
{\usebibmacro{cite:postnote}}
\newbibmacro*{cite:post}{%
\xifinlist{\thefield{fullhash}}{\cbx@names}
{}
{\listxadd{\cbx@names}{\thefield{fullhash}}}}
\global\let\cbx@names\@empty
\def\cbx@ifnamesaved{%
\xifinlist{\thefield{fullhash}}{\cbx@names}
{\@firstoftwo}
{\@secondoftwo}}
\newbibmacro*{metacite}{%
\ifnameundef{shortauthor}
{\usebibmacro{cite}}
{\usebibmacro{sacite}}}
\newbibmacro*{sacite}{%
\cbx@ifnamesaved
{\printnames{shortauthor}}
{\printnames{author}%
\addspace\mkbibbrackets{\printnames[sabrackets]{shortauthor}}}%
\setunit{\printdelim{nameyeardelim}}%
\usebibmacro{cite:labeldate+extradate}%
\savefield{namehash}{\cbx@lasthash}%
\savefield{labelyear}{\cbx@lastyear}%
\setunit{\multicitedelim}}
\makeatother
\begin{document}
Citation number one \autocite{test1}.
Citation number two \autocite{test1}.
Third citation with a different publication by the same author \autocite{test2}.
\end{document}
|
[
"stackoverflow",
"0028652276.txt"
] | Q:
Group data into time dependent sets using numpy
Given a 2D set of data [Time, Value] I'd like to split it into like groups but in time ordered chunks. I am using both numpy and pandas already so a method for either is great.
Original:
Foo = np.array([[0,A],[1,A],[2,A],[3,B],[4,B]
[5,A],[6,A],[7,B],[8,B],[9,B],[10,A]....]])
Split into:
bar = np.array([[0,A],[1,A],[2,A]])
baz = np.array([[3,B],[4,B]])
qux = np.array([[5,A],[6,A]])
arr = np.array([[7,B],[8,B],[9,B]])
wiz = np.array([[10,A],......]])
A:
Assuming that you mean for A and B to be values, you can just use itertools.groupby if it's the case that your grouping logic is to place contiguous sequences of each value into different groups.
Concretely (including fixing a bracket and comma error in your example code, and adding some dummy values for A and B):
A = 1.0
B = 2.0
Foo = np.array([[0,A],[1,A],[2,A],[3,B],[4,B],
[5,A],[6,A],[7,B],[8,B],[9,B],[10,A]])
from itertools import groupby
groups = [np.array(list(v)) for k,v in groupby(Foo, lambda x: x[1])]
Now what you call bar will be groups[0], and so on. If you want to give them names automatically, it's advisable not to try to do this at the top level with some kind of locals() or globals() trickery, but instead just list out the names and use a dict:
names = ['bar', 'baz', 'qux', 'arr', 'wiz']
named_groups = {names[i]:groups[i] for i in range(len(groups))}
Now named_groups['bar'] returns what you used to just call bar.
Alternatively, if you can guarantee the precise number of groups, you can use tuple unpacking to name them all in one step like this:
(bar,
baz,
qux,
arr,
wiz) = [np.array(list(v)) for k,v in itertools.groupby(Foo, lambda x: x[1])]
(Note: I've never gotten a great answer about what PEP 8 might say about best practice for needing to have a lot of (possibly verbosely named) tuple elements to unpack on the left side of =)
This still lets you have the groups bound to top-level variable names, but rightfully forces you to be explicit about how many such variables there are, avoiding the bad practice of trying to dynamically assign variables on the fly.
|
[
"stackoverflow",
"0020328454.txt"
] | Q:
Need to print out details of the books if isOnLoan is false? Using setters getters
Boolean status = false;
for (int i = 0; i<SomeArray.length; i++) {
if(status == SomeArray[i].getisOnLoan()) {
System.out.print("\n" + SomeArray[i].toString());
}
}
I need to print out all the objects of array where isOnLoan is = to false but I have tried number of times and I keep getting null pointer exception etc. I even used status variable to compare the values to see if it was false but no one it is working
A:
Two potential causes of NullPointerException in your code snippet:
someArray is null
some cells from someArray are null.
Assuming someArray is not null, here's a solution (and cleaner):
for (int i = 0; i<someArray.length; i++)
if(someArray[i] != null && !someArray[i].isOnLoan()) //notice the check for nullity since your current cell could be null
System.out.println(someArray[i]);
And please follow the Java naming convention.
|
[
"stackoverflow",
"0043727405.txt"
] | Q:
How to navigate faster in react native on Android and Windows Device?
Here is the code in index.js:
render() {
return (
<Navigator initialRoute = {{
id: 'firstPage'
}}
renderScene={
this.navigatorRenderScene
} />
);
}
navigatorRenderScene(route, navigator) {
switch (route.id) {
case 'firstPage':
return(<FirstPage navigator={navigator} title="First Page"/>);
case 'secondPage':
return(<SecondPage navigator={navigator} title="Second Page"/>);
}
}
Inside firstPage.js
class FirstPage extends Component {
...
<TouchableHighlight onPress={() => this.onFirstButtonPress()}>
</TouchableHighlight>
onFirstButtonPress() {
this.props.navigator.push({
id:'secondPage'
})
}
...
}
Inside secondPage.js:
<TouchableHighlight onPress={ () => this.onSecondButtonPress() } > </TouchableHighlight>
onSecondButtonPress() {
this.props.navigator.pop();
}
My intend here is after click FirstButton on FirstPage, I navigate to SecondPage. After clicking SecondButton, I return to FirstPage.
My code works, but when I click on FirstButton, I see the first page slowly disappears, and the 2nd page slowly shows up, and there is 1 or 2 seconds, they overlap each other. Is there a way I can make a clear and quick switch between the two?
A:
The code looks fine to me. Can you check couple of things here, please :
1) You are running on Debug mode.(That boosts the performance)
2) See if you have not triggered Slow Animations in your simulator. Try clicking on Slow Animation from Debug->Slow Animation.
|
[
"stackoverflow",
"0014346190.txt"
] | Q:
Force constraint error in SQLite when using a rowid integer primary key
I have created a table using the following command:
CREATE TABLE Person (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL)
The problem I am having is that I can insert NULL for the id column despite the NOT NULL constraint. From what I understand, this is because the id column is now an alias for rowid.
If I change the data type of id to INT instead of INTEGER, the constraint works as I expect but I lose the rowid alias (and the benefits that come with it).
My question is: Is there a way to throw a constraint error when passing in NULL for a column that is an alias for rowid?
A:
It seems the short answer here is that there is no way to maintain the rowid alias while also preventing null insertions.
|
[
"stackoverflow",
"0003047722.txt"
] | Q:
Does window.open not work inside an AIR html component?
I have a component in AIR like so:
<mx:HTML
id="html"
width="100%"
height="100%"
location="https://example.com"
locationChange="dispatchLocationChange(event)"
/>
The page it loads contains this:
<a onclick="alert('onclick')">Alert</a>
<a href="javascript:alert('js')">Alert</a>
<a onclick="window.open('http://www.google.com','_blank')">new window</a>
The 2 alerts both work. however nothing happens when you click the new window link.
all 3 links works when in a real browser so I know its ok.
Is there just no support for window.open in the AIR HTML component? or is this a bug?
Is there a work around?
A:
I found out you need to extend the class HTMLHost and override the createWindow method like this:
override public function createWindow(windowCreateOptions:HTMLWindowCreateOptions):HTMLLoader
{
var window:Window = new Window();
window.open();
window.visible = true;
window.height = windowCreateOptions.height;
window.width = windowCreateOptions.width;
var htmlLoader:FlexHTMLLoader = new FlexHTMLLoader();
htmlLoader.width = window.width;
htmlLoader.height = window.height;
htmlLoader.htmlHost = new MyHTMLHost();
window.stage.addChild(htmlLoader);
return htmlLoader;
}
Then set this subclass as the htmlHost property for the HTML component.
This does get it to work. But there is some strange behavior in the new popup window. Seems kinda buggy.
|
[
"stackoverflow",
"0045530063.txt"
] | Q:
How can send link group without show info ? Bot Telegram
I send link public group to user.
When receive to user.show info the group.
How can send link group without show info ?
A:
If you are human, just wait preview before sending that, and click X to disable.
For bots, add disable_web_page_preview=true in parameter, you can find usage in API Doc.
|
[
"homebrew.stackexchange",
"0000012810.txt"
] | Q:
Belgian golden strong
I'm working in my first high gravity beer. Its been in primary for two weeks in the yeast cake. Looking for pointers on when to secondary.. How close to f.g. should I be before I transfer for the rest if the 6+ weeks..
A:
There is no reason to secondary that beer. Most homebrewers these days don't bother with secondary unless adding fruit or something else that will cause fermentation to restart. Here's what John Palmer, Jamil Zainisheff and others have to say...."Therefore I, and Jamil and White Labs and Wyeast Labs, do not recommend racking to a secondary fermenter for ANY ale, except when conducting an actual second fermentation, such as adding fruit or souring. Racking to prevent autolysis is not necessary, and therefore the risk of oxidation is completely avoidable. Even lagers do not require racking to a second fermenter before lagering. With the right pitching rate, using fresh healthy yeast, and proper aeration of the wort prior to pitching, the fermentation of the beer will be complete within 3-8 days (bigger = longer). This time period includes the secondary or conditioning phase of fermentation when the yeast clean up acetaldehyde and diacetyl. The real purpose of lagering a beer is to use the colder temperatures to encourage the yeast to flocculate and promote the precipitation and sedimentation of microparticles and haze.
So, the new rule of thumb: don’t rack a beer to a secondary, ever, unless you are going to conduct a secondary fermentation." https://www.homebrewersassociation.org/forum/index.php?topic=15108.msg191642#msg191642
|
[
"stackoverflow",
"0026005894.txt"
] | Q:
Generating unique solutions with Constraint Programming
I had a brief exposure to CP and MiniZinc but I'm no expert.
I have a CP model, which I cannot post here ATM, implemented in MiniZinc.
I need to generate all the feasible solution for the problem. We expect to have just a "few" ones, say less than 1000, more than 100.
I tried to solve the model with the -a flag passed to minizinc ver. 1.6 but I notice a lot of solutions being printed are identical.
Here they refer to "projection". In another paper I read they used some "backtracking mechanism".
It's still not clear to me.
My questions then are:
what is the best way to generate only unique solutions from a CP model?
Is there a standard mechanism implemented in CP libraries like SCIP or Gecode? Does it have a common name?
Is it computationally efficient?
does minizinc support that? How do I access that feature?
A:
Normally, CP systems give you just distinct solutions. I suspect that you have decision variables that are not printed (not in the output section) and you don't see that if these values are included in the solution it would be unique solutions.
In the question you linked to (this recent discussion), it is mentioned that Gecode's FlatZinc solver (at least the SVN version) now generates distinct solutions given a subset of decision variables in the output section. Other FlatZinc solver don't seem to have this feature.
If that doesn't answer your questions, please give more details of the model and example of the output (including the output section).
|
[
"stackoverflow",
"0012075987.txt"
] | Q:
How to increase function by 1 using loop in javascript
I want to run a loop that auto increase the function name by 1. For easier to understand:
My currently code:
for(var i = 1; i <= 2; i++) {
var fn = 'this.getExterior',
el = (fn + i + '()').getInnerItems();
}
I want to increase the function name and retrieve something like this.getExterior1 , this.getExterior2. The above code give me an object not a function. Can someone give me a solution how to achieve it. Thank you very much in advance!
A:
You can't really use strings as code (eval can but it's not necessary here). You can use the [] syntax:
el = this["getExterior" + i]().getInnerItems();
(Also, function is a keyword; you cannot use it as a variable name.)
|
Subsets and Splits