text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
What are the kind of variables that must be disposed? (.NET/Java)
Three questions:
What kind of variables should be disposed manually in .NET/Java? I know that SqlConnection should always be either disposed manually or used in a using{} block. Is it right? What are the other kind of variables that should be disposed?
I read somewhere that unmanaged code must be disposed manually. Is that right? What exactly is unmanaged code and how do I know if a variable is managed or unmanaged?
Finally, how do I dispose variables? I know that the Dispose() method does not really dispose a variable. So what does Dispose() do? Should I set them to null()? What is the logic by which the garbage collector works?
A:
This answer deals only with the .NET part of your question
What kind of variables should be disposed manually in .NET/Java? I know
that SqlConnection should always be
either disposed manually or used in a
using{} block. Is it right? What are
the other kind of variables that
should be disposed?
In .NET, all objects that implement IDisposable should be disposed explicitly (or used in a using block).
I read somewhere that unmanaged code must be disposed manually. Is
that right? What exactly is unmanaged
code and how do I know if a variable
is managed or unmanaged?
You probably mean unmanaged resources, as code can't be disposed... All classes that use unmanaged resources (memory allocated not on the managed heap, win32 handles...) should implement IDisposable, and should be disposed explictly, since they are not managed by the garbage collector.
Finally, how do I dispose variables? I know that the Dispose()
method does not really dispose a
variable. So what does Dispose() do?
Should I set them to null()? What is
the logic by which the garbage
collector works?
I'm not sure I understand your question... you don't dispose a variable, it is managed by the garbage collector. All managed memory is automatically released when it's not used anymore (i.e. it is not accessible by code because there are no references left to it). The IDisposable.Dispose method is only intended for resources that are not managed by the GC.
EDIT: as a side note, I would like to add that IDisposable is primarily intended to clean-up unmanaged resources, but is also frequently used to perform other cleanup actions and guarantee state or data integrity. For instance, IDbTransaction implements IDisposable in order to rollback the transaction if an exception occurs before the transaction was committed :
using (var trx = connection.BeginTransaction())
{
// Do some work in the transaction
...
// Commit
trx.Commit();
} // the transaction is implicitly rolled back when Dispose is called
A:
In Java, you "close" rather than "dispose".
JDBC Connections, unless you got them from a pool.
JDBC ResultSets, depending on the JDBC connector.
InputStreams, OutputStreams, Readers and Writers (with the exception of those that are byte array and string backed).
Some third-party Java libraries or frameworks have classes that need to be manually disposed / closed / destroyed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Knight returning to corner on chessboard -- average number of steps
Context: My friend gave me a problem at breakfast some time ago. It is supposed to have an easy, trick-involving solution. I can't figure it out.
Problem: Let there be a knight (horse) at a particular corner (0,0) on a 8x8 chessboard. The knight moves according to the usual rules (2 in one direction, 1 in the orthogonal one) and only legal moves are allowed (no wall tunnelling etc). The knight moves randomly (i.e. at a particular position, it generates a set of all possible and legal new positions, and picks one at random). What is the average number of steps after which the knight returns to its starting corner?
To sum up: A knight starts at (0,0). How many steps on average does it take to return back to (0,0) via a random (but only legal knight moves) walk.
My attempt: (disclaimer: I don't know much about Markov chains.)
The problem is a Markov chain. There are $8\times8 = 64$ possible states. There exist transition probabilities between the states that are easy to generate. I generated a $64 \times 64$ transition matrix $M_{ij}$ using a simple piece of code, as it seemed too big to do by hand.
The starting position is $v_i = (1,0,0,...) = \delta_{0i}$.
The probability that the knight as in the corner (state 0) after $n$ steps is
$$
P_{there}(n) = (M^n)_{0j} v_j \, .
$$
I also need to find the probability that the knight did not reach the state 0 in any of the previous $n-1$ steps. The probability that the knight is not in the corner after $m$ steps is $1-P_{there}(m)$.
Therefore the total probability that the knight is in the corner for the first time (disregarding the start) after $n$ steps is
$$
P(n) = \left ( \prod_{m=1}^{n-1} \left [ 1 - \sum_{j = 0}^{63} (M^m)_{0j} v_j \right ] \right ) \left ( \sum_{j = 0}^{63} (M^n)_{0j} v_j \right )
$$
To calculate the average number of steps to return, I evaluate
$$
\left < n \right >= \sum_{n = 1}^{\infty} n P(n) \, .
$$
My issue:
The approach I described should work. However, I had to use a computer due to the size of the matrices. Also, the $\left < n \right >$ seems to converge quite slowly. I got $\left < n \right > \approx 130.3$ numerically and my friend claims it's wrong. Furthermore, my solution is far from simple. Would you please have a look at it?
Thanks a lot!
-SSF
A:
Details of the method mentioned in @Batman's comment:
We can view each square on the chessboard as a vertex on a graph consisting of $64$ vertices, and two vertices are connected by an edge if and only if a knight can move from one square to another by a single legal move.
Since knight can move to any other squares starting from a random square, then the graph is connected (i.e. every pair of vertices is connected by a path).
Now given a vertex $i$ of the graph, let $d_i$ denote the degree of the vertex, which is number of edges connected to the vertex. This is equivalent to number of possible moves that a knight can make at that vertex (square on chessboard). Since the knight moves randomly, transition probabilities from $i$ to its neighbors is $1/d_i$.
Now since the chain is irreducible (since the graph is connected) the stationary distribution of the chain is unique. Let's call this distribution $\pi$. Now we claim the following:
Claim Let $\pi_j$ denote $j^\text{th}$ component of $\pi$. Then $\pi_j$ is proportional to $d_j$.
Proof Let $I$ be the fuction on vertices of the graph such that $I(i)=1$ if $i$ is a neighbor of $j$, and $I(i)=0$ otherwise. Then
$$
d_j=\sum_i I(i)=\sum_i d_i \cdot \frac{I(i)}{d_i} = \sum_i d_i p_{ij}
$$
where $p_{ij}$ is the transition probability from $i$ to $j$. Hence we have $dP=d$ where $P$ is the transition matrix of the chain, and $d=(d_1,\cdots,d_j,\cdots,d_{64})$. Thus $\pi P=\pi \implies$ Claim
Therefore, it follows that after normalising we have
$$
\pi_j=d_j/\sum_i d_i
$$
Finally we recall the following theorem
Theorem If the chain is irreducible and positive recurrent, then
$$
m_i=1/\pi_i
$$
Where $m_i$ is the mean return time of state $i$, and $\pi$ is the unique stationary distribution.
Thus if we call the corner vertex $1$, we have
$$
m_1=1/\pi_1
$$
You can check that $\sum_i d_i = 336$, and we have $d_1=2$ (at corner knight can make at most $2$ legal moves. Therefore $\pi_1=1/168$ and
$$
m_1=168
$$
A:
The first thing we do is find a stable distribution for the Markov process. We see that the process will be stable if the mass for each square of the chessboard is proportional to the number of knight moves leading away from it; then the process will move a mass of 1 along each possible knight move, so each square with n moves from it will have a mass of n moving in and a mass of n moving out, so everything balances.
Next, we want to find the total mass of the system. This is the total number of possible knight moves; there are 8 possible directions a knight can move, and each direction can start from a 6x7 square, so there will be 8*6*7 = 336 possible moves, and that is the total mass of the distribution.
Since a corner square has a mass of 2, that represents 2/336 = 1/168 of the mass of the distribution. Since we have a connected recurrent process, an infinite random walk from any square will be at that particular corner 1/168 of the time. That means the average time between visits to the corner will be 168.
| {
"pile_set_name": "StackExchange"
} |
Q:
conda build ignoring my activated environment?
I've created a Python 3 Conda environment, expressly for the purpose of testing whether a particular package could be built, targeting Python 3, as opposed to 2. However, when I launch a conda build from this environment, it appears to want to target Python 2.7:
(pybert_py3) Davids-MacBook-Air-2:PyBERT dbanas$ conda build conda.recipe/chaco/
BUILD START: chaco-4.6.1-py27_0
I can find nothing in the meta.yaml file, which is directing the build towards Python 2.7. Does anyone know what's going on, here, and how I direct this build at Python 3?
A:
Conda does not use your environment:
https://docs.conda.io/projects/conda-build/en/latest/concepts/recipe.html
Creates a build environment and installs the build dependencies there.
Therefore, you need to set the Python version explicitly:
--python PYTHON_VER Set the Python version used by conda build.
Try:
conda build --python=3.6 conda.recipe/chaco/
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use custom type with WCF data service and EF
I've created a WCF Data Service with a base class of my EF model.
I wanted to return a custom type (one that isn't in my EF model), but I get the error:
The server encountered an error processing the request. Please see the service help
page for constructing valid requests to the service.
My custom class looks like:
public class MyCustomClass
{
public string CustomProp { get; set; }
public List<int> Ids { get; set; }
}
How can I make this work?
A:
The only way I have found to do this with WCF Data Services is to pass a json string as a parameter and then deserialize it into the custom class.
Like so:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public bool ConfigurationChanged(string jsonStr)
{
try
{
MyObject obj = new JavaScriptSerializer().Deserialize<MyObject>(jsonStr);
// ... do something with MyObject
}
catch (Exception)
{
throw;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Best practice to creating View layer in MVP GWT
I red google-gwt article about MVP
and would like to ask about how you are creating the view layer.
Suppose you have three different "elements" on one view, the Tree, the Table and Text.
And now I think the best practice is to create these three elements decoupled
(I mean that, if I don't want Tree "element", in my view, I would comment the line, with for instance setTree(...) in code, somewhere).
Also I would like to use UIBinder for creating each of the "element"
So my questions are:
Who should be responsible for creating such decoupled element like Tree or Table (Controller, Presenter or may View)
and
Who is responsible for setting such elements to the View?
A:
The view should be responsible for assembling the widget components it needs. Your view class will be the one with a corresponding UiBinder file, and in that file you can combine a Tree, Table, and Label (or whatever).
| {
"pile_set_name": "StackExchange"
} |
Q:
Закрытие диалогового окна по условию
Есть кнопка ОК для некоторого диалогового окна (свойства у нее соответствующие - DialogResult == ОК и AcceptButton). В обработчике нажатия проверяются некоторые условия, и если они не выполняются - вызывается MessageBox и по идее управление возвращается к первому окну. Но оно по понятным причинам закрывается - оно же AcceptButton. Так вот, как в случае невыполнения условии оставить окно на месте?
A:
Если вы всё равно пишете обработчик события нажатия, то уберите значение из свойства DialogResult у кнопки и вручную выставляйте свойство формы, если вы хотите её закрыть.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I send long messages over long distances?
For communicating short messages (of 25 words or less) over long distances, we have the Sending spell. However, if I wanted to communicate, say, the contents of a 1-page letter (i.e. long enough that simply casting Sending multiple times isn't good enough) to someone far away (on the same plane, probably on the same continent, but many weeks away by land travel), is there a spell or other magic that can accomplish this? A solution might involve physically teleporting the letter itself, or simply conveying the message via some other means. Although sending the letter as a physical object would probably be preferable, unless you're expecting the recipient to be constantly prepared to take dictation at any time.
It can be assumed that the intended recipient is living in a city and not traveling around much, so for example a spell that sent the message to their place of residence rather than directly to them would be fine, as long as the message isn't so ephemeral that it appears and then disappears before they get home from their grocery shopping. It would also be acceptable if some reasonable amount of setup was required to create a "receiving station". I, on the other hand, am a busy adventurer constantly on the move, so an elaborate or non-portable setup on the sending end is probably not viable.
One obvious method of accomplishing this task is to use a 7th level spell slot to teleport to the recipient and deliver the message in person. So that puts a sort of upper limit on what should be required: a better method should be more efficient than teleporting there yourself.
Since this is pretty open-ended, you can impose reasonable additional constraints in your answer, such as requiring the recipient to also be a spellcaster. Just be clear about what your solution requires.
A:
A few 5th level options
One of the best options is the 5th level spell Dream. With this spell, you can converse with a person known to you while they sleep, as long as they are on the same plane of existence as you. If you aren't trying to damage or impair them with this spell, the spell automatically works. And best of all...
The target recalls the dream perfectly upon waking. [PHB, p.236]
If the recipient of the message you intend to send is in a location with a permanent teleportation circle, (such as an academy of magic or a major temple of a powerful religion), then you could also use the 5th level spell Teleportation Circle. It can transport "creatures". You could find a mouse, tie your message to it, and have an ally toss it through the portal that the spell opens (you couldn't toss it yourself, since you already took your action to cast the spell, and the portal only lasts one round).
With some specific subclasses, there may be other options as well. As an example, a Wizard of the School of Illusion could cast Magic Mouth on the wall of the room of a minion, who is given instructions to stand in front of it and say a specific phrase every day at an appointed time. The mouth could be programmed to appear and say "nothing to report" over and over for 10 minutes when the minion says its trigger phrase. Then, when the Wizard wants to contact the minion, they could cast the 5th level spell Scrying on the location, and thus see the mouth activate. The Wizard could use their "Malleable Illusion" ability:
Starting at 6th level, when you cast an illusion spell that has a duration of 1 minute or longer, you can use your action to change the nature of that illusion (using the spell’s normal parameters for the illusion), provided that you can see the illusion. [PHB, p. 118]
With this, the Wizard could change the message every round, and thus send a long message over the 10 minutes that Scrying last. Since Magic Mouth lasts until it is dispelled, this could be done every day (though it would take up a 5th level spell slot to Scry on the location, in order to "see the illusion").
A:
There are a few possibilities that come to mind here, some of which are more feasible than others.
Animal Messenger
Animal messenger lets you send an animal a long distance with a short message. A flying animal can travel about twice as fast as walking, and can go for one day plus two days per extra spell level.
Normally, you can only send 25 words with an animal messenger, but there's nothing saying that you can't tie a longer message to the animal, and then send it off that way. The recipient can get a 25 word message telling them to untie the message, and then a much longer message tied to the bird.
Telepathy
While telepathy is one level higher than teleport, it offers an unlimited and fail-safe method of communication with a known target. It has unlimited range and a 24 hour duration, so it can be used anywhere on the same plane for instantaneous communication.
Teleport
On possibility that is technically less costly than teleporting yourself and teleporting back is teleporting the message directly. Teleport can send "a single object" to the designated location, and if you take an object from your target area, you can send messages this way at will with no chance of failure.
A:
The Crystal Ball of Telepathy
All magical crystal balls allow you to use their powers to scry, but the crystal ball of telepathy additionally enables you to communicate telepathically with someone within 30ft of the scrying sensor that it creates.
As per the scrying spell, a subject who is happy to be magically spied on can voluntarily fail the save, and you can also arbitrarily scry upon a location if you've been there before, so it's a reliable way to communicate with allies on the same plane - and it offers a two-way conversation. It is, however, a legendary magical item, so is probably a very expensive solution to your problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create write and run your php code online
Give me solution for this issue. I want to create a site : write and run your php code online as same as this site : http://www.writephponline.com/ (have a textarea, button run & output area). Please help me (I really don't know where start) because I am newbie
.output {
background: #eee;
min-height:40px;
}
textarea {
width: 100%;
}
<textarea name="txtCode" rows="10"></textarea>
<br/>
<input type="submit" value="run" name="btnRun"/>
<br/>
<div class="output">
</div>
A:
Honestly to say, if you are a newbie you'd better shouldn't write software like this, because it will result in a big security whole online and your server will be hacked soon after you will launch your website.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sequential \frac that aren't nested
I'm new to Latex and am having trouble troubleshooting an equation that I can't get to display correctly. The equation I am trying to create in Latex is:
...but I keep getting nested fractions starting with the 3rd to last term so it appears like:
The code I am using is:
\begin{equation}
\centering
\frac{\partial UB}{\partial t}+\frac{\partial UUB }{\partial x}+\frac{\partial WUB}{\partial z}=gB\sin\alpha+g\cos\alpha B\frac{\partial \eta}{\partial x}-\frac{g\cos\alpha B}{\rho} \[\int_\eta^z \frac{\partial \rho}{\partial x}dz\]+\frac{1}{\rho}\frac{\partial B\tau_x_x}{\partial x}+\frac{1}{\rho}\frac{\partial B\tau_x_z}{\partial z}+qBU_x
\label{eqn:horizontalmomentum}
\end{equation}
I'm also getting a whole bunch of errors:
A:
You cannot use \[ ... \] inside a math expression. USe
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{align}\label{eqn:horizontalmomentum}
\begin{aligned}
\frac{\partial UB}{\partial t}+\frac{\partial UUB }{\partial x}
+\frac{\partial WUB}{\partial z} & = gB\sin\alpha
+g\cos\alpha B\frac{\partial \eta}{\partial x}
-\frac{g\cos\alpha B}{\rho} \int_\eta^z \frac{\partial \rho}{\partial x}dz \\
&
+\frac{1}{\rho}\frac{\partial B{\tau_x}_x}{\partial x}
+\frac{1}{\rho}\frac{\partial B{\tau_x}_z}{\partial z}+qBU_x
\end{aligned}
\end{align}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to parameterize table and column names in SQLite queries?
Im trying to perform a parameterized query in SQLite from C#, and the method im using is along the lines of creating a static command with
SQLiteCommand cmd = new SQLiteCommand(
"SELECT [ID]" +
",[email]" +
",[serializedata]" +
",[restrictions]" +
" FROM " + UserTable +
" WHERE @search = @searchparam", SQLConnection);
cmd.Parameters.Add(new SQLiteParameter("@searchparam"));
cmd.Parameters.Add(new SQLiteParameter("@search"));
and calling it like this:
Command.Parameters["@searchparam"].Value = searchdata;
Command.Parameters["@search"].Value = search;
SQLiteDataAdapter slda = new SQLiteDataAdapter(UserSelectUsernameCommand);
DataSet ds = new DataSet();
slda.Fill(ds);
User[] array = new User[ds.Tables[0].Rows.Count];
int index = 0;
foreach (DataRow row in ds.Tables[0].Rows)
{
array[index] = new User(this, row);
index++;
}
return array;
but im getting an error along the line of " '@search' is not a correct column name " or something like that. if i use a constant column name, and only use the data for parameters it works, but i dont want to create 10 different commands for when i need to search by different column names.
What is the issue here?
A:
Generally things like column names (or table names) can not be parameterised - and the fact that there are different indices means that it will have to be a different plan internally. So you will have to use concatenation - but be careful to white-list the known column names to prevent sql injection:
SQLiteCommand cmd = new SQLiteCommand(@"
SELECT [ID],[email],[serializedata],[restrictions]
FROM " + whiteListedUserTable + @"
WHERE [" + whiteListedColumnName + @"] = @searchparam", SQLConnection);
cmd.Parameters.Add(new SQLiteParameter("@searchparam"));
...
Command.Parameters["@searchparam"].Value = searchdata;
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ reading user inputs comparing array
I have this code where it read user code and store it on array, and later find sums of elements on each array and compare both of them, the code is as follows:
#include <iostream>
#include <vector>
#include <numeric>
typedef std::vector<int> int_vec_t;
//Call by reference to set variables in function
void readData(int_vec_t& v1, int_vec_t& v2)
{
v1 = int_vec_t{1,1,8}; //This only works for C++11
v2 = int_vec_t{2,2,2};
}
void readUserData(int_vec_t& v)
{
for(;;)
{
int val;
std::cin>>val;
if(val == 0) break;
v.push_back(val);
}
}
int main()
{
using namespace std;
int_vec_t A;
int_vec_t B;
readData(A,B);
//Or
readUserData(A);
readUserData(B);
int sumA = accumulate(A.begin(), A.end(), 0); //Then use iterators
int sumB = accumulate(B.begin(), B.end(), 0);
cout << ((sumA > sumB) ? "Array A Greater Than Array B\n" : "Array B Greater Than Array A\n");
return 0;
}
But the above code generate following errors:
test.cpp: In function ‘void readData(int_vec_t&, int_vec_t&)’:
I am using g++ test.cpp -o test to compile the code. What am I missing here?
A:
don't you think the compilation should be something like:
$ g++ -std=c++11 test.cpp -o test ?
it keep taking inputs, how can i limit it to take only 5 elements per array
void readUserData(int_vec_t& v)
{
for(int i = 0; i < 5; i++)
{
int val;
std::cin>>val;
// if(val == 0) return;
v.push_back(val);
}
}
Great thanks, in between the loop how can out put statement so that user knows he is entering array for array 1 and after that array 2?
void readUserData(int_vec_t& v, std::string default = "")
{
for(int i = 0; i < 5; i++)
{
int val;
std::cout << "Enter for "<< default << "[" << i << "]: ";
std::cin>>val;
// if(val == 0) return;
v.push_back(val);
}
}
And from your main() you can send in a different string.
for example like this:
readUserData(A, "A");
readUserData(B, "B");
| {
"pile_set_name": "StackExchange"
} |
Q:
Restrict access to some pages with a password [JSP/Servlet]
I'm developping a little website for school with JSP and servlets, but i'm having a problem.
I'm trying to restrict the access to the toolbox page, so only someone with the admin password could access to it.
So i put a little form (with post method) to get the password, and in my servlet i get it and check if it's the good one. But it seems like it always consider it's a wrong password and always redirect me to the wrong page ...
Content of my FiltreAdmin servlet :
public class FiltreAdmin extends HttpServlet {
public static final String VUE = "/WEB-INF/filtreAdmin.jsp";
public static final String ACCES_PUBLIC = "/restreintAdmin.jsp";
public static final String ACCES_RESTREINT = "/WEB-INF/toolbox.jsp";
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );
}
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
if ( request.getAttribute("passwd") != "freebeer" ) {
/* Redirection vers la page publique */
response.sendRedirect( request.getContextPath() + ACCES_PUBLIC );
} else {
/* Affichage de la page restreinte */
this.getServletContext().getRequestDispatcher( ACCES_RESTREINT ).forward( request, response );
}
}
}
Would someone have an idea ?
A:
Forgot to edit to post the answer .. My bad !
I found the solution thanks to the link of home (How do I compare strings in Java?)
I just needed to change my == and use the .equals() function instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
OpenCV Android: Define and save ROI in new Mat
I am trying to slice (crop) part of my image to another so it can be worked on separately. I have found contours and now trying to save every contour in new Mat but it is giving error
Mat crop;
Imgproc.findContours(m, contours, new Mat() ,Imgproc.RETR_EXTERNAL , Imgproc.CHAIN_APPROX_SIMPLE);
for(int i=0; i <contours.size();i++)
{
Rect rect = Imgproc.boundingRect(contours.get(i));
crop = m.submat(rect);
}
Utils.matToBitmap(crop, bm);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(bm);
Here m is my Mat where image is saved
Error:
A:
What I always do in this situation is to create a new mat using the constructor with a rect:
Mat cropped = new Mat(mOriginal, boudingRect);
Edit:
Your bitmap should also have the same size:
bm = Bitmap.createBitmap(crop.size().width,crop.size().height, Bitmap.Config.ARGB_8888);
| {
"pile_set_name": "StackExchange"
} |
Q:
Applications of Sard's Theorem.
I am writing my Bachelors Thesis about Sard's Theorem and I was asking myself if there are any good applications of it or the direct consequences (Whitneys Embedding and Morse functions) in physics or geometric analysis for example. I found only one example from electrostatics online, some hints would be appriciated!
A:
There are more applications in differential topology than the ones you mention. Two main ones are the approximation theorems (of Whitney too), which you can see for example in [Introduction to Smooth Manifolds, John.M.Lee] or the Brouwer fixed point theorem, which you can see very short and nicely in [Topology from the Differential Viewpoint, John.W.Milnor].
There is also a nice topology differentiable theory called "degree theory" which studies the zeroes of continuous functions. The building of this theory widely uses the Sard theorem in order to prove several properties of an application called "degree". If you are interested, you can have a look at [Mapping Degree Theory, Enrique Outerelo, Jesús M. Ruiz]. With a quick search of the word "Sard" you can find plenty of applications. This theory also admits a generalization to Banach spaces, which might be something you are looking for, since this has many applications to EDP's. However, I do not know yet any good reference for this...
Sorry, I do not know about any more specific applications in physics, but I hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
'User' object has no attribute '__getitem__' error
I have the following model:
class StudentUsername(models.Model):
user = models.OneToOneField(User)
student = models.ForeignKey(Student)
When I try to add a user and student to this table using default Django Admin interface, I get the following error:
Exception Type: TypeError
Exception Value: 'User' object has no attribute '__getitem__'
Kindly help.
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
432. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
198. return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
25. return func(self, *args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\db\transaction.py" in inner
371. return func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in add_view
1133. self.log_addition(request, new_object)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in log_addition
600. action_flag=ADDITION
File "C:\Python27\lib\site-packages\django\contrib\admin\models.py" in log_action
19. e = self.model(None, None, user_id, content_type_id, smart_text(object_id), object_repr[:200], action_flag, change_message)
Exception Type: TypeError at /backoffice/students/studentusername/add/
Exception Value: 'User' object has no attribute '__getitem__'
A:
It seems likely that you have defined a __unicode__ method on StudentUsername that is returning either a User or a Student object - that is, self.user or self.student - rather than actual unicode. So when Django tries to slice it, it gets this error.
Ensure that your unicode method actually returns unicode text.
| {
"pile_set_name": "StackExchange"
} |
Q:
Positive operator is bounded
For a real Banach space $X$ let $A:X\rightarrow X^*$ be a positive operator in the sense that $(Ax)(x)\geq 0$ for all $x\in X$. Show that $A$ is bounded.
I don't know how to do that, maybe it's an application of the closed graph theorem?
A:
It's indeed an application of closed graph theorem. First, we take $\{x_n\}\subset X$ a sequence which converges to $x$ and such that $Ax_n\to l$, where $l\in X^*$. As the sequence $\{x_n\}$ is bounded, we have $\langle T(x_n),x_n\rangle\to l(x)$. For $y\in X$, we have
$$0\leq \langle Tx_n-Ty,x_n-y\rangle=\langle Tx_n,x_n\rangle-\langle Ty,x_n\rangle-\langle Tx_n,y\rangle+\langle Ty,y\rangle.$$
Taking the limit $\lim_{n\to +\infty}$, we get
$$0\leq l(x)-\langle T(y),x\rangle-l(y)+\langle T(y),y\rangle,$$
which gives
$$l(y-x)\leq \langle T(y),y-x\rangle.$$
Let $y=z+x$. Then
$$l(z)\leq \langle Tz,z\rangle+\langle T(x),z\rangle.$$
Replacing $z$ by $az$, where $0<a$ and taking $a\to 0$, we get $l(z)\leq \langle T(x),z\rangle$. Replacing $z$ by $-z$, we get $l=Tx$.
As $X$ and $X^*$ are Banach spaces, we conclude by closed graph theorem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditionally set Angular's ng-class based on state
I would like to conditionally set the class of an element based on the application state (using AngularUI Router). I've tried this, but it is not working:
<li ng-class="{active: $state.current.name === 'state1'}">State 1</li>
<li ng-class="{active: $state.current.name === 'state2'}">State 2</li>
Any ideas?
A:
You could also use the ui-sref-active directive.
to add the class active to your element when the ui-router state matches use
ui-sref-active="active"
see: http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref-active
A:
The reason it didn't work was because, as @charlietfl pointed out, $state was not in scope. So I added the following to my state's controller:
$rootScope.$state = $state;
and it worked great. This plunker is a working example.
A:
You can do something like this:
<li ng-class="{active: $state.includes('state1')}">State 1</li>
<li ng-class="{active: $state.includes('state2')}">State 2</li>
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic form doesn't work in table
I have dynamic form,..I use this to populate other select option and it works
$(document).ready(function() {
$("#itemRows").on("change", ".jenis", function() {
var id = $(this).val();
var dataString = 'jenis=' + id;
var par = $(this);
$.ajax({
type: "POST",
url: "ajax_menu.php",
data: dataString,
cache: false,
success: function (html) {
par.siblings(".bahan").html(html);
}
});
});
});
demo dynamic form fiddle
if I use this in html, it will works fine:
<div id="itemRows">
<select name="jenis" class="jenis">
<option selected="selected">--Jenis Makanan--</option>
<option value="1">Makanan Pokok</option>
<option value="2">Daging Telur</option>
<option value="3">Buah</option>
<option value="4">Seafood</option>
<option value="5">Bijian</option>
<option value="6">Sayuran</option>
<option value="7">Susu Minyak</option>
</select>
<select name="bahan" class="bahan">
<option selected="selected">--Pilih Bahan--</option>
</select>
</div>
But if I use this in my html,.. it doesn't work
<table class="table table-striped" id="itemRows" cellpadding="3">
<tbody>
<tr>
<th scope="col">No.</th>
<th scope="col">Jenis</th>
<th scope="col">Nama Bahan</th>
<th scope="col">
<input onclick="addRow(this.form);" type="button" value="Add row">
</th>
</tr>
<tr class="1">
<td>1</td>
<td>
<select name="jenis" class="jenis">
<option selected="selected">--Jenis Makanan--</option>
<option value="1">Makanan Pokok</option>
<option value="2">Daging Telur</option>
<option value="3">Buah</option>
<option value="4">Seafood</option>
<option value="5">Bijian</option>
<option value="6">Sayuran</option>
<option value="7">Susu Minyak</option>
</select>
</td>
<td>
<select name="bahan" class="bahan">
<option selected="selected">--Pilih Bahan--</option>
</select>
</td>
<td>
<input type="button" value="Remove" onclick="removeRow(1);">
</td>
</tr>
</tbody>
</table>
any idea why it does't work?
A:
You need to change par.siblings(".bahan").html(html); to par.closest('tr').find(".bahan").html(html); because now they are not siblings
$(document).ready(function () {
$("#itemRows").on("change", ".jenis", function () {
var id = $(this).val();
var dataString = 'jenis=' + id;
var par = $(this);
$.ajax({
type: "POST",
url: "ajax_menu.php",
data: dataString,
cache: false,
success: function (html) {
par.closest('tr').find(".bahan").html(html);
//or par.closest('td').next().find(".bahan").html(html);
}
});
});
});
Demo: Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
SOLR MoreLikeThis + join query
I'm using SOLR MoreLikeThis feature to get similar documents based on the provided DocumentID. Would it be possible somehow specify to remove documents that don't have some attribute as provided DocumentID?
For example: document has id, location, ...
query would be: return me documents similar to doc_id and having same location?
Thank for help!
A:
One way of doing this would be using join query in fq and it works for MLT as well.
Something like:
&fq=(!join from=location to=location)DocumentID:1234
| {
"pile_set_name": "StackExchange"
} |
Q:
How to download files from URL to VMware ESXi using SSH Shell of it?
My Internet is slow relatively, so I need to download Ubuntu Server (ISO file) to my directory of VMware ESXi directly via ssh shell.
How can I do it?
A:
To enable SSH access in the direct console
At the direct console of the ESXi host, press F2 and provide credentials when prompted
Scroll to Troubleshooting Options and press Enter
Choose Enable SSH and press Enter once. On the left, Enable SSH changes to Disable SSH. On the right, SSH is Disabled changes to SSH is Enabled.
Press Esc until you return to the main direct console screen.
After this you can use wget read man wget:
Connect to your ESXi via SSH
Change to the folder where you want to download the ISO
Run wget http://releases.ubuntu.com/16.04.1/ubuntu-16.04.1-server-amd64.iso
This will download the ISO directly.
Setting up an ISO store on your ESXi server:
Go to configuration > storage
Right-click on a datastore and select Browse
Created an ISO folder
Use SSH to mv the downloaded ISO to the new folder
| {
"pile_set_name": "StackExchange"
} |
Q:
Tolman-Bondi-Lemaitre space times
One can see this reference for TBL space-times.
I would like to know how the explicit expression for the function called $G$ in equations $3.108,3.108,3.110$ in the above reference is obtained.
Also it would be nice to see some further references about TBL space-times.
A:
It actually just comes from integration. Equation 3.106 from that book is
$$ \dot R^2 = \left( - \frac{\partial R}{\partial t} \right)^2 = \frac FR + f $$
rearranging the terms gives (note that $\dot R < 0$)
$$ dt = - \frac{dR}{\sqrt{\frac FR + f}} $$
Now perform the substitution $z = fR/F$, giving
$$ dt = -\frac F{f^{3/2}} \frac{dz}{\sqrt{1+\frac1z}}. $$
Integrating gives
$$ t - t_0 = \frac F{f^{3/2}} \left( \sinh^{-1}\sqrt z - \sqrt{z(z+1)}\right) $$
the rest is just algebra.
I am no expert on general relativity, but the common term of that TBL spacetime seems start with "Lemaitre-Tolman". There is a review article on arXiv[1] which might help.
[1]: Kari Enqvist (2008). Lemaitre–Tolman–Bondi model and accelerating expansion. General Relativity and Gravitation 40, 2–3, pp 451–466. DOI: 10.1007/s10714-007-0553-9.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery: Saving a form with jQuery turns the form invalid
I'd like to save a form containing an image.
Without jQuery the form saves as intended, however, adding below "js-product_image-create-form" function creates an invalid form, but, at the same time, json respond status is: <JsonResponse status_code=200, "application/json">
The form is invalid in the View (prints "invalid" below) and in "invalid" in jQuery.
However,
removing the class="js-product_image-create-form", visually I get json with a valid form = True as well as the function prints "valid"
Why is the form valid in one case but invalid in the other case?
Using Django View:
def save_product_image_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
form.save()
data['form_is_valid'] = True
print("valid")
product_image = ProductImage.objects.all()
data['html_product_image_list'] = render_to_string('product_image/includes/partial_product_image_list.html', {
'product_image': product_image
})
else:
data['form_is_valid'] = False
print("invalid")
context = {'form': form}
data['html_form'] = render_to_string(
template_name, context, request=request)
return JsonResponse(data)
def product_image_create(request):
if request.method == 'POST':
form = ProductImageForm(request.POST, request.FILES)
else:
form = ProductImageForm()
return save_product_image_form(request, form, 'product_image/includes/partial_product_image_create.html')
$(function() {
var saveForm = function() {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function(data) {
if (data.form_is_valid) {
alert("I am valid");
$("#product_image-table tbody").html(data.html_product_image_list);
$("#modal-product_image").modal("hide");
} else {
alert("I am invalid !");
$("#modal-product_image .modal-content").html(data.html_form);
}
}
});
return false;
};
$("#modal-product_image").on("submit", ".js-product_image-create-form", saveForm);
});
{% load crispy_forms_tags %}
<form method="post" action="{% url 'image_create' %}" class="js-product_image-create-form"
enctype="multipart/form-data">
{% csrf_token %}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Add a new Product Image</h4>
</div>
<div class="modal-body">
{% crispy form %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-secondary">Add Product Image</button>
</div>
</form>
A:
IIRC, binary data (such as images) needs to be sent as multipart form data. If you want to send it as json, you'll have to base64 encode the image before sending it to the server, then decode the image on the server and save it using the storages api.
It works when you remove the class because jQuery is no longer controlling the form, and the data is instead sent synchronously to your {% url 'image_create' %} url using multipart (see your action= and enctype= html form attributes).
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding WHERE clause if record exists
I'm working on a query wherein I have three tables to join, however the third table may or may not have a relevant record.
I currently have:
SELECT table1.val, table2.val, table.3.val
FROM
table1
LEFT JOIN table2
ON table1.val = table2.val
LEFT JOIN table3
ON table.3.val = table2.val
WHERE
table1.name = "name"
AND table3.name = 'certain name'
ORDER BY table1.val ASC
How can I write this so that if 'certain name' doesn't exist in table3, that portion is omitted from the WHERE and SELECT clauses? I'm actually selecting several more fields but this should adequately demonstrate the problem.
A:
If you mean that result form table3 should only be visible, if the table3.val is equal to the table2.val AND that the table3.name should equal 'certain name', then this will fit you:
SELECT table1.val, table2.val, table.3.val
FROM table1
LEFT JOIN table2
ON table1.val = table2.val
LEFT JOIN table3
ON table.3.val = table2.val AND table3.name = 'certain name'
WHERE table1.name = "name"
ORDER BY table1.val ASC
After all, this is what LEFT JOIN is for...
| {
"pile_set_name": "StackExchange"
} |
Q:
Programmatically finding solutions to OEIS A001839
Okay, so here is an integer sequence. Over at the math stackexchange, I learned what this sequence means. Basically:
Given n item, a(n) is the number of groups of three you can create where no two groups have more than one item in common.
So if you have 7 items, represented by the letters a-g, you can make these seven groups:
1. abc
2. ade
3. afg
4. bdf
5. beg
6. cdg
7. cef
'a' and 'b' only show up once together, same with 'a' and 'c', and every other pair.
I'm trying to write a little program that can give me these trios for any number. Right now it works with a string that is n characters long. Here's what I have. I think it explains itself pretty well.
var str = 'abcdefg';
var userPairs = [];
var found = 0
var x;
var y;
var z;
$('.bundles').append(str.length+'<br>');
for (x = 0; x < str.length; x += 1) {
for (y = 0; y < str.length; y += 1) {
for (z = 0; z < str.length; z += 1) {
var possible = str[x]+str[y]+str[z];
if (!tooSimilar(possible)) {
found += 1;
$('.bundles').append(found + ') ');
$('.bundles').append(possible+'<br>');
userPairs.push(str[x]+str[y]);
userPairs.push(str[y]+str[z]);
userPairs.push(str[x]+str[z]);
}
}
}
}
function tooSimilar(possible) {
if (possible[0] === possible[1] ||
possible[1] === possible[2] ||
possible[2] === possible[0]) {
console.log('repeated char');
return true;
} else if (userPairs.indexOf(possible[0]+possible[1]) !== -1 ||
userPairs.indexOf(possible[1]+possible[0]) !== -1 ||
userPairs.indexOf(possible[1]+possible[2]) !== -1 ||
userPairs.indexOf(possible[2]+possible[1]) !== -1 ||
userPairs.indexOf(possible[0]+possible[2]) !== -1 ||
userPairs.indexOf(possible[2]+possible[0]) !== -1){
console.log('repeated pair');
return true;
} else {
console.log('FOUND ONE');
return false;
}
}
You can see the functioning JSFiddle here.
It works for seven characters or less, giving the number of trios you'd expect from the sequence. But more than seven it breaks down.
The list of trios it outputs always fits the criteria, but it seems to be missing some and I have no idea where.
A:
You are doing a greedy search, while finding the maximum might require some form of backtracking. An alternate way to think of it, you are looking for a maximal independent set in a graph where the trios are the vertices and two trios have an edge in common iff they share two letters. Not saying that this is a good way to model things, but you see how you'd find an independent set which cannot be extended, but which is still not globally maximal.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is Data Remanence a Myth?
Possible Duplicate:
Why is writing zeros (or random data) over a hard drive multiple times better than just doing it once?
Multiple overwrites have often been discussed as a secure way of erasing data. Some people say that the only way to securely erase a magnetic HDD is to physically destroy the device, grinding each platter to powder, incineration etc.
If I ask the question whether a single overwrite makes data permanently irretrievable, I get different answers. Some people say that it was an issue on older hardware, others that it still is. I have not come across a case where a single overwrite of zeros has been recovered, despite many people theorising that this could be done using techniques such as magnetic force microscopy.
It seems that in general people err on the side of caution under the assumption that one of the mysterious government entities has some crazy eletron-microscope equipment capable of recovering data after single, or even multiple overwrites.
While this is clearly the sensible option as it doesn't take a great deal of time to shred a disk this way, the question remains; is it necessary?
A:
The best citation I can give is from Overwriting Hard Drive Data: The Great Wiping Controversy, which was published as part of the 4th International Conference on Information Systems Security, ICISS 2008. You can view the full text of the paper by viewing the book on Google Books, and jumping to page 243.
The following excerpt is from their conclusion:
The purpose of this paper was a categorical settlement to the controversy surrounding the misconceptions involving the belief that data can be recovered following a wipe procedure. This study has demonstrated that correctly wiped data cannot reasonably retrieved even if it of a small size or found only over small parts of the hard drive. Not even with the use of a MFM or other known methods. The belief that a tool can be developed to retrieve gigabytes or terabytes of data of information from a wiped drive is in error.
Although there is a good chance of recovery for any individual bit from a drive, the chance of recovery of any amount of data from a drive using an electron microscope are negligible. Even speculating on the possible recovery of an old drive, there is no likelihood that any data would be recoverable from the drive. The forensic recovery of data using electron microscopy is infeasible. This was true both on old drives and has become more difficult over tine. Further, there is a need for the data to have been written and then wiped on a raw unused drive for there to be any hopy of any level of recovery even at the bit level, which does not reflect real situations. It is unlikely that a recovered drive will have not been used for a period of time and the interaction of defragmentation, file copies and general use that overwrites data areas negates any chance of data recovery. The fallacy that data can be forensically recovered using an electron microscope or related means needs to be put to rest.
NIST also seem to agree. In NIST SP 800-88, they state the following:
Studies have shown that most of today’s media can be effectively cleared by one overwrite.
Purging information is a media sanitization process that protects the confidentiality of information against a laboratory attack. For some media, clearing media would not suffice for purging. However, for ATA disk drives manufactured after 2001 (over 15 GB) the terms clearing and purging have converged.
As such, I'd say that data remanence on modern hard drives is a complete myth, and it's likely to be infeasible for old drives too.
So, as a quick set of bullet points:
You might be able to extract individual bits after a single overwrite, but not any useful amount of data.
It is entirely infeasible to recover any data, even at the bit level, from a wiped disk area outside lab conditions, due to the effects of day-to-day use (file copies, etc).
A single overwrite, for all intents and purposes, provides complete protection against useful data recovery.
A:
As usual, the Wikipedia page contains useful links (Wikipedia is not "The Truth" but it is a great starting point for investigating technical issues and making one's own mind). In particular, it says that:
As of November 2007, the United States Department of Defense considers overwriting acceptable for clearing magnetic media within the same security area/zone, but not as a sanitization method. Only degaussing or physical destruction is acceptable for the latter.
On the other hand, according to the 2006 NIST Special Publication 800-88 (p. 7): "Studies have shown that most of today’s media can be effectively cleared by one overwrite" and "for ATA disk drives manufactured after 2001 (over 15 GB) the terms clearing and purging have converged." An analysis by Wright et al. of recovery techniques, including magnetic force microscopy, also concludes that a single wipe is all that is required for modern drives. They point out that the long time required for multiple wipes "has created a situation where many organisations ignore the issue all together – resulting in data leaks and loss. "
So the generic conclusion seems to be that a simple overwrite will most probably erase all the data, but if you need some kind of compliance with regards to some bureaucratic regulations, then old-style physical obliteration may still be required. Note that, with regards to data cleansing, you have two needs:
you want to wipe the data out;
you want to be sure that the data has been thoroughly wiped out.
A sledgehammer or an acid cauldron will go a long way towards fulfilling the latter goal.
| {
"pile_set_name": "StackExchange"
} |
Q:
Use COPY to import a csv in a table with counters in Cassandra
I am trying to import a csv dump in my cassandra table using the copy command.
It works fine except for tables which contain counter column.
For these tables I get the following error message:
code=2200 [Invalid query] message="INSERT statement are not allowed on counter tables, use UPDATE instead"
Is there a workaround here? How can I bulk import the data from my csv file in my table?
Many thanks
A:
The documentation on the COPY command is pretty clear on this one:
You cannot copy data to or from counter tables.
As mentioned in this similar question(How can a CSV file with counter columns be loaded to a Cassandra CQL3 table), you can load tables with counter columns using the sstableloader.
There does not appear to be a ticket addressing this problem in the Cassandra JIRA project, either. You are welcome to create one, but there are some underlying issues that would make this difficult (basically, COPY TO also uses CQL and would also be subject to the restriction about setting a specific counter value vs. incrementing it).
EDIT 20180525
As of CASSANDRA-9043 tables with counter columns should now work with the COPY command.
| {
"pile_set_name": "StackExchange"
} |
Q:
git status reports modified files in a freshly cloned repo
Solved
It seems the remote repo contains two files named the same, except for the first letter. This caused a file overwrite on my system, which led to the issue below.
Update
It seems it has nothing to do with newlines, but I can't yet find an explanation. Here's what happens.
git status reports FileStartingWithCapitalLetter.php has been modified
On the other hand, browsing my case-insensitive file system, shows fileStartingWithCapitalLetter.php, which is actually starting with a lower-case "f".
git diff FileStartingWithCapitalLetter.php
shows this (the diff is hard to spot, it's the R in Redirect, which led me to think it has to do with CRLF):
diff --git a/test/functional/frontend/RedirectActionsTest.php b/test/functional/frontend/RedirectActionsTest.php
index 66e1fef..c574583 100644
--- a/test/functional/frontend/RedirectActionsTest.php
+++ b/test/functional/frontend/RedirectActionsTest.php
@@ -5,10 +5,10 @@ include(dirname(__FILE__).'/../../bootstrap/functional.php');
$browser = new sfTestFunctional(new sfBrowser());
$browser->
- get('/Redirect/index')->
+ get('/redirect/index')->
with('request')->begin()->
- isParameter('module', 'Redirect')->
+ isParameter('module', 'redirect')->
isParameter('action', 'index')->
end()->
On the other hand, git diff fileStartingWithCapitalLetter.php (lower-case f), shows no changes.
What's the fix to this?
Old issue
I've cloned a git repo and then, immediately, executed git status. It was not a surprise to see that it reports modified files, as it happened to me before. There are CRLF line endings committed from a Windows machine (I'm on OS X).
Now, what really surprised me is that this didn't work:
$ git config core.autocrlf false
$ rm .git/index
$ git reset
Unstaged changes after reset:
M test/functional/frontend/RedirectActionsTest.php
Does anyone have any ideas about what's wrong and how to solve it? I'm using Git 1.7.0.2.
A:
You could try to set this setting at the global level (Note: I also like having it set to false)
$ git config --global core.autocrlf false
and then clone again to see if this work better.
The other setting to watch out is: ignorecase true (also to set at the global level).
See this SO question as an example, and this one as an illustration of what can go wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
Merge Two package names in one
I have two standalone apps with different package names com.example.x and com.example.y
in the same account. I did that for a marketing purpose and now i want to merge them in one app also merge the two statistics of the two apps (installs, reviews,..etc).
How can i do that without losing users ?
A:
I'm afraid you can't , no body does that . you may update your application and put a message to your users that this version is no longer maintained and that they have to install the new version , you may also add a button that sends an intent to the play store app to redirect your users to the new version .
| {
"pile_set_name": "StackExchange"
} |
Q:
I couldn't understand how to make a k-fold cross validation test with multi-class SVM
i am very new to matlab and SVM and i am reproducing this experiment from strach http://bioinformatics.oxfordjournals.org/content/19/13/1656.full.pdf
*There they say "In the training of SVMs, we use the method of one versus
the others, or one versus the rest" . ok there are 12 classes so they produce 12 SVMs. they train each one with positives vs all rest.
*but then they say "The prediction performance was examined by the 5-fold cross-validation test"
My noob question is, How can they make a k-fold cross validation after! they train SVMs. what i think(likely faulty) is when you make a k-fold cross validation, you construct a new svm from beginning. they may be similar but svm model is different in every loop. there are k different svm models. but, if they train svm models beforehand, How can they make a cross validation test? What am i missing? Please help and thank you very much
A:
First they produce cross-validated datasets. Then they train 5 models (one for each fold) and repeatedly train-test. You can do this as follows:
% I assume use of LIBSVM for svm training-testing in this code snippet
% Create a random data
data=1+2*randn(1000,10);
labels=randi(12,[1000,1]);
%do 5-fold cross-validation
ind=crossvalind('Kfold',labels,5);
for i=1:5
% (4/5)^th random data for training
trainingData=data(ind~=5,:); %notice ~=
trainingLabels=labels(ind~=5);
% (1/5)^th random data for testing
testingData=data(ind==5,:); %notice ==
testingLabels=labels(ind==5);
% train svm
model{i,1}=svmtrain(trainingLabels,trainingData);
%test svm
[predLabels{i,1},accuracy(i,1)]=svmpredict(testingLabels,testingData,model{i,1});
end
% I think this is what they mean when they say, we analyze the performance
% using 5 -fold cross validation
% following two things is what you will report
plot(accuracy); %how accuracy varies over random selection of data
avgAccuracy=mean(accuracy); %what is the average accuracy over 5 runs?
| {
"pile_set_name": "StackExchange"
} |
Q:
In Scala, is there a way to represent price as $Y.YY?
At the moment, I'm thinking of representing price as follows:
case class Price(amount: Double)
Which allows me to do
val price = Price(4.52)
Is there any mechanism which would allow me to create a Price object as follows?
val price = $4.52
A:
No because $4 is a valid identifier and . signifies a method.
However you could say
val $ = Price
to set $ equal to the price companion object and parenthetize the Double:
scala> val p = $(4.52)
p: Price = Price(4.52)
edit: another thing you could do would be:
scala> implicit def toDollar(d: Double) = new {
| def $ = Price(d)
| }
toDollar: (d: Double)java.lang.Object{def $: Price}
scala> val p = 4.52 $
p: Price = Price(4.52)
| {
"pile_set_name": "StackExchange"
} |
Q:
Support of a function and the struggle...
The concept of support is very confusing to me, I'm just getting used to it.
Lets consider $\Omega\subseteq\Bbb R^n$ an open set, $C^1_c(\Omega):=\{f\in C^1(\Omega)\mid\operatorname{supp}(f)\text{ is compact and $\operatorname{supp}(f)\subset\Omega$}\}$.
Let $f\in C^1_c(\Omega)$, prove that: $\mathtt {(1)}$ $\frac{\partial f}{\partial x_i}\in C^0_c(\Omega)$ and that: $$\begin{array}{cc} \mathtt {(2)} &\int_{\Omega} \frac{\partial f}{\partial x_i}=0, & \forall \;i=1,\dots,n. \end{array}$$
$\mathtt {(1)}$ Because $f\in C^1(\Omega)$, then $\frac{\partial f}{\partial x_i}\in C^0(\Omega)$. Now we have to prove that $\operatorname{supp}(\frac{\partial f}{\partial x_i})$ is compact and $\operatorname{supp}(\frac{\partial f}{\partial x_i})\subset\Omega$. After a few tries, I thought showing that $\operatorname{supp}(\frac{\partial f}{\partial x_i})\subseteq\operatorname{supp}(f)$ was the way to prove this.
Lets assume there's a sequence $(x_n)_{n\in\Bbb N}\in \operatorname{supp}(\frac{\partial f}{\partial x_i})$ such that $(x_n)\to x_o$, where $x_o\not\in\operatorname{supp}(f)$, then $f(x_o)=0$. On the other hand, we also have that $x_o\in \operatorname{supp}(\frac{\partial f}{\partial x_i})$, then $\frac{\partial f}{\partial x_i}(x_o)\not=0$, but also $\frac{\partial f}{\partial x_i}(x_o)=0$, since $f(x_o)=0$, wich is a contradiction. Then it follows that $\operatorname{supp}(\frac{\partial f}{\partial x_i})\subseteq\operatorname{supp}(f)\subset \Omega$, hence $\operatorname{supp}(\frac{\partial f}{\partial x_i})$ is compact and $\operatorname{supp}(\frac{\partial f}{\partial x_i})\subset \Omega$.
(Is this correct?)
$\mathtt {(2)}$ Here I think we have to make induction on $n$. So let's see the base $n=1$, i.e., $\Omega \subseteq\Bbb R$ open. Let's define
$$F(x)=\begin{cases} f(x) & x\in\Omega \\ 0 & x\in \Bbb R\setminus\Omega \end{cases}$$
Where this function satisfies $F\in C^1_c(\Bbb R)$, if $f\in C^1_c(\Omega)$. In this case follows that $\frac{\partial f}{\partial x_i}\equiv\frac{df}{dx}=f'$. Also
$$F'(x)=\begin{cases} f'(x) & x\in\Omega \\ 0 & x\in \Bbb R\setminus\Omega \end{cases}$$
We defined $F$ because we know that $$\int _{\Omega}f:=\int_{\Bbb R^n} F$$
Then $$\int_{\Omega} \frac{\partial f}{\partial x}=\int_{\Omega} f'=\int_{\Bbb R^n} F'$$
I keep thinking Fundamental Theorem of Calculus, but it really doesn't help, and I don't see how this equals to zero!!!
A:
For a) if $f$ is 0 outside $C$, does it not follow that $\frac{\partial f}{\partial x_i}$ is also 0 outside of $C$, i.e. $\text{supp}\frac{\partial f}{\partial x_i} \subset \text{supp} \ f \subset \Omega$, $\forall i$? Since $\text{supp} \ f$ is compact and $\text{supp} \frac{\partial f}{\partial x_i}$ is closed, this gives you $\frac{\partial f}{\partial x_i} \in C^0_C(\Omega)$.
For b) think about how $\int_{\Omega} \frac{\partial f}{\partial x_i}$ and $\int_{\partial \Omega} f$ are related and how $f$ behaves on $\partial \Omega$ (since $\Omega$ is open, $\partial \Omega \cap \Omega = \emptyset$).
| {
"pile_set_name": "StackExchange"
} |
Q:
Should grub be removed before reinstalling Ubuntu?
I once installed Ubuntu alongside Windows 8. I then removed Ubuntu by formatting the partition. Ubuntu was gone but the grub remained. Should I remove grub before installing Ubuntu again?
A:
Simply do install, grub gonna be update with it.
After, if you install a new kernel or remove one directly from your system, you need to update grub manually with :
update-grub
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get selected input:radio
How come this works.
$('input:checked')
and this won't?
$('input').is(':checked')
Thanks.
A:
The second version should use .filter() instead of .is().
$('input').filter(':checked')
It seems like .is() should work since there's a .not() method. But .not() is actually the opposite of .filter().
| {
"pile_set_name": "StackExchange"
} |
Q:
Object constructed within reference initialization
Hopefully a simple question: Given a class
class Foo {
// some private data members
public :
Foo(int) {...};
}
What happens if an instance is constructed during reference initialization?
const Foo &f(Foo(1));
Does f now refer to a dead object - and if not, will the object get destructed correctly when f goes out of scope?
And, does anything change if we make the reference initialization use a expression?
const Foo &f( condition? Foo(1) : Foo(42));
A:
If an rvalue reference or a const reference is initialized with a prvalue of class type, the lifetime of the temporary object is extended to the lifetime of the reference. So no worries about dangling references.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is this really all I need to log a user in?
I was looking over some ASP.NET MVC 1 code (C#) in search of the mechanisms that the site was using to log in a user. This is what I found...
FormsAuthentication.SetAuthCookie(authenticatedUser.UserName, false);
followed by a redirect. Is it REALLY that simple?
I couldn't find any other code after the redirect that would be responsible for this.
A:
FormsAuthentication.SetAuthCookie creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication.
This will "log in a user" but you need to actually make sure the user exists somehow. You can use the built in membership providers which will by default target a SQL Express database in your App_Data folder called ASPNETDB.mdf.
If the default membership provider does not work for you then you can create a custom membership provider by inheriting from the base MembershipProvider class. If you don't want to do this then you can roll your own solution and still issue an authentication ticket, but at the very least you need to do something to actually make sure a user is who he says he is.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to log bandwidth usage on windows 8
My Father has a Verizon jet pack (hotspot card). He is seeing 100+ MB spikes on the Verizon data usage report a few times a day. On July 4th the verizon data usage report online shows 6 GB were used 3 times 6:02 am, 12:02 pm, and 6:02 pm. Over 18 GB in one day. He is a very light internet user. A few emails per day, no videos.
I am running tcpview on his computer to see how many MB each process is using. Over 4 days we are not seeing anything strange. TCPVIEW does not seem to agree with the verizon data usage report. TCPVIEW only shows total values. The verizon report gives totals at random times.
date time MB
07/17/2014 4:02 AM 123.95
07/17/2014 3:55 AM 0.07
07/17/2014 2:41 AM 0.70
07/17/2014 1:50 AM 0.36
07/17/2014 1:50 AM 0.18
07/16/2014 8:41 PM 65.92
07/16/2014 2:41 PM 59.24
07/16/2014 8:41 AM 117.84
07/16/2014 7:16 AM 32.51
07/16/2014 7:04 AM 0.00
07/15/2014 7:29 PM 5.17
07/15/2014 6:36 PM 5.17
07/15/2014 6:30 PM 0.06
07/15/2014 6:04 PM 1.62
07/15/2014 4:50 PM 47.70
07/15/2014 3:03 PM 2.48
07/15/2014 11:30 AM 78.56
07/15/2014 11:25 AM 0.23
07/15/2014 11:22 AM 2.29
07/15/2014 5:22 AM 107.32
What tool would you recommend to track down the details of these data usage spikes? He is using Windows 8. If you know of a way to stop these spikes, please tell me. His internet setup using a verizon jet pack (hot spot) needs to stay under 15 GB per month.
A:
As explained here you can use netbalancer to both monitor the usage on specific applications as well as log, and can limit total usage either system wide or for specific applications as well. Free version should be sufficient. Also, this would probably be better suited for the super user community, rather than the Sysadmin one.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pyodbc installation failed inside Virtualenvs(Pycharm)
Im trying to install pyodbc inside Virtualenvs within pycharm.
i have no problem when i use normal command prompt inside windows :
but when i use the install command inside the pycharm console it gives me this error :
My project also based on django template. this is default new project setting :
A:
In the project settings check on inherit global site-packages and restart the pycharm and then try to install the package.
| {
"pile_set_name": "StackExchange"
} |
Q:
Beginner at HTML5 Canvas, using layers?
I'm new to the HTML5 canvas, and I'm trying to use layers. I've looked for ways to implement them, but haven't had anything that helps what I'm trying to do. I am trying to make an animation of a volcano eruption. I want to put the volcano and background sky-blue color onto one layer, the lava falling from the sky onto a second layer, and the ash clouds on a third layer. I already had worked on this when I found out about layers, so I know things are out of place. My question though is am I on the right track when it comes to implementing the layers?
<body>
<div id="canvasesdiv" style="position:relative; width:400px; height:300px">
<canvas id="layer1" style="z-index: 1; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
<canvas id="layer2" style="z-index: 2; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
<canvas id="layer3" style="z-index: 3; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
</div>
</body>
<script>
//var canvas = document.getElementById("myCanvas");
//var context = canvas.getContext("2d");
var layer1;
var layer2;
var layer3;
var particles;
var eruption;
var timer;
var timerRestart;
function init(){
layer1 = document.getElementById("layer1");
ctx1 = layer1.getContext("2d");
layer2 = document.getElementById("layer2");
ctx2 = layer2.getContext("2d");
layer3 = document.getElementById("layer3");
ctx3 = layer3.getContext("2d");
}
function animationHandler(){
fillBackgroundColor(canvas, context);
drawVolcano();
drawClouds();
eruption = setTimeout(makeParticles, 10);
}
function drawClouds(){
ctx3.beginPath();
ctx3.moveTo(0, 100);
ctx3.bezierCurveTo(0, 100, 75, 200, 150, 100);
ctx3.bezierCurveTo(150, 100, 225, 200, 300, 85);
ctx3.bezierCurveTo(300, 85, 375, 200, 450, 75);
ctx3.bezierCurveTo(450, 75, 525, 200, 600, 100);
ctx3.bezierCurveTo(600, 100, 700, 200, 800, 100);
ctx3.lineTo(800, 0);
ctx3.lineTo(0, 0);
ctx3.closePath();
ctx3.fillStyle = "#6f2a2a";
ctx3.fill();
ctx3.lineWidth = 5;
ctx3.strokeStyle = "#371515";
ctx3.stroke();
}
function drawVolcano(){
ctx1.beginPath();
ctx1.moveTo(0, 400);
ctx1.bezierCurveTo(0, 400, 250, 400, 325, 200);
ctx1.lineTo(425, 200);
ctx1.bezierCurveTo(425, 200, 450, 400, 800, 400);
ctx1.lineTo(800, 500);
ctx1.lineTo(0, 500);
ctx1.closePath();
ctx1.fillStyle = "#802b00";
ctx1t.fill();
ctx1.lineWidth = 5;
ctx1.strokeStyle = "#b33c00";
ctx1.stroke();
}
function fillBackgroundColor(canvas, context){
ctx1.fillStyle = "#3399ff" ;
ctx1.fillRect(0, 0, canvas.width, canvas.height);
}
function makeParticles() {
//create an array of particles for our animation
particles = [];
for(var i = 0; i < 100; i++)
{
particles.push(new Particle());
}
}
function degreesToRadians(degrees) {
//converts from degrees to radians and returns
return (degrees * Math.PI)/180;
}
function Particle(){
//the constructor for a single particle, with random starting x+y, velocity, color, and radius
//this.x = Math.random()*canvas.width;
//this.y = Math.random()*canvas.height;
this.x = canvas.width/2;
this.y = (0,0);
this.vx = Math.random()*16-8;
this.vy = Math.random()*10;
var colors = ["red", "#ff6600", "yellow", "#262626"];
this.color = colors[Math.floor(Math.random()*colors.length)];
this.radius = 50;
}
function moveParticles() {
//partially clear the screen to fade previous circles, and draw a new particle at each new coordinate
ctx2.globalCompositeOperation = "source-over";
ctx2.fillStyle = "rgba(0, 0, 0, 0.3)";
ctx2.fillRect(0, 0, canvas.width, canvas.height);
ctx2.globalCompositeOperation = "lighter";
for(var i = 0; i < particles.length; i++)
{
var p = particles[i];
ctx2.beginPath();
ctx2.arc(p.x, p.y, p.radius, 0, degreesToRadians(360), true);
ctx2.fillStyle = p.color;
ctx2.fill();
p.x += p.vx;
p.y += p.vy;
if(p.x < -50) p.x = canvas.width+50;
if(p.y < -50) p.y = canvas.height+50;
if(p.x > canvas.width+50) p.x = -50;
if(p.y > canvas.height+50) p.y = -50;
p.radius -= 1;
}
}
function clearScreen(color) {
//clears the screen and fills with the color of choice
ctx2.clearRect(0, 0, canvas.width, canvas.height);
ctx2.fillStyle = color;
ctx2.fillRect(0, 0, canvas.width, canvas.height);
}
window.onload = function() {
animationHandler();
timer = setInterval(moveParticles, 60);
//timerRestart = setInterval(makeParticles, 4000);
}
EDIT: So my issue before and why I started to try to use layers was because the animation of the lava would black out the canvas. So I thought if I separated everything onto different layers, it wouldn't black out the canvas. I implemented Sergio's code down in the answers and it's close to what I'm trying to achieve, but I still am getting the issue from before. I was referencing some code for the eruption animation and that's just how the animation works itself. I guess I should probably put this into a separate question, but is there a different way to get the lava to work to where it will still have the same effect as now, but maybe to where it's canvas' opacity is down so you can see the layer underneath?
This is where the animation happens:
function moveParticles() {
//partially clear the screen to fade previous circles, and draw a new particle at each new coordinate
ctx2.globalCompositeOperation = "source-over";
ctx2.fillStyle = "rgba(0, 0, 0, 0.3)";
ctx2.fillRect(0, 0, canvas.width, canvas.height);
ctx2.globalCompositeOperation = "lighter";
A:
your on the right path. but there are a few issues.
first on windows.load you start by calling animationHandler, without ever calling init(), which results in a lot of errors. then there is a lot of references to a variable called canvas which has not been defined, well; it was but you commented it out. and there are one or two typing error(drawVolcano() has a typing error), which prevent the code from execution.
fixing a few bugs: and adding the init on windows.load you get an animation that works: try this, let me know if this is what you wanted.
if it is, then you did it correctly.. you just had a few small bugs.
<body>
<div id="canvasesdiv" style="position:relative; width:800px; height:500px">
<canvas id="layer1" style="z-index: 1; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
<canvas id="layer2" style="z-index: 2; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
<canvas id="layer3" style="z-index: 3; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
</div>
<script>
//var canvas = document.getElementById("myCanvas");
//var context = canvas.getContext("2d");
var layer1;
var layer2;
var layer3;
var particles;
var eruption;
var timer;
var timerRestart;
function init(){
layer1 = document.getElementById("layer1");
ctx1 = layer1.getContext("2d");
layer2 = document.getElementById("layer2");
ctx2 = layer2.getContext("2d");
canvas=layer3 = document.getElementById("layer3");
context=ctx3 = layer3.getContext("2d");
}
function animationHandler(){
fillBackgroundColor(canvas, context);
drawVolcano();
drawClouds();
eruption = setTimeout(makeParticles, 10);
}
function drawClouds(){
ctx3.beginPath();
ctx3.moveTo(0, 100);
ctx3.bezierCurveTo(0, 100, 75, 200, 150, 100);
ctx3.bezierCurveTo(150, 100, 225, 200, 300, 85);
ctx3.bezierCurveTo(300, 85, 375, 200, 450, 75);
ctx3.bezierCurveTo(450, 75, 525, 200, 600, 100);
ctx3.bezierCurveTo(600, 100, 700, 200, 800, 100);
ctx3.lineTo(800, 0);
ctx3.lineTo(0, 0);
ctx3.closePath();
ctx3.fillStyle = "#6f2a2a";
ctx3.fill();
ctx3.lineWidth = 5;
ctx3.strokeStyle = "#371515";
ctx3.stroke();
}
function drawVolcano(){
ctx1.beginPath();
ctx1.moveTo(0, 400);
ctx1.bezierCurveTo(0, 400, 250, 400, 325, 200);
ctx1.lineTo(425, 200);
ctx1.bezierCurveTo(425, 200, 450, 400, 800, 400);
ctx1.lineTo(800, 500);
ctx1.lineTo(0, 500);
ctx1.closePath();
ctx1.fillStyle = "#802b00";
ctx1.fill();
ctx1.lineWidth = 5;
ctx1.strokeStyle = "#b33c00";
ctx1.stroke();
}
function fillBackgroundColor(canvas, context){
ctx1.fillStyle = "#3399ff" ;
ctx1.fillRect(0, 0, canvas.width, canvas.height);
}
function makeParticles() {
//create an array of particles for our animation
particles = [];
for(var i = 0; i < 100; i++)
{
particles.push(new Particle());
}
}
function degreesToRadians(degrees) {
//converts from degrees to radians and returns
return (degrees * Math.PI)/180;
}
function Particle(){
//the constructor for a single particle, with random starting x+y, velocity, color, and radius
//this.x = Math.random()*canvas.width;
//this.y = Math.random()*canvas.height;
this.x = canvas.width/2;
this.y = (0,0);
this.vx = Math.random()*16-8;
this.vy = Math.random()*10;
var colors = ["red", "#ff6600", "yellow", "#262626"];
this.color = colors[Math.floor(Math.random()*colors.length)];
this.radius = 50;
}
function moveParticles() {
//partially clear the screen to fade previous circles, and draw a new particle at each new coordinate
ctx2.globalCompositeOperation = "source-over";
ctx2.fillStyle = "rgba(0, 0, 0, 0.3)";
ctx2.fillRect(0, 0, canvas.width, canvas.height);
ctx2.globalCompositeOperation = "lighter";
for(var i = 0; i < particles.length; i++)
{
var p = particles[i];
ctx2.beginPath();
ctx2.arc(p.x, p.y, p.radius, 0, degreesToRadians(360), true);
ctx2.fillStyle = p.color;
ctx2.fill();
p.x += p.vx;
p.y += p.vy;
if(p.x < -50) p.x = canvas.width+50;
if(p.y < -50) p.y = canvas.height+50;
if(p.x > canvas.width+50) p.x = -50;
if(p.y > canvas.height+50) p.y = -50;
p.radius -= 1;
}
}
function clearScreen(color) {
//clears the screen and fills with the color of choice
ctx2.clearRect(0, 0, canvas.width, canvas.height);
ctx2.fillStyle = color;
ctx2.fillRect(0, 0, canvas.width, canvas.height);
}
window.onload = function() {
init();
animationHandler();
timer = setInterval(moveParticles, 60);
//timerRestart = setInterval(makeParticles, 4000);
}
</script>
</body>
on my browser however, the particle moved from the top to the bottom. if you want a volcano effect. it has to move in an arc. shooting up from the volcano then falling down. however, you are on the right track, just need to change the code a little bit more.
I modified the code a bit more a few minutes ago, to add an arc type motion of the fireball, and to use some sprites.(http://www.dominicanvoice.com/test/volcano.php)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<div id="canvasesdiv" style="position:relative; width:800px; height:500px">
<canvas id="layer1" style="z-index: 1; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
<canvas id="layer1f" style="z-index: 1; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
<canvas id="layer2" style="z-index: 2; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
<canvas id="layer2f" style="z-index: 2; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
<canvas id="layer3" style="z-index: 3; position:absolute; left:0px; top:0px;" width="800" height="500"></canvas>
</div>
<script>
//var canvas = document.getElementById("myCanvas");
//var context = canvas.getContext("2d");
var layer1;
var layer2;
var layer3;
var particles;
var eruption;
var timer;
var timerRestart;
function init(){
layer1 = document.getElementById("layer1");
ctx1 = layer1.getContext("2d");
layer1f = document.getElementById("layer1f");
f1 = layer1f.getContext("2d");
layer2 = document.getElementById("layer2");
ctx2 = layer2.getContext("2d");
layer2f = document.getElementById("layer2f");
f2 = layer2f.getContext("2d");
canvas=layer3 = document.getElementById("layer3");
context=ctx3 = layer3.getContext("2d");
}
function animationHandler(){
fillBackgroundColor(canvas, context);
drawVolcano();
//drawClouds();
eruption = setTimeout(makeParticles, 10);
}
var cloud = new Image();
cloud.src='http://www.dominicanvoice.com/test/volcano/cloud.png';
var fireball = new Image();
fireball.src='http://www.dominicanvoice.com/test/volcano/fireball.png';
function drawVolcano(){
img = new Image();
img.src='http://www.dominicanvoice.com/test/volcano/layer2.png';
img.onload = function() { ctx1.drawImage(this,0,0);};
img2 = new Image();
img2.src="http://www.dominicanvoice.com/test/volcano/front.png";
img2.onload = function() { ctx2.drawImage(this,0,0);};
}
function fillBackgroundColor(canvas, context){
ctx1.fillStyle = "#3399ff" ;
ctx1.fillRect(0, 0, canvas.width, canvas.height);
}
function makeParticles() {
//create an array of particles for our animation
particles = [];
for(var i = 0; i < 100; i++)
{
particles.push(new Particle());
}
}
function degreesToRadians(degrees) {
//converts from degrees to radians and returns
return (degrees * Math.PI)/180;
}
function Particle(){
//the constructor for a single particle, with random starting x+y, velocity, color, and radius
//this.x = Math.random()*canvas.width;
//this.y = Math.random()*canvas.height;
this.x = canvas.width/2;
this.y = 160;
this.vx = Math.random()*16-8;
this.vy = Math.random()*25;
var colors = ["red", "#ff6600", "yellow", "#262626"];
this.color = colors[Math.floor(Math.random()*colors.length)];
this.radius = 50;
}
function moveParticles() {
//partially clear the screen to fade previous circles, and draw a new particle at each new coordinate
f1.clearRect(0, 0, canvas.width, canvas.height);
f2.clearRect(0, 0, canvas.width, canvas.height);
for(var i = 0; i < particles.length; i++)
{
var p = particles[i];
f=(p.vy>0) ?f1:f2;
if (p.vy>0) f.drawImage(cloud,Math.floor((25-p.vy)/2)*128,0,128,128,p.x-64,p.y,128,128)
else ctx3.drawImage(cloud,1536,0,128,128,p.x-Math.random()*5-64,-20+Math.random()*10,128,128);
if (p.y<500) {
f.drawImage(fireball,Math.floor(-p.vy/2)*128,0,128,64,p.x-64,p.y,128,64);
// f.beginPath();
// f.arc(p.x, p.y, p.radius, 0, degreesToRadians(360), true);
// f.fillStyle = p.color;
// f.fill();
p.x += p.vx;
p.y -= p.vy;
p.vy-=1;
if(p.x < -50) p.x = canvas.width+50;
if(p.y < -50) p.y = canvas.height+50;
if(p.x > canvas.width+50) p.x = -50;
if(p.y > canvas.height+50) p.y = -50;
p.radius -= 1;
};
}
}
window.onload = function() {
init();
animationHandler();
timer = setInterval(moveParticles, 60);
//timerRestart = setInterval(makeParticles, 4000);
}
</script>
</body>
The code has not been cleaned up or optimized, but you can look at it modify it and play with it.
you can see it working here: http://www.dominicanvoice.com/test/volcano.php
NOTE: I did not test this code on a Mac. only on windows and it worked fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding the Remainder after Division in C
You need to use division and remainder by 10,
Consider this example,
163 divided by 10 is 16 and remainder is 3
16 divided by 10 is 1 and remainder is 6
1 divided by 10 is 0 and remainder is 1
Notice that the remainder is always the last digit of the number that's being divided.
How can I do this in C?
A:
It looks like homework so I won't give you code, but I suggest you research the modulo operator and how this could be used to solve your assignment.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding a line $L\subset V(y-xz)\subset\mathbb A^3_k$
I want to find lines $L\subset V(y-xz)$ and $M\subset\mathbb A_k^2$ such that
$$ V(y-xz)\setminus L \simeq \mathbb A_k^2\setminus M\ . $$
Hint suggests that I use the projection $(x,y,z)\mapsto(x,y)$. I tried to find nice inverse rational map plugging some lines but failed. How can I get such $L$ and $M$?
A:
Take $M=\{ax+by=0\} \subset\mathbb{A}_k^2$. The pre-image under the projection of $V(y-xz)$ to the affine plane is contained in the union of two lines $L:\{x=0,y=0\}\cup \{a+bz=0,y-xz=0\}$ (convince yourself that these are lines). On the complement, you have $x\neq 0$ and thus $z=y/x$ makes sense. So the complement looks like the affine plane minus the line $x= 0$ minus the line $x= -b/ay$. You want the second line to be contained in the first line, so $b$ must be zero. Then you see that for lines $M=\{x=0\}\subset \mathbb{A}_k^2$ and $L=\{x=0,y=0\}\subset V(y-xz)$ the complements are isomorphic.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to retrieve Crystal page setting programmatically in C#?
I created a Crystal report (.rpt file) in Crystal Designer. I configured Page Setup. I want to retrieve e.g. page orientation, page width, page high programmatically in C#. How to do it? Note that I want to retrieve page settings, no print settings. I don't want to edit page settings, I only need to read it.
===EDIT===
Following figure shows my page setup:
PrintOptions.PageContentWidth and PrintOptions.PageContentHeight in C# have different values.
ReportDocument rp = new ReportDocument();
rp.Load(path_to_my_report_file);
Console.WriteLine(rp.PrintOptions.PageContentHeight);
Console.WriteLine(rp.PrintOptions.PageContentWidth);
Output:
5670
8505
I need to retrieve page width and height to set they in PaperSize (myPaperSize = new System.Drawing.Printing.PaperSize(name, width, height);)
A:
ReportDocument.PrintOptions should give you the numbers that you need. For example, for the page width, using members of PrintOptions:
PageContentWidth + PageMargins.leftMargin + PageMargins.rightMargin
However, these values are in TWIPS, where 1440 twips = 1 inch. (I have no idea what the proper capitalization is...)
On the other hand, System.Drawing.Printing.PaperSize uses numbers in hundredths of an inch, so you would have to convert:
[Dimension in hundredths of an inch] = [Dimension in TWIPS] / 1440.0 * 100
| {
"pile_set_name": "StackExchange"
} |
Q:
The address entered appears to be invalid. Please correct your address and resubmit
I am new to iOS development. I have a Apple ID. In that I am getting following error while updating the address in iTunes connect agreements, tax, and banking page.
I have used address like this
here I have display the screen shot of my error
how to rectify this error.
A:
You can try this solution found on AppDeveloper
Just found a solution. Try clicking the add/save/submit button 3 times.
It worked for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there any downsides to regularly getting a condo appraised for tax purposes in the US?
I own a condo in a metropolitan downtown area of Colorado, USA. The housing market is very hot, and my property taxes are skyrocketing to the point where I can barely afford them. Part of the problem is that, in my opinion, the city is incorrectly evaluating the market value of my condo based on recent sales of much "nicer" condos in my building.
To combat this, I have been considering getting my condo appraised every two years, at around the time that the "value" of the condo is determined by the city for tax purposes. What I'm trying to find out is: is there a downside that I'm not considering from this approach?
The long form:
I have a bit of an odd situation. I live in a building which was once a 19th-century department store. In the early 1990s, it was converted into condos and apartments. The units in the building are of a wide range of styles and "niceness"; that is, there is a large variety in how "nice" a unit is. However, when the city evaluates my condo's worth for property tax purposes, it appears that they do so without regard to the "niceness" of the units. That is, it compares my condo with the recent sales of any units in the building without regard to how nice the unit is.
For example, the building takes up half of a square city block, so half of the units have a view of the alley between this building and the next (which is not very nice, in my opinion). The units on the top floors used to be a luxury restaurant atop the department store, so they have much nicer basic furnishings -- wood panelling on the walls, wrought iron fixtures, patios, etc.
Some numbers:
Unit was bought in February 2013, for less than $400,000
Property tax assessment claims it was worth $480,000 as of June 2014; challenged. Revised to $420,000.
I refinanced my mortgage in December 2015. Professionally appraised on behalf of the new mortgage company at $480,000 as of December 28.
Property tax assessment claims it is worth $660,000 as of June 2016.
The documentation included in the last tax assessment indicated that the value was based on the sale price of other units in my building within the past year -- three units on the upper floors. (eg the "luxury" units with patios, nice furnishings, views of the street, etc.) Other tenants and homeowners in my building have also mentioned to me that they've been having issues with the city valuing all units in the building as if they are identically furnished, so this isn't just in my head. :)
I've challenged this latest valuation based primarily on the assessment done six months prior, and also challenged the validity of the comparison to the "luxury" units. However, upon further reflection, I've also realized that if I hadn't refinanced and hadn't gotten my unit assessed, this challenge would have been much more difficult. Due to this, I've started considering a plan in which I would get my condo assessed every two years, at around the time that the city determines the "value" of my unit for tax purposes. Other than the cost of the assessment itself, I'm trying to determine what other potential issues, side effects, or hidden costs I might run into with this plan.
(Admittedly, the results of my last challenge haven't been determined yet; however if they don't accept my numbers based on the appraisal I will be doing an in-person challenge of the valuation. I also have one of the highest HOA fees in the city on a per-square-foot basis which was included as a footnote in my challenge and is only halfway relevant, I think.)
A:
The main downside as I see it is the costs of appraisal that you mentioned. I would expect that there would need to be a significant amount of error in the government appraisal in order to make a separate appraisal you paid for yourself worth it, though perhaps there is in your case. I can't foresee any "hidden costs", as it just gives you a more accurate valuation of what you own that you can use as evidence in your abatement request.
If this seems to be an issue among the large group of people in the building, it may also be worth organizing a meeting between interested people in your building and the Board of Assessors (that's what it's called here in Massachusetts; I assume there'd be something similar elsewhere) explaining the differences in the different units and trying to come to an understanding as to the best way for them to assess you. It's likely that they just don't have the additional information that you have when they try to determine an appropriate valuation.
| {
"pile_set_name": "StackExchange"
} |
Q:
p-value for two small Bernoulli trials
I am no statistician, but I am among the more statistically inclined at my workplace, so my coworkers consult me from time to time. I don't alway give the right answer, but I'd like to think I give reasonable answer most of the time. This time, I couldn't find exactly what I was looking for on the internet, so I come here for help.
At our laboratory, they have received 23 samples and tested for a pathogen. 16 came out positive. In the general population, they would expect the prevalence to be about 10%, so this is rather high. They want to be sure, thoguh, and therefore want to design a control study. The main issue I was asked about was the control sample size. They didn't want a large control size, so I was asked to look into, for different control sizes and different control results, how strong would the result be.
So the first thing I found was the test statistic
$$
z = \frac{\hat p_1 - \hat p_2}{\sqrt{\hat p(1-\hat p)\left(\frac1{n_1}+ \frac1{n_2}\right)}}
$$
but it came with the stipulation that both trials have more than five successes and more than five failures. And if we expect a control prevalence of 10%, that means we should have at least 50 controls. That's more than the lab guys expect.
And I couldn't find any info on the internet to help me with the small sample size. So, this is what sounds reasonable to me:
Let the null hypothesis be that the control samples and the case samples come from the same Bernoulli distribution. Let the control sample size be $n$, and the control results be $k$ positive. Then we have $23+n$ samples from a Bernoulli trial, and the first $23$ of them had $16$ of the $16+k$ positive results.
The probability that at least $16$ of the positive results happen to appear among the first $23$ samples is
$$
\sum_{j = 0}^{k}\frac{\displaystyle\binom{23}{16+j}\cdot \binom{n}{k-j}}{\displaystyle\binom{23+n}{16+k}}
$$
To a non-statistician like me, that looks like a (one-tailed) $p$-value. And as the numbers are small, it's rather easy to compute.
I am pretty certain that I have missed something, because this is not my area of expertise. The fact that this is one-tailed is one of those things. Is this approach salvageable, or am I completely off the mark?
A:
Define $\pi =P(\text{Dis})$ as prevalence, and let $\tau = P(\text{Pos}).$
Also define
$\eta = P(\text{Pos}|\text{Dis})$ as sensitivity and
$\theta =P(\text{Neg}|\text{No Dis})$ as specificity.
Then $\tau = \pi\eta + (1-\pi)\theta.$ And with a little algebra, one obtains
$$\pi = \frac{\tau+\theta - 1}{\eta + \theta - 1}.$$
So if $\tau$ is estimated by $t = \frac{\text{Nr. testing Pos}}{\text{Nr. tested}},$ then $\pi$ may be estimated by
$$p = \frac{t+\theta - 1}{\eta + \theta - 1}.$$
One can obtain a binomial confidence interval (CI) for $\tau$ and use the second displayed equation to transform endpoints of the CI for $\tau$ to get a
CI for $\pi$ (of the tested population).
In some cases, the estimate $p$ of prevalence can fall outside of $(0, 1).$
Then one can use a Bayesian approach and perhaps Gibbs sampling to get
a useful interval estimate for $p.$
| {
"pile_set_name": "StackExchange"
} |
Q:
ADT Plugin "Loading data for Android X.X.X" every time XML files are opened
I know there are some questions like this on stackOverflow, but i think they are old.
I'm working with the latest versions of Android SDK Tols (24.3.2 rev) and ADT 23.0.6. This problem with eclipse, it seems fixed for ADT 22.6.3, but i dont want to downgrade my ADT version.
Anyone can help to fix this problem?.
My scenario:
Eclipse Juno
Jdk 1.7
Android SDK Tools 24.3.2 rev
ADT 23.0.6
Windows 8.1 Pro
8GB ram
Thanks!
EDIT
I'm using the old Eclipse Bundle with sdk. If set Android Sdk Path to the sdk bundle, the problem appears but if i use SDK from [USER]/AppData/Android/sdk i works as espected. (AppData Android is generated by Android Studio).
My question is, what is the reason for that behavior?.
Thanks
A:
The problem is in the version of your SDK and ADT. You can resolve installing Android Studio that is now the official IDE for Android Application development.
Here is a notice from developer.android.com:
Important: Support for the Android Developer Tools (ADT) in Eclipse is ending, per our announcement. You should migrate your app development projects to Android Studio as soon as possible. For more information on transitioning to Android Studio, see Migrating to Android Studio.
Android studio download
Android studio overview
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the largest sum of 3 consecutive digits from number
I have a task to write the C program that finds the largest sum of 3 consecutive digits in numbers. I wrote it, but I have trouble: the program seems to work fine, but instead of correct answer it types some strange numbers.
For example, if input is "560315", the response is "155". However, if I type "560415" the answer is still "155" and if I type "561315" the response changes to "156". Is it a problem with encoding?
Here's the code:
#include <stdio.h>
int isempt(int a) {
if ((a==' ')||(a=='\n')||(a=='\t')) {
return 1;
}
else return 0;
}
main() {
int a, b, c, d, e, i, maxsum;
a = 0;
b = 0;
c = 0;
d = 0;
maxsum = 0;
i = 0;
int counter = 0; //the variables "numsearch" and "inside" indicate whether program is in the number or outside it
int numsearch = 1;
int inside = 0;
while ((i = getchar())!=EOF) {
if (numsearch==1) {
if (isempt(i)==0) {
numsearch = 0;
inside = 1;
a = i;
counter++;
}
}
else if ((isempt(i)==0)&&(inside==1)) {
if (counter == 1) {
b = i;
counter++;
}
else if (counter == 2) {
c = i;
counter++;
}
else if (counter == 3) {
d = i;
maxsum = a+b+c;
if ((b+c+d) > maxsum) {
maxsum =( b+c+d);
}
a =b;
b = c;
c = d;
counter++;
}
else if (counter == 4) {
d = i;
if ((b+c+d)>maxsum) {
maxsum = b+c+d;
}
a=b;
b=c;
c=d;
}
}
else if ((counter>=3)&&(isempt(i)==1)) {
printf("\n%d\n", maxsum );
counter = 0;
numsearch = 1;
inside = 0;
a = 0;
b = 0;
c = 0;
d = 0;
}
else {
counter = 0;
numsearch = 1;
inside = 0;
a = 0;
b = 0;
c = 0;
d = 0;
}
}
}
A:
to solve this problem ,you can subtract 48 from i every time you use value of variable i to assign it to the variables of your algorithm : a,b,c,d , in this case the answer to your example 560316 will be 11 ,and I believe it's the largest sum of 3 consecutive digits, That will work because 48 is the ascii code of the digit 0 ,49 is for the digit 1 and so on, so your code should be like this :
#include <stdio.h>
int isempt(int a) {
if ((a==' ')||(a=='\n')||(a=='\t')) {
return 1;
}
else return 0;
}
void main() {
int a, b, c, d, e, i, maxsum;
a = 0;
b = 0;
c = 0;
d = 0;
maxsum = 0;
i = 0;
int counter = 0; //the variables "numsearch" and "inside" indicate whether program is in the number or outside it
int numsearch = 1;
int inside = 0;
while ((i = getchar())!=EOF) {
if (numsearch==1) {
if (isempt(i)==0) {
numsearch = 0;
inside = 1;
a = i - '0';
counter++;
}
}
else if ((isempt(i)==0)&&(inside==1)) {
if (counter == 1) {
b = i - '0' ;
counter++;
}
else if (counter == 2) {
c = i - '0';
counter++;
}
else if (counter == 3) {
d = i - '0';
maxsum = a+b+c;
if ((b+c+d) > maxsum) {
maxsum =( b+c+d);
}
a =b;
b = c;
c = d;
counter++;
}
else if (counter == 4) {
d = i - '0' ;
if ((b+c+d)>maxsum) {
maxsum = b+c+d;
}
a=b;
b=c;
c=d;
}
}
else if ((counter>=3)&&(isempt(i)==1)) {
printf("\n%d\n", maxsum );
counter = 0;
numsearch = 1;
inside = 0;
a = 0;
b = 0;
c = 0;
d = 0;
}
else {
counter = 0;
numsearch = 1;
inside = 0;
a = 0;
b = 0;
c = 0;
d = 0;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to order X axis by YearMonth at Seaborn
I use the current version of http://archive.ics.uci.edu/ml/datasets/Air+quality
My issue is that I want to create a plot that is ordered by monthly aggregates of different features that plotted on multiple graphs
YearMonth Creation for X Axis
INPUT:
df['DateTime'] = df['Date'].astype(str) + ' ' + df['Time'].astype(str)
df['DateTime'] = pd.to_datetime(df['DateTime'], format='%m/%d/%Y %H:%M:%S')
print(df['DateTime'].iloc[:2])
OUTPUT:
0 2004-11-23 19:00:00
1 2004-11-23 20:00:00
Name: DateTime, dtype: datetime64[ns]
INPUT:
df['Date'] = pd.to_datetime(df['Date'].astype(str), format='%m/%d/%Y')
df['Year'] = df['DateTime'].map(lambda x: x.year)
print(df['Year'].iloc[:2])
OUTPUT:
0 2004
1 2004
Name: Year, dtype: int64
INPUT:
df['YearMonth'] = pd.to_datetime(df.DateTime).dt.to_period('m')
print(df['YearMonth'].iloc[:2])
OUTPUT:
0 2004-11
1 2004-11
Name: YearMonth, dtype: period[M]
Goal project has same results, format
My Plotting
plt.figure(figsize=(30,60))
#fig, axes = plt.subplots(1, 1, figsize=(30, 60), dpi=100)
gasList = ['CO_GT', 'C6H6_GT', 'Nox_GT', 'NO2_GT']
for i, col in enumerate(gasList, start=1):
plt.subplot(len(showList), 1, i)
sns.pointplot(x='YearMonth', y=col, hue='Year', data=df)
plt.title(col, y=0.5, loc='right')
#axes.set_xticks(year_month_day)
plt.show()
Ideal plotting
I am trying to achieve the same as this projects
Tried to do to Solve the problem
If I would just use DateTime than it works to order the dates but that makes the plot to densely populated
I have the same data format that creates the YearMonth
<class 'pandas.core.frame.DataFrame'>
Int64Index: 9357 entries, 0 to 9356
Data columns (total 17 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Date 9357 non-null datetime64[ns]
1 Time 9357 non-null object
2 CO_GT 9357 non-null float64
3 PT08_S1_CO 9357 non-null float64
4 C6H6_GT 9357 non-null float64
5 PT08_S2_NMHC 9357 non-null float64
6 Nox_GT 9357 non-null float64
7 PT08_S3_Nox 9357 non-null float64
8 NO2_GT 9357 non-null float64
9 PT08_S4_NO2 9357 non-null float64
10 PT08_S5_O3 9357 non-null float64
11 T 9357 non-null float64
12 RH 9357 non-null float64
13 AH 9357 non-null float64
14 DateTime 9357 non-null datetime64[ns]
15 Year 9357 non-null int64
16 YearMonth 9357 non-null period[M]
dtypes: datetime64[ns](2), float64(12), int64(1), object(1), period[M](1)
memory usage: 1.3+ MB
His data set's time formatting was Y m d mine was m d Y but I have changed back to the the same as his
I have tried to use seaborn's order parameter. It loads for a long time but doesn't gives anything back.
col_one_list = df['YearMonth'].tolist()
plt.figure(figsize=(30,60))
gasList = ['CO_GT', 'C6H6_GT', 'Nox_GT', 'NO2_GT']
for i, col in enumerate(gasList, start=1):
plt.subplot(len(showList), 1, i)
sns.pointplot(x='YearMonth', y=col, hue='Year', data=df, order = col_one_list )
plt.title(col, y=0.5, loc='right')
plt.show()
I have created a list myself of uniq values but that have also crashed. OUTPUT: correct YearMonth-s x axis ticks, correct plot external elements, but no data points plotted.
plt.figure(figsize=(30,60))
col_two_list = ['2004-03','2004-04', '2004-05', '2004-06', '2004-07', '2004-08', '2004-09', '2004-10', '2004-11','2004-12', '2005-01','2005-02','2005-03', '2005-04']
gasList = ['CO_GT', 'C6H6_GT', 'Nox_GT', 'NO2_GT']
for i, col in enumerate(gasList, start=1):
plt.subplot(len(showList), 1, i)
sns.pointplot(x='YearMonth', y=col, hue='Year', data=df, order = col_two_list )
plt.title(col, y=0.5, loc='right')
plt.show()
A:
Short answer
When you generate your pointplot, pass sorted DataFrame (by
YearMonth) and the printout should be just as you wish.
Without the above sort the picture is as you presented (wrong).
Long answer
I prepared a test input file, for just 2 columns, as follows:
DateTime CO_GT C6H6_GT
2004-11-01 2.7 12.4
2004-12-01 2.6 10.6
2004-10-01 3.0 13.8
2005-01-01 2.0 9.0
2005-02-01 2.2 8.0
2004-03-01 2.2 10.0
2004-09-01 2.2 12.0
2005-03-01 2.0 8.6
2004-04-01 2.1 10.2
2004-05-01 1.95 10.5
2004-06-01 1.85 10.4
2004-07-01 1.7 10.5
2005-04-01 1.3 4.5
2004-08-01 1.4 6.8
Then I read it, converting DateTime column to datetime type (as early
as possible, i.e. just on reading):
df = pd.read_fwf('Input.csv', widths=[12, 7, 7], parse_dates=[0])
The first step is to create "auxiliary" columns:
df['Year'] = df.DateTime.dt.year
df['YearMonth'] = df.DateTime.dt.to_period('m')
And to generate the picture, I ran:
gasList = ['CO_GT', 'C6H6_GT']
plt.figure(figsize=(14, 8))
for i, col in enumerate(gasList, start=1):
plt.subplot(len(gasList), 1, i)
sns.pointplot(x='YearMonth', y=col, hue='Year', data=df.sort_values('DateTime'))
plt.title(col, y=0.5, loc='right')
plt.show()
The result is:
| {
"pile_set_name": "StackExchange"
} |
Q:
Change day start and end time
How can I force R to change the parameters of a day. So I mean that for example yrDay like here provided doesn't go from 0am til 0am but from 6pm til 6pm.
df <- data.frame(Date=seq(
from=as.POSIXct("2012-1-1 13:00:00", tz="UTC"),
to=as.POSIXct("2012-1-3 13:00:00", tz="UTC"),
by="hour")
)
df$yrDay <- as.numeric(strftime(df$Date,format="%j"))
A:
Just add 5 hours (5 * 60 min * 60 sec) using your code:
df$yrDay <- as.numeric(strftime(df$Date + 5*60*60,format="%j"))
Date yrDay
1 2012-01-01 13:00:00 1
2 2012-01-01 14:00:00 1
3 2012-01-01 15:00:00 1
4 2012-01-01 16:00:00 1
5 2012-01-01 17:00:00 1
6 2012-01-01 18:00:00 2
7 2012-01-01 19:00:00 2
8 2012-01-01 20:00:00 2
9 2012-01-01 21:00:00 2
10 2012-01-01 22:00:00 2
...
Or 6 hours using lubridate (better approach IMHO):
df$yrDay <- lubridate::day(df$Date + 6*60*60)
But as mentioned by @ngm in the comments, it is a quick and dirty solution that might not be robust for all cases.
| {
"pile_set_name": "StackExchange"
} |
Q:
Avoiding un-representable DateTime when using DateTimePicker CustomFormat MMM-yyyy
Suppose I have a DateTimePicker with a CustomFormat of MMM-yyyy which has been initialised to a value of 31st Oct 2013, this will display as Oct-2013.
If the select the Oct section of the control and press either up or down arrow, this generates an ArgumentOutOfRangeException - Year, Month, and Day parameters describe an un-representable DateTime.
Presumably it is changing the month without changing the day and there are only 30 days in September and November. Note, if the CustomFormat is dd-MMM-yyyy then no error is thrown because the day is automatically changed to the 30th.
How can I avoid or catch this error?
I can add code to ensure that the DateTimePicker is always initialised to the first of a month, but I want to allow the user to select the month and date from the calender dropdown, so I need to cope with the situation where the user has manually selected the 31st and then tries to change the month using the keyboard.
A:
Just initialize it to Oct 1st. No exception, still the same display.
And of course you'll need to adjust the value picked by the user to keep it on the 1st:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e) {
var dtp = (DateTimePicker)sender;
dtp.Value = new DateTime(dtp.Value.Year, dtp.Value.Month, 1);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Change opacity of random image (toggle)
I have looked for an answer for about 2 hours without any success:
How do you make an animation that change the opacity of images in a grid randomly with a slow fadein ?
A:
It's not the most elegant code since I did it in like 5 minutes, but you may be able to get the idea and improve it:
jQuery
$(function(){
setInterval(function(){
var i = Math.floor(Math.random() * 10) + 1;
$("[data-highlight=1]").attr("data-highlight", "0").animate({
opacity: 0.2
}, 1000);
$("#photo-" + i).attr("data-highlight", "1").animate({
opacity: 1
}, 1000);
}, 3000);
});
CSS
.photo {
width: 150px;
height: 150px;
background-color: #F00;
font-size: 2em;
color: #FFF;
float: left;
opacity: 0.2;
}
HTML
<div class="photo" id="photo-1" data-highlight="0">DIV</div>
<div class="photo" id="photo-2" data-highlight="0">DIV</div>
<div class="photo" id="photo-3" data-highlight="0">DIV</div>
<div class="photo" id="photo-4" data-highlight="0">DIV</div>
<div class="photo" id="photo-5" data-highlight="0">DIV</div>
<div class="photo" id="photo-6" data-highlight="0">DIV</div>
<div class="photo" id="photo-7" data-highlight="0">DIV</div>
<div class="photo" id="photo-8" data-highlight="0">DIV</div>
<div class="photo" id="photo-9" data-highlight="0">DIV</div>
<div class="photo" id="photo-10" data-highlight="0">DIV</div>
Here is a demo: https://jsfiddle.net/ymu3ghgk/
| {
"pile_set_name": "StackExchange"
} |
Q:
Funciones en Jtable Java
Buenas necesito saber como poner una funcion en un Jtable en Java para que en una columna descuente un porcentaje especifico de otra columna, ejemplo que la tabla tenga dos columnas que en la columna 1 se pone un monto y la columna dos descuente un porcentaje automaticamente de la columna 1, la idea es para hacer una nomina y que al poner el salario del empleado en las otras columnas descuente automaticamente los porcentajes que se descuentan de dicho salario por seguro, entre otros. Gracias espero ser claro y obtener una ayuda.
A:
La verdad es que ni tu pregunta, ni la manera que existe para cambiar los datos de una JTable son demasiado claras, pero vamos a intentarlo.
Aqui tienes un MVCE para que modifiques como necesites. (comentarios en el código) que permite el cambio de los datos y recalcula la 3a columna en funcion de las dos primeras como pedías.
NOTAS:
He realizado las pruebas en Eclipse: ten en cuenta que el IDE (en tu caso NetBeans) no influye en como trabajan las technologias (en este caso Swing).
He realizado la operacion de precio * cantidad, pero pasar a descuento como tu quieres es muy facil...
MVCE
public static void main(String[] args) throws Exception {
// nombre de las columnas
Object nombreColumnas[] = { "Precio" , "Cantidad", "Total" };
// datos iniciales SIN TOTALES
String datos[][] = {
{ "10.33", "2", "" },
{ "30.5", "8", "" } };
// creamos la tabla con los datos de ejemplo
final JTable table = new JTable(datos, nombreColumnas);
// calculamos los totales antes de mostrar la tabla
table.setModel(calculatTotales(table.getModel()));
// y le añadimos un listener
//
// ¡¡¡¡OJO!!!!!
//
// El listener se lo ponemos AL MODELO DE DATOS, no a la tabla!!!!
table.getModel().addTableModelListener(new TableModelListener() {
// para evitar concurrencias
boolean active = false;
// evento general
public void tableChanged(TableModelEvent e)
{
// si no tiene una ejecucion y hemos modificado
if (!active && e.getType() == TableModelEvent.UPDATE) {
active = true;
// recogemos el modelo
TableModel modelo = table.getModel();
// y le ponemos el nuevo con los totales calculados
table.setModel(calculatTotales(modelo));
active = false;
}
}
});
// jframe standard para enseñar la tabla
JFrame frame = new JFrame();
frame.setSize(300, 100);
// apartde de hacer scrill sirve para
// mostrar los titulos de las columnas
frame.add(new JScrollPane(table));
frame.setVisible(true);
}
private static TableModel calculatTotales(TableModel datos) {
for (int x = 0; x < datos.getRowCount(); x ++) {
String valor = null;
try {
valor = String.valueOf((Double.valueOf((String) datos.getValueAt(x, 0)) * (Integer.valueOf((String) datos.getValueAt(x, 1)))));
} catch (Exception e) {}
datos.setValueAt(valor, x, 2);
}
return datos;
}
RESULTADO:
inicial
una vez modificado
| {
"pile_set_name": "StackExchange"
} |
Q:
The location of EIP and other Registers in x86 Process
I am working with x86 instructions and now I confused about :
Where do x86 Registers (Like :EIP,ESP and etc.) stores ?!
For example when I use ollydbg I could see what is the actual EIP register value and how it changes.
If it stores in memory where is the actual location ? (For example in .data .text or .bss)
And can I change the EIP of another process manually ?! How ?!
A:
You have a severe misconception about what a register is.
A register is actually a register, ie. a really small piece of memory in the processor that can contain the operands or can be the target of a CPU instruction. It doesn't have an address in memory - it's really adressable as the register it is.
RAM is something totally different – an x86 program can work completely without RAM, but there's no operation that doesn't work on registers. For example, to add two numbers that are somewhere in RAM, you use LOAD instructions to load these two numbers into two register, and then some ADD instruction to add one number to the other, targeting a register, and then there's some STORE instruction that takes the register value and writes it to some address in RAM.
So, there's no "process-specific" registers. Every CPU core has exactly one set of registers (some specialities like virtualization nonwithstanding), and there's mechanisms to store registers in RAM, and restore them from RAM, for example when calling a function or switching contextes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use code inspector in Firefox to do a Check All input type = checkbox on a website that isn't mine?
I have a question that is a little outside my realm. I'm a newbie to jquery and javascript. I run a forum on ProBoards, and when the forum runs out of its allocation for attachments (pictures the users can post) I have to manually go through the attachment list and check every single checkbox one by one, then I am able to click a delete button to delete every attachment I've checked. Checking the thousands of boxes one by one takes forever. There is no implemented "check all", and there are thousands of checkboxes.
In the code, every single checkbox has the name ids[]:
<input type="checkbox" value="1494" name="ids[]"></input>
So I should be able to target them by the name "ids[]" I would think. The value is different for each one. The name is the same for all. But the question is... what code would I use and where would I put it in Firebug or Inspector? I'm sadly too much of a noob to be able to figure out what I would do.
I have Firebug for Firefox, and in that I have the add-on jQuerify, so I can force jQuery into the code if that helps create the simplest solution.
Basically I'm looking for a way to add some code to automatically check every single one of these boxes (or add a button that will allow me to do so if that is the only way), and I must be able to do it from Firebug or the Inspector in Firefox (or even in Chrome would be fine). I don't think I am able to modify the code (permanently) of this specific administrative page of my forum, so I need to be able to do it from the Inspector/Firebug. I'd like something I can just copy and paste into there to save myself 45 minutes to an hour of clicking thousands of checkboxes one by one.
Any solutions?
A:
Use like this,
$("input:checkbox").attr('checked','checked');
| {
"pile_set_name": "StackExchange"
} |
Q:
convergence of series involving powers
Test the following series for convergence:
a. $$\sum_{n=1}^{\infty}\frac{(n+1)^n}{(n)^{n+\frac{5}{4}}}$$
b. $$\sum_{n=1}^{\infty}\frac{1}{\sqrt{n}} \tan\left(\frac{1}{n}\right)$$
When I tried using ratio and root tests for (a), the limit came out to be $1$. So I could reach no conclusion.
May be limit comparison test can be used . Not sure which series to compare it with.
A:
For the first series, write
$$\frac{(n + 1)^n}{n^{n + 5/4}} = \left(1 + \frac 1 n\right)^n \frac{1}{n^{5/4}} \le \frac{3}{n^{5/4}}$$
since $(1 + 1/n)^n \to e$, for large enough $n$.
As a hint for the second, show that
$$\lim_{x \to \infty} x \tan \frac 1 x = 1$$
Use this to apply the comparison test.
| {
"pile_set_name": "StackExchange"
} |
Q:
In docker container how to run another container command?
Example:
I have a image ubuntu and another image mongodb.
How can I run mongod(mongodb command) or another mongodb image command when I'm running ubuntu image.
A:
Any image will generate one or more containers.
Every container is isolated of others.
If you can run MongoD inside a Ubuntu based container you need to install MongoDB inside your Ubuntu based container.
But, if you need connect on mondodb to create a user, change settings of your mongod instance, you don't need a second container, on mongodb container you can execute commands to perform that.
On mongodb documentation at docker hub, the example about mondodb security talks about it, the example explain how to connect your shell to container, and show how execute docker exec -it [mongodbContainerName|mongodbContainerId] mongo admin to get access to administration of mongodb using console.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fourier Phase Angle Interpretation
I am trying to fit the following tide data (taken from here) with a sinusoidal curve that looks like the following: displacement+amplitude * sin(t w - ph), where t is the independent variable, w is the angular frequency, ph is the phase, displacement is the average offset from zero, and amplitude is the sine curve's amplitude.
(* Times measured from midnight, 28 September (hours) *)
xd = {19.4000, 25.6333, 31.7833, 38., 44.1167, 50.3667, 56.4667,
62.6833, 68.8167, 75.0500, 81.1333, 87.3333, 93.5000, 99.7500,
105.8000, 112.0167};
(* Tidal heights offset from standard water level (m) *)
yd = {0.88, 12.71, 0.88, 12.63, 0.78, 12.59, 1.06, 12.57, 0.88, 12.32,
1.40, 12.35, 1.15, 11.94, 1.84, 12.02};
samples = Transpose[{xd, yd}];
Thus far, I have tried four methods (LinearModelFit, Solve, NonlinearModelFit, and Fourier). This question concerns the last.
Here is the code I have used to produce the sine function using the discrete Fourier transform:
SinusoidFitDFT[data_] :=
Module[{xd, yd, deltaT, numberOfSamples, samplingPeriod,
samplingRate, displacement, amplitude, \[Omega], \[CurlyPhi]},
xd = data[[1 ;; All, 1]];
yd = data[[1 ;; All, 2]];
deltaT = Mean[Differences[xd]]; numberOfSamples = Length[xd];
samplingPeriod = numberOfSamples deltaT; samplingRate = 1/deltaT;
dft = Fourier[yd];
maximumFrequencyPosition = (1. + Position[#1, Max[#1]][[1, 1]] &)[
Abs[Rest[dft]]];
frequencies =
Table[((i - 1) samplingRate)/
numberOfSamples, {i, numberOfSamples}];
maximumFrequencyContributor =
frequencies[[maximumFrequencyPosition]]; displacement = Mean[yd];
amplitude =
Norm[Standardize[yd, Mean, 1 &], \[Infinity]]; \[Omega] =
2 \[Pi] maximumFrequencyContributor; \[CurlyPhi] =
Arg[dft[[maximumFrequencyPosition]]]; {displacement,
amplitude, \[Omega], \[CurlyPhi]}
];
This solution produces reasonable parameters, with the exception of the phase ([CurlyPhi]). Here is a plot of the original data (red dots) with the overlaid Sine curve (blue line). Included also are the values of the four fitted parameters and the root-mean square error.
{displacement, amplitude, \[Omega], \[CurlyPhi]} =
SinusoidFitDFT[samples]
fittedFunction = (displacement +
amplitude*Sin[\[Omega]*# - \[CurlyPhi]] &);
RootMeanSquare[yd - fittedFunction /@ xd]
Show[
ListPlot[samples, PlotStyle -> Red],
Plot[fittedFunction[x], {x, samples[[1, 1]], samples[[Length@xd, 1]]}]
]
It is my understanding that the phase angle of the curve can be obtained by taking the ArcTangent of the result of the Fourier transform at the position of the maximum frequency contributor. Here are the intermediate results. First, the list of frequencies used to construct the transform:
Here is the Fourier transform of the tidal data:
Now the frequency spectrum plot:
Everything looks okay to this stage. Note that the biggest frequency contributor (besides the zero-frequency component) occurs at the ninth position in the transform. The value of the frequency at this position is at about .08, which naturally corresponds to one high tide about every twelve hours.
It is my understanding that the phase information for the curve can be obtained by looking at the (two-argument) arctangent of the value of the Fourier transform at this position (available via the Arg function). In the case of the maximum frequency, the phase is [Pi].
When I look at the original graph, however, it appears that the phase should be -[Pi]/2. That is, the first data point is at near the curve's minimum value. When that value is added into the fitted function, the error is reduced by a factor of twenty.
My questions are: What have I misunderstood about the way that Fourier works? How should I use the Fourier function to fit the data to a sine curve?
BTW, I am aware of this, this and this previous SE questions.
Edit 1:
I ran across an interesting mystery when I tried to refactor
the solution provide below by Ulrich Neumann. First, I wrapped his code into the following function call:
MyFunc[] :=
Module[{J, a, b, om, c, opt},
J = Sum[(a + b Sin[om xy[[1]] + c] - xy[[2]])^2, {xy, samples}];
opt = NMinimize[J, {a, b, c, om}];
{a, b, c, om} /. opt[[2]]
];
Show[
{displacement, amplitude, \[CurlyPhi], \[Omega]} = MyFunc[];
Plot[
displacement + amplitude Sin[\[Omega] t + \[CurlyPhi]],
{t, Min[xd], Max[xd]},
PlotRange -> All
],
ListPlot[samples]
]
After doing so, the produced plot is identical to that shown in his answer. The anomaly comes when I try to do a simple renaming of a local variable in MyFunc:
MyFunc[] :=
Module[{J, a, b, cx, c, opt},
J = Sum[(a + b Sin[cx xy[[1]] + c] - xy[[2]])^2, {xy, samples}];
opt = NMinimize[J, {a, b, c, cx}];
{a, b, c, cx} /. opt[[2]]
];
Note that the variable om has become cx. When the code is now run, the results look much different:
This strongly violates my intuition that changing a local variable name should not affect the computed results. BTW, I did a Remove["*"];` before each execution to ensure a clean environment. Can anyone explain to me what is happening here?
Edit 2:
I tried a somewhat different approach to get around the problems mentioned by the respondants (unequal increments, incomplete cycles, and too few data points). I took the original data and constructed an interpolation function. I found the roots of this function and extracted values at equally spaced intervals, starting at the first root and continuing through a full number of cycles. I then supplied the extracted values to the Fourier function. Unfortunately the results were no better: the phase angle is still off. The bottom line is that I still don't know how to get a meaningful phase angle out of the Fourier function.
A:
I'm unsure, wether the number of samples is sufficient to apply FourierSeries.
But you can identify a sine-function directly:
J = Sum[(a + b Sin[om xy[[1]] + c] - xy[[2]])^2, {xy, samples}];
opt = NMinimize[J, {a, b, c, om}]
(*{0.293904, {a -> 6.79905, b -> 5.9243, c -> 7.19992, om -> 0.515526}}*)
The results fits your samples very good
Show[{Plot[a + b Sin[om t + c] /. opt[[2]], {t, Min[xd], Max[xd]},PlotRange -> All], ListPlot[samples]}]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to print out two way circular linked list?
so I wrote a code for two-way circular linked list (unordered), in C, and I've run into a problem. I have this code for printing out the elements (starting from head):
void ShowListFromHead(List& l){
if(l.head==l.tail){
printf("%d", l.head->value);
return;
}
Element* p;
p=l.head;
while(p->next!= l.head){
printf("%d,", p->value);
p=p->next;}
}
It works fine except for the tail, since the while loop works until it reaches tail (until p->next is the head). So, here's my question: is there a way to show the whole list without excluding any element? It seems that however I formulate the loop, there is always one element left out. Using do/while loop isn't working either. I tried just adding one printf after the loop for the last element, but it messes up the functionality of other functions in the code. I'm trying to fix this for a couple of days and still have no idea how to, so any help is highly appreciated!
EDIT I'm adding the deleteHead function, it appears that maybe the problem isn't entirely in show function.
bool deleteHead(List& l, int &oldHead){
if(l.head!=NULL){
oldHead= l.head->value;
Element *p=l.head;
if(l.head->next!=NULL){
l.head=l.head->next;
l.head->prev=l.tail;
l.tail->next=l.head;
delete p;
return true;
}}
else if(l.head==NULL){
return false;
}
}
A:
Modification to the original code:
void ShowListFromHead(List& l){
if(l.head == 0)
return;
Element* p = l.head;
do{
printf("%d,", p->value);
p=p->next;
}while (p != l.head);
}
or
void ShowListFromHead(List& l){
if(l.head == 0)
return;
Element* p = l.head;
do{
std::cout << p->value << ", " ;
p=p->next;
}while (p != l.head);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
AWS Lambda does not run independently
I am using the nodejs to use AWS Lambda.
As I know each function of lambda is handled in independent and parallel process.
However, following example shows different result than I expected.
// test.js
const now = new Date();
module.exports = () => {
console.log(now);
};
// handler.js
const test = require('./test');
module.exports.hello = async (event, context) => {
test();
return {
statusCode: 200,
body: null
};
};
RESULT:
hello handler log
As I intended, each function was executed independently, so the value of console.log(now) should always be the point at which it was executed.
However, in the actual log, the value of now is continuously recorded at the point of the very first execution - rather than each function’s execution.
The log’s value after 5 minutes was the same.
However, the value changed after 12 hours, but after that, it shows the same problem.
This result gives us serious consideration of how to manage the DB connection.
There are two assumption for each case of lambda’s recycling
If lambda recycles like test.js,
better to use connection pool
also recommends to use a orm such as sequelize which requires initialization
If not,
better to use simple connections and regular queries to quickly consume connections
How can we use lambda within maximum performance?
How can we interpret the test results above?
A:
AWS Lambda creates and reuses the containers, so you need to understand the impact of this practice on the programming model.
The first time a function executes, a new container will be created to execute it.
Let’s say your function finishes, and some time passes, then you call it again. Lambda may create a new container all over again. However, if you haven’t changed the Lambda function code and not too much time has gone by, Lambda may reuse the previous container. This offers performance advantages: Lambda gets to skip the nodejs language initialization, and you get to skip initialization in your code (so you can reuse DB connections, for example); files that you wrote to /tmp last time around will still be there if the container gets reused; anything you initialized globally outside of the Lambda function handler persists.
For more see Understanding Container Reuse in AWS Lambda.
| {
"pile_set_name": "StackExchange"
} |
Q:
CS193P UITabBarController MVC Help on Assignment 4
I'm going through the Stanford CS193P course on iTunesU and am a little puzzled on how to do the recently viewed photos portion on assignment 4.
In the assignment we are to have a tab bar controller with two tabs.
1st tab is a navigation controller that will show a table of places, which will push a table of photo names, which will push a scroll view with a photo
2nd tab is a navigation controller that will show a table of recently viewed photos, which will push a scroll view with a photo.
I have the first tab working, and now when I push the scroll view with the image, I also want to add that photo to an array of recent photos, which MVC should own this recent photos array?
The Tab View Controller (if so the docs say that this class is not intended for sub classing)
The root Table View Controller of the 2nd Tab (how do I pass the current photo to the instance is in another tab) (and quite frankly should the first tab know about the second tab)
The root Table View Controller of the 1st Tab (then how does the second tab pull this data from the first tab?)
Something else
I guess I'm still hazy about MVC's, protocols, delegates and data sources. If you have your solution to this task that I could look through I would greatly appreciate it.
I ended up pushing and pulling the data from user defaults.
Although I'm curious why the tab bar controller is not intended for sub classing. That seems like the most logical place for data to be owned when it is needed by multiple tabs.
A:
After a bunch of additional searching, I didn't find any one consistent way to pass data from tab to tab.
Since we are only storing a relatively small amount of data, I decided to make a class, with class methods (for convenience) to push and pull the data into user defaults.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are all of the effects of a move canceled if the Label is locked and cannot be shifted?
The Legacy's move I know what I am says:
I know what I am: Once per scene, when you defend a teammate you can
shift Savior up and another Label down in addition to any other
benefits from the move, even on a miss. If you do, add 1 Team to the
pool.
What happens in the case that The Legacy has Savior locked? Is the whole move canceled or just the Label shift?
A:
Only the label shift is cancelled
The rules say this about locking labels:
Pick one label and lock it - it can't move up or down. If that Label would shift, ignore that effect in its entirety. (p 118)
What is unclear here is what the "effect" is in this situation. Luckily, the creator Brendan Conway has answered a similar question about the The Janus' second team move which says:
When you share a vulnerability or weakness with someone, tell them a
secret about who you really are. Give them Influence, and shift your
Mundane up and your mask’s Label down.
He was asked:
If either Mundane or the mask label are locked, clearly you ignore the
second clause. But do you ignore the first as well? Is the whole
sentence the "effect" that is being ignored, or just the bit about
shifting labels?
To which he replied:
Just the Label shift! You get the benefits of the Label lock (no shifting Label), but the Influence is separate. Good question!
Extending it to the Legacy's move would bring us to the same conclusion. The Label shift would be canceled but you would still add 1 Team to the pool on a successful defend.
| {
"pile_set_name": "StackExchange"
} |
Q:
GridView does not expand
I am kinda new in android and got such a problem, I am trying to use ExpandableHeightGridView for gridview inside scrollview, but layout doesn't render, some advice please.
It always gives me this error:
Exception raised during rendering: ScrollView can host only one direct child
ExpandableHeightGridView.class:
public class ExpandableHeightGridView extends GridView {
boolean expanded = false;
public ExpandableHeightGridView(Context context)
{
super(context);
}
public ExpandableHeightGridView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ExpandableHeightGridView(Context context, AttributeSet attrs,
int defStyle)
{
super(context, attrs, defStyle);
}
public boolean isExpanded()
{
return expanded;
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// HACK! TAKE THAT ANDROID!
if (isExpanded())
{
// Calculate entire height by providing a very large height hint.
// View.MEASURED_SIZE_MASK represents the largest height possible.
int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
else
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded)
{
this.expanded = expanded;
} }
layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#fed70d"
android:orientation="horizontal">
<ImageView
android:id="@+id/iconBack"
android:layout_width="45dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:paddingBottom="16dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="16dp"
android:src="@drawable/icon_back_white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="20dp"
android:text="Wishlist"
android:textColor="#ac920d"
android:textSize="24sp" />
<LinearLayout
android:id="@+id/myCart"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center|right"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="10dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/addedInCart"
android:layout_width="27dp"
android:layout_height="27dp"
android:layout_gravity="center|right"
android:src="@drawable/icon_menu_cart" />
<TextView
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_marginTop="5dp"
android:background="@drawable/icon_mycart_count"
android:gravity="center_horizontal|center"
android:text="2"
android:textColor="#ffffff"
android:textSize="10dp" />
</LinearLayout>
<TextView
android:id="@+id/myMoneyInMyPocket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|right"
android:layout_marginRight="10dp"
android:text="2000$"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#ad8c22" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#fed70d"
android:orientation="horizontal"
android:weightSum="5.0">
<LinearLayout
android:id="@+id/menuItemStores"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical"
android:paddingTop="8dp">
<ImageView
android:id="@+id/menuIconStores"
android:layout_width="27dp"
android:layout_height="27dp"
android:layout_gravity="center"
android:src="@drawable/icon_menu_logo" />
<TextView
android:id="@+id/menuTextStores"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Stores"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/menuItemInfo"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical"
android:paddingTop="8dp">
<ImageView
android:id="@+id/menuIconInfo"
android:layout_width="27dp"
android:layout_height="27dp"
android:layout_gravity="center"
android:src="@drawable/icon_menu_info" />
<TextView
android:id="@+id/menuTextInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Info"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:background="@drawable/selected_menu_background"
android:orientation="vertical"
android:paddingTop="8dp">
<ImageView
android:id="@+id/menuIconWishlist"
android:layout_width="27dp"
android:layout_height="27dp"
android:layout_gravity="center"
android:src="@drawable/icon_wishlist" />
<TextView
android:id="@+id/menuTextWishlist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Wishlist"
android:textColor="#ffffff"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/menuItemAccount"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical"
android:paddingTop="8dp">
<ImageView
android:id="@+id/menuIconAccount"
android:layout_width="27dp"
android:layout_height="27dp"
android:layout_gravity="center"
android:src="@drawable/icon_menu_account" />
<TextView
android:id="@+id/menuTextAccount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Account"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/menuItemCart"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical"
android:paddingTop="8dp">
<ImageView
android:id="@+id/menuIconCart"
android:layout_width="27dp"
android:layout_height="27dp"
android:layout_gravity="center"
android:src="@drawable/icon_menu_cart" />
<TextView
android:id="@+id/menuTextCart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Cart"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
<View
android:id="@+id/dropShadow"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="@drawable/drop_shadow"
android:cacheColorHint="#f1e7dd"
android:paddingTop="8dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<com.example.utils.ExpandableHeightGridView
android:id="@+id/wishListGridView"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:columnWidth="80dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:isScrollContainer="false"
android:numColumns="2"
android:paddingBottom="@dimen/activity_horizontal_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
</LinearLayout>
A:
This problem is discussed here.
Try adding one more LinearLayout inside your ScrollView as a direct child and put all other layouts/controls inside of the new LinearLayout.
| {
"pile_set_name": "StackExchange"
} |
Q:
I thought the mac mini server also serves as a wifi router?
I just bought a snow leopard mac mini server, everything came as a bundle pretty nice. The snow leopard server software preinstalled on the mac mini too. Only thing I'm not sure about is does this also act as a wifi router? In the back of the box it says "airport extreme wireless networking included", I assumed this means that this can act as a wifi router like an aiport extreme? Is this true? If so, how do I do it?
According to this artcile http://ipliance.com/index.php/eng/Blog/(day)/4/(month)/1/(year)/2010 I can create an ad hoc wifi, but it doesn't say how to do it. Does anyone know?
A:
Airport Extreme is a generic term used by Apple to mean 802.11n pretty much. It has an Airport Extreme card in it. This is just the wireless card. An Airport Extreme base station is the wifi router/media extender/switch that you were expecting.
A:
The only way I know of to create a wireless network in OSX is to use the Internet Sharing Options.
Here are the steps to turn it on:
Apple Menu
System Preferences
Sharing
Click on Internet Sharing (in the left-hand list)
Select your wired connection (Usually Ethernet 1) under "Share your connection from:"
Under "To computers using" select your wireless card.
You can customize the wireless settings by clicking the Wireless Settings button in the lower-right corner of the window.
You won't get WPA encryption (at least not in the desktop version of OSX), but you can use WEP. From there it should act similar to an Airport Base Station.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring JPA - Is there a good way for inner join between entities or the only way is JPQL?
I have the following Entities:
@Entity
public class Organisation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
// ...
}
@Entity
public class Section{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
// ...
@ManyToOne
@JoinColumn(name = "organisation_id", nullable = false)
private Organisation organisation;
}
@Entity
public class SubSection {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
// ...
@ManyToOne
@JoinColumn(name = "section_id")
private Section section;
}
Now I want to find all SubSections by Organisation Id. Right now I am doing it using JPQL at the SubSectionRepository as above:
public interface SubSectionRepository extends JpaRepository<SubSection, Long>{
@Query(value = "SELECT ss.* FROM sub_section as ss INNER JOIN section as s ON ss.section_id = s.id WHERE s.organisation_id = ?1", nativeQuery = true)
List<SubSection> findByOrganisation(Long organisationId);
}
Is there any way that I can make INNER JOIN using the JpaRepository interface?
A:
Did you try this way
subsectionRepository.findBySectionOrganizationId(long organizationId)
| {
"pile_set_name": "StackExchange"
} |
Q:
What does mean in gdb?
I was debugging a C++ code using gdb. The program stopped due to a segmentation fault.
Program received signal SIGSEGV, Segmentation fault.
So I was trying to print out the value of variables to identify where the error is coming from. I have an array called 'ring' of type 'Link **', where Link is a class I defined. Each element in the array points to a 'Link *' variable. Here is the output when I print the first three elements of the 'ring' array.
(gdb) print ring[0]
$13 = (Link *) 0x8125290
(gdb) print ring[1]
$14 = (Link *) 0xb7e80b86 <exp+6>
(gdb) print ring[2]
$15 = (Link *) 0x8132e20
Why am I getting '' after the memory address when printing 'ring[1]'? What does it mean?
EDIT: Im using gdb 7.8 on Arch Linux (3.16.4-1-ARCH)
A:
It means the pointer value is equal to the address of the exp symbol plus 6. It's just the debugger trying to be helpful—whenever it decodes any pointer value, it tries to see if the pointer happens to lie near any known symbols in the object code, and it prints out that information if so.
You might expect to see such notation when examining the disassembly of a function's code, e.g. in branch targets, but as a data pointer, that's very unusual (function pointers would tend to point directly at function symbols, not offset into them).
You almost certainly have some kind of memory corruption bug that just happens to produce that value as a side effect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery - find the next input:text element after a known element
I have an id for a <tr id="tagTR">
Given the above, is it possible to find the next input:text element regardless of any other mark up in between . Is there a jQuery selector that I can use for this scenario?
For example :
<tr id="tagTR">
</tr>
<tr id="tagRed">
<td> </td>
</tr>
<div>
<tr>
<td>
<input> // This is what I want to get to.
</td>
</tr>
</div>
A:
I thought this question was very interesting. It seems others are reading this as, find the next input among siblings. But I read it as - find me the next input no matter what. I don't know if its in a sibling, a parent or a parent's sibling. This is what I came up with based on feedback I received from this question.
http://jsfiddle.net/GesSj/1
//assume you know where you are starting from
var $startElement = $('#foo');
//get all text inputs
var $inputs = $('input[type=text]');
//search inputs for one that comes after starting element
for (var i = 0; i < $inputs.length; i++) {
if (isAfter($inputs[i], $startElement)) {
var nextInput = $inputs[i];
alert($(nextInput).val());
}
}
//is element before or after
function isAfter(elA, elB) {
return ($('*').index($(elA).last()) > $('*').index($(elB).first()));
}
A:
Check it out: moved this into a more complete question and answer
Based on the awesome answer by @mrtsherman, I wrote this more complete solution:
(function( $ ){
$.fn.findNext = function(sel) {
var $result = $(sel).first();
if ($result.length <= 0) {
return $result;
}
$result = [];
var thisIndex = $('*').index($(this));
var selIndex = Number.MAX_VALUE; // Number.MAX_SAFE_INTEGER is not yet fully supported
$(sel).each(function(i,val){
var valIndex = $('*').index($(val));
if (thisIndex < valIndex && valIndex < selIndex) {
selIndex = valIndex;
$result = $(val);
}
});
return $result;
};
})( jQuery );
Then you can use it as this:
$('#tagTR').findNext('input');
I would submit a PR for this on jQuery lib if I knew my code was properly optimized and if it was okay by Mr T Sherman there, meaning I think this should be a core method on jQuery! :P
| {
"pile_set_name": "StackExchange"
} |
Q:
Get automatically notified on audio device connection/disconnection?
Is it possible to get automatically notified whenever the user connects or disconnects an audio device?
A:
In Vista+ you can use Core Audio IMMNotificationClient interface to be notified.
The IMMNotificationClient interface provides notifications when an
audio endpoint device is added or removed, when the state or
properties of an endpoint device change, or when there is a change in
the default role assigned to an endpoint device.
Handling WM_DEVICECHANGE and/or polling is the solution in odler OS versions.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL server PHP PDO COUNT field incorrect or syntax error
I didn't want to post this but last resort.
PHP with MS SQL Server 2008 and I'm getting an error of: [SQLSTATE[07002]: [Microsoft][ODBC Driver 11 for SQL Server]COUNT field incorrect or syntax error
Here is my code:
$server_name = 'sqlserver';
$user = 'user';
$passwd = 'pass';
$sqlString = "INSERT INTO dbo.tbl (UniqID, rideid, stopRatingId, category, ddescription, rating, createdDate) VALUES (?, ?, ?, ?, ?, ?, ?)";
$conn = new PDO("sqlsrv:Server=$server_name;Database=db;ConnectionPooling=0", $user, $passwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare($sqlString);
$sqlVals = "'1', '233', '34', 'Delivery', 'Data Integrity', 'Good', '2018-07-11 08:34:21'";
$stmt->execute(array($sqlVals));
The array shows:
print_r(array($sqlVals));
Array ( [0] => '1', '233', '34', 'Delivery', 'Data Integrity', 'Good', '2018-07-11 08:34:21' )
when I try this, the insert is successful without error:
$stmt->execute(array('1', '233', '34', 'Delivery', 'Data Integrity', 'Good', '2018-07-11 08:34:21'));
Not sure how to correct - any help is much appreciated!
A:
In First example $sqlVals is treated as 1 string value not distinct values
so you can try this
$sqlVals = array('1', '233', '34', 'Delivery', 'Data Integrity', 'Good', '2018-07-11 08:34:21');
$stmt->execute($sqlVals);
| {
"pile_set_name": "StackExchange"
} |
Q:
Can`t use custom restClient for replacing id to _id. Parsing error: Unexpected token
I`m trying to change restClient to support mongoDB(replace id to _id).
This is documantation https://marmelab.com/admin-on-rest/FAQ.html#can-i-have-custom-identifiers-primary-keys-for-my-resources. I tried different variants, but with this one it shows "Unexpected token"
This is the screenshot of error
const convertHTTPResponseToREST = (response, type, resource, params) => {
const { headers, json } = response;
switch (type) {
case GET_LIST:
return {
data: json.map(resource => { ...resource, id: resource._id } ), // here an error with "...resource"
total: parseInt(headers.get('content-range').split('/').pop(), 10),
};
case UPDATE:
case DELETE:
case GET_ONE:
return { ...json, id: json._id };
case CREATE:
return { ...params.data, id: json._id };
default:
return json;
}
};
<Admin
title="Dashboard"
restClient={convertHTTPResponseToREST('/api')}>
</Admin>
When I use jsonServerRestClient() it works. Maybe there is other way to change id to _id?
A:
Edited answer:
You need to replace:
data: json.map(resource => { ...resource, id: resource._id }),
by
data: json.map(resource => ({ ...resource, id: resource._id })),
Note the additional parenthesis around the returned object
| {
"pile_set_name": "StackExchange"
} |
Q:
Generalized Suffix Tree implementation
I've started to write a Generalized Suffix Tree implementation. The overall code is still in an experimental state, though I think it's mature enough to ask for a little review.
I'd like to know how I can make it better, especially on the use of the standard library, the consistency of the code and the design.
A quick example can be found running Live on Coliru.
#include <iostream>
#include <unordered_map>
#include <list>
#include <utility>
#include <limits>
template <typename S, typename C=int>
class SuffixTree {
// Forward declarations of inner classes
struct Node;
typedef S string;
typedef C character;
typedef std::pair<Node*, std::pair<int, int>> ReferencePoint;
// NESTED CLASSES DEFINITIONS
// Node class:
// Contains the suffix link to another Node
// The Transitions "g(s,(k,i)) = s'" to children nodes
//
// Note:
// Transitions are stored in a hashtable indexed by the first substring
// character. A given character can only have at most one Transition in a
// node.
// A Generalized Suffix Tree can contain more than one string at a time
// Each string is labeled with an int. Thus each substring is related to
// an appropriate reference string:
// (ref string id, left ptr, right ptr)
struct MappedSubstring {
int ref_str;
// A substring is a pair of integer (left ptr, right ptr)
// To denote an empty substring, set right ptr < left ptr.
int l;
int r;
MappedSubstring() : ref_str(0), l(0), r(0) {}
MappedSubstring(int ref, int left, int right) :
ref_str(ref),
l(left),
r(right)
{}
bool empty() {
return (this->l > this->r);
}
};
struct Transition {
MappedSubstring sub;
Node *tgt;
Transition() : sub(), tgt(nullptr) {}
Transition(MappedSubstring s, Node *t) : sub(s), tgt(t) {}
};
struct Node {
std::unordered_map<C, Transition> g;
Node *suffix_link;
virtual Transition find_alpha_transition(C alpha) {
auto it = g.find(alpha);
if (g.end() == it) {
return Transition(MappedSubstring(0, 0, -1), nullptr);
}
return it->second;
}
Node() : suffix_link(nullptr) {}
virtual ~Node() {}
};
// Simple workaround for the specific sink node
// This node must have a transition for every char of the input alphabet.
// Instead of creating such transitions, we just make them up through
// an override of `find_alpha_transition`
struct SinkNode : public Node {
virtual Transition find_alpha_transition(C alpha) override {
return Transition(MappedSubstring(0, 0, 0), this->suffix_link);
}
};
// Leaf nodes:
// Leaves must contain an explicit reference to the suffix they represent
// Some strings might have common suffixes, hence the map.
// The suffix link **remains** UNIQUE nonetheless.
struct Leaf : public Node {
// TODO
};
// Base - A tree nested base class
// This clase is here to hide implementation details
// And to handle destruction properly.
//
// The processing (insertion, deletion of strings) is done by SuffixTree,
// Base handles the cleanup.
struct Base {
SinkNode sink;
Node root;
Base() {
root.suffix_link = &sink;
sink.suffix_link = &root;
}
virtual ~Base() {
clean();
}
void clean() {
std::list<Node*> del_list {&root};
while (!del_list.empty()) {
Node *current = del_list.front();
del_list.pop_front();
for (auto it : current->g) {
del_list.push_back(it.second.tgt);
}
if (&root != current) {
delete current;
}
}
}
};
// "OUTER" CLASS MEMBERS
Base tree;
C end_token;
std::unordered_map<int, S> haystack;
std::unordered_map<int, Node*> borderpath_map;
int last_index;
// Given a Node n, a substring kp and a character t,
// test_and_split must return if (n, kp) is the end point.
// If not, and we are in an implicit state, a new state is created.
bool test_and_split(Node *n, MappedSubstring kp, C t, const S& w, Node **r) {
C tk = w[kp.l];
int delta = kp.r - kp.l;
if (0 <= delta) {
Transition tk_trans = n->find_alpha_transition(tk);
MappedSubstring kp_prime = tk_trans.sub;
auto str_prime = haystack.find(kp_prime.ref_str);
if (str_prime->second[kp_prime.l + delta + 1] == t) {
*r = n;
return true;
}
*r = new Node();
Transition new_t = tk_trans;
new_t.sub.l += delta+1;
(*r)->g.insert(std::pair<C, Transition>(
str_prime->second[new_t.sub.l], new_t));
tk_trans.sub.r = tk_trans.sub.l + delta;
tk_trans.tgt = *r;
n->g[tk] = tk_trans;
return false;
} else {
// kp represents an empty substring
Transition t_Transition = n->find_alpha_transition(t);
*r = n;
return (t_Transition.tgt != nullptr);
}
}
// update performs the heart of an iteration:
// It walks the border path from the active point to the end point
// and adds the required Transitions brought by the insertion of
// the string's i-th character.
//
// It returns the end point.
ReferencePoint update(Node *s, MappedSubstring ki) {
Node *oldr = &tree.root;
Node *r = nullptr;
bool is_endpoint = false;
MappedSubstring ki1 = ki;
auto ref_str_it = haystack.find(ki.ref_str);
S w = ref_str_it->second;
ReferencePoint sk(s, std::pair<int,int>(ki.ref_str, ki.l));
ki1.r = ki.r-1;
is_endpoint = test_and_split(s, ki1, w[ki.r], w, &r);
while (!is_endpoint) {
Leaf *r_prime = new Leaf();
r->g.insert(std::pair<C,Transition>(
w[ki.r], Transition(MappedSubstring(
ki.ref_str, ki.r, std::numeric_limits<int>::max()), r_prime)));
if (&tree.root != oldr) {
oldr->suffix_link = r;
}
oldr = r;
sk = canonize(sk.first->suffix_link, ki1);
ki1.l = ki.l = sk.second.second;
is_endpoint = test_and_split(sk.first, ki1, w[ki.r], w, &r);
}
if (&tree.root != oldr) {
oldr->suffix_link = sk.first;
}
return sk;
}
// canonize - Get canonical pair
// Given a Node and a substring,
// This returns the canonical pair for this particular combination
ReferencePoint canonize(Node *s, MappedSubstring kp) {
if (kp.r < kp.l)
return ReferencePoint(s, std::pair<int,int>(kp.ref_str, kp.l));
auto kp_ref_str = haystack.find(kp.ref_str);
int delta;
Transition tk_trans = s->find_alpha_transition(kp_ref_str->second[kp.l]);
while ((delta = tk_trans.sub.r - tk_trans.sub.l) <= kp.r - kp.l) {
kp.l += 1 + delta;
s = tk_trans.tgt;
if (kp.l <= kp.r)
tk_trans = s->find_alpha_transition(kp_ref_str->second[kp.l]);
}
return ReferencePoint(s, std::pair<int,int>(kp.ref_str, kp.l));
}
// get_starting_node - Find the starting node
// @s[in]: The string to insert
// @r[in/out]: The walk starting/ending point
//
// get_starting_node walks down the tree until s does not match anymore
// character.
// @r is updated through this process and contains the reference pair of the
// diverging point between @s and the tree.
// The result '(s,k)' of this function may then be used to resume the Ukkonen's
// algorithm.
int get_starting_node(const S& s, ReferencePoint *r) {
int k = r->second.second;
int s_len = s.length();
bool s_runout = false;
while (!s_runout) {
Transition t = r->first->find_alpha_transition(s[k]);
if (nullptr != t.tgt) {
int i;
auto ref_str = haystack.find(t.sub.ref_str);
for (i=1; (i <= t.sub.r - t.sub.l); ++i) {
if (k+i >= s_len) {
s_runout = true;
break;
}
if (s[k+i] != ref_str->second[t.sub.l+i]) {
r->second.second = k;
return k+i;
}
}
if (!s_runout) {
r->first = t.tgt;
k += i;
}
} else {
return k;
}
}
r->second.second = std::numeric_limits<int>::max();
return std::numeric_limits<int>::max();
}
// deploy_suffixes - Deploy suffixes
// @s[in]: The string to insert in the tree
// @sindex[in]: The index id of @s
//
// deploy_suffixes performs the Ukkonen's algorithm to inser @s into the
// tree.
int deploy_suffixes(const S& s, int sindex) {
ReferencePoint active_point(&tree.root, std::pair<int,int>(sindex, 0));
int i = get_starting_node(s, &active_point);
if (std::numeric_limits<int>::max() == i) {
return -1;
}
for (; i < s.length(); ++i) {
MappedSubstring ki(sindex, active_point.second.second, i);
active_point = update(active_point.first, ki);
ki.l = active_point.second.second;
active_point = canonize(active_point.first, ki);
}
return sindex;
}
void dump_node(Node *n, bool same_line, int padding, MappedSubstring orig) {
int delta = 0;
if (!same_line) {
for (int i = 0; i < padding; ++i) {
std::cout << " ";
}
}
if (!orig.empty()) {
auto s = haystack.find(orig.ref_str);
for (int i = orig.l; i <= orig.r && i <= s->second.length(); ++i) {
std::cout << s->second[i];
}
std::cout << "-";
delta = orig.r - orig.l + 2;
if (orig.r == std::numeric_limits<int>::max()) {
delta = s->second.length() - orig.l + 2;
}
}
same_line = true;
for (auto t_it : n->g) {
dump_node(t_it.second.tgt, same_line, padding + delta, t_it.second.sub);
same_line = false;
}
if (same_line) {
std::cout << "##" << std::endl;
}
}
public:
SuffixTree() : end_token('$'), last_index(0) {
}
int add_string(const S new_string) {
++last_index;
haystack.insert(std::pair<int, S>(last_index, new_string));
if (0 > deploy_suffixes(new_string, last_index)) {
haystack.erase(last_index--);
return -1;
}
return last_index;
}
virtual ~SuffixTree() {
}
void dump_tree() {
dump_node(&tree.root, true, 0, MappedSubstring(0,0,-1));
}
};
A:
You've forgotten to implement the TODO comment in struct Leaf. This may be why your code segfaults with optimizations turned on; I don't know. You might try compiling with clang++ -std=c++14 -fsanitize=address (on a Linux box) to see if that helps track down the misbehavior.
Since the code segfaults, I don't feel guilty about giving merely a superficial review. Here are some style comments, though:
Never ever pass or return objects by const value.
int add_string(const S new_string)
should be either
int add_string(const S& new_string)
or
int add_string(S new_string)
Your code triggers at least two compiler warnings about "signed versus unsigned comparison." I know you've seen the warnings, because you posted the link to Coliru. Why didn't you fix those warnings as soon as the compiler pointed them out?
(The idiomatic way to fix them would be to go through your code and make sure you're using size_t for any variable that's intended to hold an index or byte-count. The lazy-practical way would be to add casts.)
// Base - A tree nested base class
You say that, but then when I look at the code I find that nothing inherits from Base. So it's not a base class.
Also, you should get rid of all the virtual destructors except those that are actually necessary. Classes that aren't used polymorphically shouldn't have any polymorphic methods. (This applies to Base and SuffixTree, obviously; but it also applies to Node and SinkNode as well, because you never use SinkNode polymorphically.)
In general, the code is just way too complicated for what it does. You shouldn't need so many different classes, or probably any virtual methods at all.
On the theme of simplification, your definition of ReferencePoint as std::pair<X, std::pair<Y,Z>> would be better expressed as std::tuple<X,Y,Z>.
MappedSubstring::empty() should be a const member function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Removing some lines according to a little complicated condition
Text file’s content is as follows.
600466 a 37.50 25.28
600466 b 31.13 18.22
600466 c 64.80 61.39
600467 a 38.79 30.00
600467 b 28.73 41.04
600467 c 58.32 61.39
600468 a 33.09 25.28
600468 b 35.57 42.69
600468 c 58.32 60.12
600469 a 36.89 29.80
600469 b 35.57 30.94
600469 c 64.80 62.49
600470 b 37.35 35.02 *
600470 c 58.32 58.32 *
600471 a 29.22 25.47
600471 b 34.74 20.61
600471 c 64.80 62.81
600472 b 31.13 30.28*
600472 c 58.32 62.04 *
I checked some lines with an asterisk.
You can get the first field of a line repeats 3 times(so it appears exactly 3 times consecutively), but some lines are not. I want remove that lines with a few shell commands.
Does anyone have a fancy idea?
(any correction of my poor English would be welcomed. Thank you for advance)
A:
cut -d' ' -f1 file \
| uniq -c \
| grep -v ' 3 ' \
| rev | cut -d' ' -f1 | rev \
| grep -vwFf- file > output
The first line outputs the first column.
The second line counts how often each value was present.
The third line excludes those lines that were present 3 times.
The fourth line removes the counts.
The fifth line excludes the strings from the original file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Upload PySpark RDD into BigQuery
I download a table from BQ into a PySpark RDD as below. How do I upload it again?
dGSConfig = {
'project_id': "project_id",
'bucket': "bucket_id"
}
dBQConfig = {
'gs_config': dGSConfig,
'project_id': "project_id",
'dataset_id': "dataset_id",
'table_id': "table_id"
}
oSc = instantiate_pyspark()
rddData, lsHeadings = get_table_cloud(oSc, dBQConfig) #rddData has a list-of-lists type format
def instantiate_pyspark():
"""instantiate the pyspark RDD stuff"""
import pyspark
oSc = pyspark.SparkContext()
oHadoopConf = oSc._jsc.hadoopConfiguration()
oHadoopConf.get("fs.gs.system.bucket")
return oSc
def get_table_cloud(oSc, dBQConfig):
"""get a table from bigquery via google cloud storage
Config format:
dGSConfig = {'project_id': '', 'bucket': ''}
dBQConfig = {'project_id: '', 'dataset_id': '', 'table_id': ''}
"""
dGSConfig = dBQConfig['gs_config']
dConf = {
"mapred.bq.project.id": dGSConfig['project_id'],
"mapred.bq.gcs.bucket": dGSConfig['bucket'],
"mapred.bq.input.project.id": dBQConfig['project_id'],
"mapred.bq.input.dataset.id":dBQConfig['dataset_id'],
"mapred.bq.input.table.id": dBQConfig['table_id']
}
rddDatasetRaw = oSc.newAPIHadoopRDD(
"com.google.cloud.hadoop.io.bigquery.JsonTextBigQueryInputFormat",
"org.apache.hadoop.io.LongWritable",
"com.google.gson.JsonObject",
conf=dConf
)
import json
lsHeadings = json.loads(rddDatasetRaw.take(1)[0][1]).keys()
rddDataset = (
rddDatasetRaw
.map(lambda t, json=json: json.loads(t[1]).values() )
)
return rddDataset, lsHeadings
A:
3 methods that I used at some point:
1) create local csv, upload to google storage, separate process to get into BigQuery:
llData = rddData.collect()
with open(sCsvPath, 'w') as f:
import csv
oWriter = csv.writer(f)
for lData in llData:
oWriter.writerow(lData)
import subprocess
lsCommand = ['gsutil', 'cp', sCsvPath, sGooglePath]
subprocess.check_output(lsCommand)
2) Use Pandas to upload directly into BigQuery:
import pandas as pd
dfData = pd.DataFrame(llData, columns=lsHeadings)
sProjectID = dBQConfig['sProjectID']
sTargetDataset = dBQConfig['sTargetDataset']
sTargetTable = dBQConfig['sTargetTable']
sTablePath = "{}.{}".format(sTargetDataset, sTargetTable)
dfData.to_gbq(sTablePath, sProjectID, if_exists='replace')
3) Save distributed results straight to storage using pyspark:
#remove previous dir if exists
import subprocess
lsCommand = ['gsutil', 'rm', '-r', sGooglePath]
subprocess.check_output(lsCommand)
rddSave.saveAsTextFile(sGooglePath)
Though none of these are what I wanted originally, and that is a PySpark way of uploading the result straight into BQ.
| {
"pile_set_name": "StackExchange"
} |
Q:
Turn off numbering of sections in LaTeX
I tried to turn off numbering of the sections in my LaTeX documten using \renewcommand\thesection{}.
The numbering did disappear but the title of the section is still indented.
The «Title of the section» should be at the point where the «3» used to be.
How can I do this?
A:
It is much simpler: use the \section*{Some Text} command:
\documentstyle[12pt]{article}
\begin{document}
\section*{Some Text}
Lorum ipsum ...
\end{document}
yields
| {
"pile_set_name": "StackExchange"
} |
Q:
Devexpress SearchLookUpEdit set value from database
I have this code on my Form load for filling my data on my datatable and then populate on my SearchLookupEdit:
FillGrids(oData, "POLIST",
"SELECT [PORecord].[POID],[ItemCode],[PONumber],"
+ "[SiteNo]+' '+[Place]+' '+[Name]+' '+[ScopeOfWork]"
+ "+' '+CAST([DeliveryDate] AS VARCHAR(30))"
+ "+' '+CAST([PRNumber]AS VARCHAR(10))+' '+[Requisitioner] AS Name,"
+ "[UnitPrice],[Quantity],[Unit],Completed,Status"
+ " FROM [Globaltek-Final].[Project].[PORecord]"
+ " INNER JOIN Project.POStatus ON Project.PORecord.POID = Project.POStatus.POID",
CommandType.Text);
cmbPOID.Properties.DataSource = oData.Tables["POLIST"];
cmbPOID.Properties.DisplayMember = "PONumber";
cmbPOID.Properties.ValueMember = "POID";
then by this event:
private void cmbPOID_EditValueChanged(object sender, EventArgs e)
{
//cmbPOID.ShowPopup();
System.Data.DataRow row = gvPOID.GetDataRow(gvPOID.FocusedRowHandle);
try
{
oPOID = row[0].ToString();
txtAmount.Text = row["UnitPrice"].ToString();
}
catch (NullReferenceException ex)
{
MessageBox.Show(ex.Message);
}
}
I can change value of the control and then add it to my database.
Edit: To load my data which i store in database i use this code:
using (SqlCommand xComm = new SqlCommand())
{
xComm.Connection = xConn;
xComm.CommandText =
"SELECT [ProjectID] ,[Year] ,[NTPID] ,Project.MainProjectRecord.[POID],"
+ "[SiteID] ,[SiteName] ,[SiteDetailsID] ,[EquipmentID] ,[RepGlobaltekID],"
+ "[CompletedID] ,[OnGoingID] ,Project.PORecord.POID"
+ " FROM [Globaltek-Final].[Project].[MainProjectRecord]"
+ " INNER JOIN Project.PORecord ON Project.MainProjectRecord.POID = Project.PORecord.POID"
+ " WHERE ProjectID = @recordID";
xComm.CommandType = CommandType.Text;
xComm.Parameters.AddWithValue("@recordID", RecordID);
SqlDataReader xReader = null;
try
{
xConn.Open();
xReader = xComm.ExecuteReader();
while (xReader.Read())
{
txtSiteID.Text = xReader["SiteID"].ToString();
txtSiteName.Text = xReader["SiteName"].ToString();
cmbPOID.EditValue = xReader["POID"].ToString();
cmbPOID.Properties.GetDisplayTextByKeyValue(xReader["POID"].ToString());
//cmbPOID.EditValue = xReader["POID"].ToString();
}
xReader.Close();
}
.....
My problem is how to set or load the value, which I get from database back to the SearchLookupEdit control?
A:
To display value or set a value on a searchlookupedit when binding it into dataset using datatable it should match the searchlookupedit.properties.valuemember to the value you pass into your editvalue something like this..
int value= 12;
searchLookUpEdit1.Properties.ValueMember = "POID";
searchLookUpEdit1.Properties.DisplayMember = "PONumber";
searchLookUpEdit1.EditValue = ValueDisplay(); //it should match the value member
private object ValueDisplay()
{
return value;
}
To my problem i fill first the datatable and populate it into the searchloookupedit. when setting the searchlookupedit.editvalue it is blank it is because on my datatable column it is name "PoID" while on my value member it is "POID". This should fix and must be in the same name so that editvalue will effect. i change "POID" --> "PoID". :D
| {
"pile_set_name": "StackExchange"
} |
Q:
Need module to accept the timestamp from command line
I need a module to accept the following timestamp from command line in Perl.
2010/11/29 09:39:57
I have used the Getopt::Long module to accept the command line options. But it doesn't accept the full
timestamp from command line. It is accepting only date value(2010/11/29) not accepting the time value(09:39:57).
If anyone know the module to solve this issue, kindly let me know.
Thanks in advance.
A:
Just put quotes around the timestamp. It should work fine with Getopt::Long
./script.pl -t '2010/11/29 09:39:57'
A:
If you want them to be separate arguments, you could do something like this:
GetOptions('date=s{2}' => \@date);
my ($day, $time) = @date;
| {
"pile_set_name": "StackExchange"
} |
Q:
Gradle doesn't include test dependencies
I'm trying to run my android tests with Gradle but it does not see my dependencies.
In my build.gradle I have these lines:
dependencies {
compile 'com.android.support:appcompat-v7:19.1.0'
compile 'com.android.support:support-v4:19.1.0'
compile fileTree(dir: 'libs', include: ['*.jar'])
// Android annotations
apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
// ORMLite
compile "com.j256.ormlite:ormlite-android:$ORMLiteVersion"
compile "com.j256.ormlite:ormlite-core:$ORMLiteVersion"
// Google Guava
compile 'com.google.guava:guava:16.0.1'
// Joda Time
compile 'joda-time:joda-time:2.3'
// Dependencies for the `testLocal` task, make sure to list all your global dependencies here as well
testLocalCompile 'junit:junit:4.11'
testLocalCompile 'com.google.android:android:4.1.1.4'
testLocalCompile 'com.android.support:support-v4:19.1.0'
testLocalCompile 'org.robolectric:robolectric:2.1.+'
// Android Studio doesn't recognize the `testLocal` task, so we define the same dependencies as above for instrumentTest
// which is Android Studio's test task
instrumentTestCompile 'junit:junit:4.11'
instrumentTestCompile 'com.google.android:android:4.1.1.4'
instrumentTestCompile 'com.android.support:support-v4:19.1.0'
instrumentTestCompile 'org.robolectric:robolectric:2.1.+'
}
But in my class: instrumentTest/java/.../Test I cannot import i.e. org.junit
Full build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
// replace with the current version of the Android plugin
classpath 'com.android.tools.build:gradle:0.9.2'
// the latest version of the android-apt plugin
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.1'
}
}
apply plugin: 'android'
apply plugin: 'android-apt'
repositories {
mavenCentral()
mavenLocal()
}
configurations {
apt
}
def AAVersion = '3.0.1'
def ORMLiteVersion = '4.46'
def mainPackage = 'pl.grzeslowski.transport'
def paidPackage = mainPackage + '.paid'
def freePackage = mainPackage + '.free'
def testPath = 'src/instrumentTest/'
sourceSets {
testLocal {
java.srcDir file(testPath + 'java')
resources.srcDir file(testPath + 'resources')
}
instrumentTest {
java.srcDir file(testPath + 'java')
resources.srcDir file(testPath + 'resources')
}
}
//configurations {
// testLocalCompile {
// extendsFrom compile
// }
//}
android {
compileSdkVersion 19
buildToolsVersion "19.0.3"
defaultConfig {
minSdkVersion 10
targetSdkVersion 19
versionCode 1
versionName "1.0"
// tests
testPackageName "pl.grzeslowski.transport.tests"
testInstrumentationRunner "android.test.InstrumentationTestRunner"
testHandleProfiling true
testFunctionalTest true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
}
signingConfigs {
debug {
storeFile file("../../debug.keystore")
}
}
buildTypes {
release {
runProguard true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
buildConfigField "java.lang.String", "DATABASE_NAME", "\"transporter\""
buildConfigField "int", "DATABASE_VERSION", "1"
buildConfigField "java.lang.String", "PAID_PACKAGE_NAME", "\"$paidPackage\""
buildConfigField "java.lang.String", "FREE_PACKAGE_NAME", "\"$freePackage\""
}
debug.initWith(buildTypes.release)
debug {
debuggable true
runProguard false
signingConfig signingConfigs.debug
}
}
productFlavors {
free {
packageName freePackage
buildConfigField "pl.grzeslowski.transport.product_flavors.MonetizationType", "MONETIAZATION_TYPE", "pl.grzeslowski.transport.product_flavors.MonetizationType.FREE"
}
paid {
packageName paidPackage
buildConfigField "pl.grzeslowski.transport.product_flavors.MonetizationType", "MONETIAZATION_TYPE", "pl.grzeslowski.transport.product_flavors.MonetizationType.PAID"
}
}
// tell Android studio that the instrumentTest source set is located in the unit test source set
sourceSets {
instrumentTest.setRoot(testPath)
main.java.srcDirs += testPath + 'java'
}
}
dependencies {
compile 'com.android.support:appcompat-v7:19.1.0'
compile 'com.android.support:support-v4:19.1.0'
compile fileTree(dir: 'libs', include: ['*.jar'])
// Android annotations
apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
// ORMLite
compile "com.j256.ormlite:ormlite-android:$ORMLiteVersion"
compile "com.j256.ormlite:ormlite-core:$ORMLiteVersion"
// Google Guava
compile 'com.google.guava:guava:16.0.1'
// Joda Time
compile 'joda-time:joda-time:2.3'
// Dependencies for the `testLocal` task, make sure to list all your global dependencies here as well
testLocalCompile 'junit:junit:4.11'
testLocalCompile 'com.google.android:android:4.1.1.4'
testLocalCompile 'com.android.support:support-v4:19.1.0'
testLocalCompile 'org.robolectric:robolectric:2.1.+'
// Android Studio doesn't recognize the `testLocal` task, so we define the same dependencies as above for instrumentTest
// which is Android Studio's test task
instrumentTestCompile 'junit:junit:4.11'
instrumentTestCompile 'com.google.android:android:4.1.1.4'
instrumentTestCompile 'com.android.support:support-v4:19.1.0'
instrumentTestCompile 'org.robolectric:robolectric:2.1.+'
}
def getSourceSetName(variant) {
return new File(variant.dirName).getName();
}
android.applicationVariants.all { variant ->
def aptOutputDir = project.file("build/source/apt")
def aptOutput = new File(aptOutputDir, variant.dirName)
println "****************************"
println "variant: ${variant.name}"
println "manifest: ${variant.processResources.manifestFile}"
println "aptOutput: ${aptOutput}"
println "****************************"
android.sourceSets[getSourceSetName(variant)].java.srcDirs += aptOutput.getPath()
variant.javaCompile.options.compilerArgs += [
'-processorpath', configurations.apt.getAsPath(),
'-AandroidManifestFile=' + variant.processResources.manifestFile,
'-AresourcePackageName=' + mainPackage,
'-s', aptOutput
]
variant.javaCompile.source = variant.javaCompile.source.filter { p ->
return !p.getPath().startsWith(aptOutputDir.getPath())
}
variant.javaCompile.doFirst {
aptOutput.mkdirs()
}
}
task localTest(type: Test, dependsOn: assemble) {
testClassesDir = sourceSets.testLocal.output.classesDir
android.sourceSets.main.java.srcDirs.each { dir ->
def buildDir = dir.getAbsolutePath().replaceAll(/\\+/, '/').split('/')
buildDir = (buildDir[0..(buildDir.length - 4)] + ['build', 'classes', 'debug']).join('/')
sourceSets.testLocal.compileClasspath += files(buildDir)
sourceSets.testLocal.runtimeClasspath += files(buildDir)
}
classpath = sourceSets.testLocal.runtimeClasspath
}
check.dependsOn localTest
assembleDebug.finalizedBy testLocalClasses
A:
In version 0.9.+ of the Android Gradle Plugin
instrumentTestCompile
was changed to
androidTestCompile
Check out this simple template if you need to see a build.gradle file: Deckard (for Gradle)
| {
"pile_set_name": "StackExchange"
} |
Q:
breakpoint in ISR
is it legal/possible to set a breakpoint inside an ISR? Or this is rather hardware specific?
A:
Yes, it is perfectly legal, but there may be some hiccups due to other ISR's not being fired in time, eg USB.
| {
"pile_set_name": "StackExchange"
} |
Q:
wpf charting X axis doesn't come properly in respect to data and making over crouded
My chart contains a series of 5 line series. Each line with approx 1001 dots. The data of each line is somewhat like this X values from 0 to 1000 and Y values from 0 to 5. My xml is :
<DVC:Chart Name="siReturnChart" Title="Si Return" LegendTitle="Legend" Width="850" Height="450">
<!-- Add Title on Y axis and X Axis -->
<DVC:Chart.Axes>
<DVC:LinearAxis Orientation="Y" Title="Chemical Concentration" HorizontalAlignment="Center" Location="Left" FontWeight="Bold" />
<DVC:CategoryAxis Orientation="X" Title="Production time (days)" Location="Bottom" HorizontalAlignment="Center" FontWeight="Bold" />
</DVC:Chart.Axes>
<DVC:Chart.Series>
<DVC:LineSeries Name="set1layer1Chart" Title="Set 1 Layer 1" IndependentValueBinding="{Binding X}" DependentValueBinding="{Binding Y}" />
<DVC:LineSeries Name="set1layer2Chart" Title="Set 1 Layer 2" IndependentValueBinding="{Binding X}" DependentValueBinding="{Binding Y}" />
<DVC:LineSeries Name="set1layer3Chart" Title="Set 1 Layer 3" IndependentValueBinding="{Binding X}" DependentValueBinding="{Binding Y}" />
<DVC:LineSeries Name="set1layer4Chart" Title="Set 1 Layer 4" IndependentValueBinding="{Binding X}" DependentValueBinding="{Binding Y}" />
<DVC:LineSeries Name="set1layer5Chart" Title="Set 1 Layer 5" IndependentValueBinding="{Binding X}" DependentValueBinding="{Binding Y}" />
<DVC:LineSeries Name="set1wellChart" Title="Set 1 Whole Well" IndependentValueBinding="{Binding X}" DependentValueBinding="{Binding Y}" />
The result of the chart is :
Why the X axis show like this and not the numbers from 0 to 1000 ?? Due to the X axis, the Y axis is also not shown properly and the center of X axis also looks somewhat weird.
Where am I going wrong ? Any idea how do I correct this !!!!
Thanks
A:
Added the following line in DVC::Chart.Axes
<DVC:LinearAxis Orientation="X" Location="Bottom" Interval="100" />
and things got better. The issue was on X Axis numbers from 0 to 1000 was displaying as it wasn't fitting on 1 line so it was coming on 3 lines messing up the display. By adding interval of 100, the dots are coming properly.
| {
"pile_set_name": "StackExchange"
} |
Q:
ant p4changes type="submitted" errors out
I have a directory structure managed by perforce checked out to my local system.
In my ant build targets of my java code. I want surf down into some subdirectory "Subdirectory_Start_here" I want to know what the highest change list information for all files under that directory.
-depot
|
|-Directory A
| |
| |-directory A.1
| |-directory A.2
| | |-Subdirectory_Start_here
| | |
| |-directory A.3
|
|-Directory B
My ant build.xml target
<target name="snapshot" depends="fully_configured,set_revision_slot">
.......
<echo>************************************^^^^^^^^^^^^^^^^^^${env.LOCAL_FS_PATH_TO_P4_MANAGED_DIRECTORY}</echo>
<taskdef resource="com/perforce/p4java/ant/tasks/P4Tasks.properties" classpath="../../../lib/p4ant-2010.1.293250.jar:../../../lib/p4java-2010.1.269249.jar" />
<p4jchanges maxmostrecent="1" client="peterc_peterc-ml" property="platformVersion" longdesc="true" type="submitted" files="${env.LOCAL_FS_PATH_TO_P4_MANAGED_DIRECTORY}/Directory A/directory A.2/Subdirectory_Start_Here/*"/>
<echo>************************************PLATFORM VERSION^^^^^^^^^^^^^^^^^^ ${platformVersion}</echo>
<exec executable="${NF}" dir="${COMMANDLINE_DIR}" failonerror="true">
<arg line="platformVersion:${platformVersion}"/>
</exec>
</target>
According to http://www.perforce.com/perforce/doc.current/manuals/p4ant/p4tasks.html#p4jchanges a type of "submitted" should be allowed. Submitted works on the standalone p4 command. But I am getting.
'submitted' is not a permitted value for com.perforce.p4java.core.IChangelist$Type
If I take type out. The echo does contain a changelist number that is different than if I don't have a files property. So it appears that I get the latest pending or submitted change info from "Subdirectory_Start_Here" and down.
Any thoughts?????
Thanks for any help?
A:
It's a bit daft, but try 'SUBMITTED'.
<p4jchanges maxmostrecent="1" longdesc="true" type="SUBMITTED" />
| {
"pile_set_name": "StackExchange"
} |
Q:
Run Database as Docker container or on a bare metal server?
Databases are designed to consume all memory, CPU and IO available to them.
Is there are good/bad reasons Docker should not be used for databases in production?
May be this question applies to other tools like MOMs Apache Kafka, Apache ActiveMQ etc.
A:
Docker is not a full-scale virtual machine (at least when run on Linux), this is just another process, running on the same kernel, as host machine. Moreover, all docker container processes can be seen in a host machine with ps aux.
The only additional load Docker gives is loading another OS on top of your kernel, but actually most containers are deployed with extremely lightweight stuff like alpine Linux, so I dont think it really has to be taken into consideration.
From another point, having Database (or any other high load service) in a containers gives you following advantages:
Scaling (containers can easily be spread among nodes with container orchestration tools like k8s)
Easy deploy (all dependencies are inside)
Easy upgrade (just replace the container)
Easy testing (no need for db-cleaning procedures in advance of running tests)
and others
So deploying containerized services today is a right practice.
| {
"pile_set_name": "StackExchange"
} |
Q:
“Il est”: what does it mean?
I have been studying French for a few months now.
I am currently studying quelle and quel and I have a question that I don't understand the answer of. So, the question is:
De quelle couleur est votre manteau?
The answer is:
The coat is beige.
So, I wrote:
Mon manteau a beige couleur.
But the answer was:
Il est beige.
From what I understood, il est means he is. So why does it mean it is?
I am not clear on why il est changes its meaning to it is. I would very much appreciate it if you provided me with some clarification as to how the meaning is changed. Basic grammar is what I need!
A:
The crux of your question is in the sentence:
From what I understood, Il est means He is. But, Why does it mean It is?
The fact is that in French there is no “it”. The only French grammatical genders are masculine (applied to male people and animals, and to part of inanimate objects, such as le manteau, il) or feminine (for female people and animals, and the rest of inanimate objects, such as la chaise, elle).
So, for every French noun you have to learn its gender, masculine or feminine, and agree adjectives and pronouns consequently.
A:
The usual answer to the question : De quelle couleur est ton manteau ? is: Il (mon manteau) est beige.
Consider it would be the same in English:
What colour is your coat? → It 's beige.
What you wanted to answer using a (3rd person of avoir): Mon manteau a une couleur beige would not sound idiomatic at all and we never say that in French. And mind the word order.
If you really wanted to mention the word couleur in your answer, you could have gone with: Mon manteau est de couleur beige, which is not usual but possible, and slightly clumsy unless in a very specific context.
We do not repeat the word couleur in the answer because it is considered as part of the question phrase, and you don't always have the question word or phrase in the answer (it's the same in lots of languages).
Quel temps fait-il ? → Il pleut.
Quelle est sa nationalité ? → Elle (il) est français(e).
But it is not always the case, you'll probably soon learn (if you haven't yet) quelle heure est-il ?, to which a French person would answer: Il est 3 heures, keeping the word heures in the answer.
A:
Mon manteau a beige couleur is not correct because a is a form of avoir , not of être. French uses the same verb as English in this sentence : The coat is beige = Le manteau est beige , or with the pronoun : Il est beige. Translating the subject it depends of the gender of the noun in French: le manteau is masculine => il ; la chemise is feminine => elle.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot implicity convert type string to System.Func
When I use method to replace the one value in a string this works, but it doesn't when I set up a function to do it. The method is almost exactly the same as the func below.
The Func gives the error
Cannot implicity string to System.Func<string,int,string,string>.
I know. I know. Use the method if it works and forget the Func. Just want to know why the Func does not work. I have spent some time trying different combinations of types without success. I am a newbie just learning C# for fun(?).
static Func<string,int,string,string> ReplaceNumber(string p, int location, string newValue)
{
StringBuilder sb = new StringBuilder();
sb.Append(p);
sb.Remove(location, 1);
sb.Insert(location, newValue);
string temp = sb.ToString();
return temp; // why doesn't "return sb.ToString()" work
}
static string ReplaceNumber(string p, int location, string newValue)
{
StringBuilder sb = new StringBuilder();
sb.Append(p);
sb.Remove(location, 1);
sb.Insert(location, newValue);
string temp = sb.ToString();
return temp; // why doesn't "return sb.ToString()" work
}
A:
Change the Func like this:
static Func<string, int, string, string> ReplaceNumber = delegate(string p, int location, string newValue)
{
StringBuilder sb = new StringBuilder();
sb.Append(p);
sb.Remove(location, 1);
sb.Insert(location, newValue);
return sb.ToString();
};
and call them like :
string output = ReplaceNumber("Sample", 1, "sample op3"); // op will be "Ssample op3mple"
Note : return sb.ToString(); will work subject to the condition that, the location having an integer value which is a valid location inside the string.
Your static method will also do the same task for you:
static string ReplaceNumber(string p, int location, string newValue)
{
StringBuilder sb = new StringBuilder();
sb.Append(p);
sb.Remove(location, 1);
sb.Insert(location, newValue);
return sb.ToString();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
naked expression at top level
I've been trying to get my head around this parse error on ghci for a while and I can't seem to find an answer online that isn't vague:
enrollment :: Eq a => [a] -> [a] -> Bool
enrollment (x:y:z:xs) (a:b:c:as) - if z == c && y == b then True else False
Parse error: naked expression at top level
Perhaps you intended to use TemplateHaskell
There were no imports to make typos on, and I've spent ages making little tweaks with no progress!
Thanks
A:
The error means that at the top level, you usually only define functions (as well as datatypes, typeclasses, type instances, etc. but let us ignore that for now).
Now you write:
enrollment :: Eq a => [a] -> [a] -> Bool
enrollment (x:y:z:xs) (a:b:c:as) - if z == c && y == b then True else False
-- ^
But as you can see, you did not define a function: indeed there is no equality sign (=). So Haskell interprets this like you want to subtract the body of the function from the head of the function.
We can solve the error with:
enrollment :: Eq a => [a] -> [a] -> Bool
enrollment (x:y:z:xs) (a:b:c:as) = if z == c && y == b then True else False
-- ^
But now there is still a problem: if one of the two lists contains less than three elements, then the function will error. So we better add a rule for such cases:
enrollment :: Eq a => [a] -> [a] -> Bool
enrollment (x:y:z:xs) (a:b:c:as) = if z == c && y == b then True else False
enrollment _ _ = False
Furthermore writing if <expr> then True else False is a quite verbose version of <expr>, so we can rewrite it as:
enrollment :: Eq a => [a] -> [a] -> Bool
enrollment (x:y:z:xs) (a:b:c:as) = z == c && y == b
enrollment _ _ = False
Or we can - like @JonPurdy says - construct two tuples and compare these, like:
enrollment :: Eq a => [a] -> [a] -> Bool
enrollment (x:y:z:xs) (a:b:c:as) = (y, z) == (b, c)
enrollment _ _ = False
| {
"pile_set_name": "StackExchange"
} |
Q:
Conservation of momentum -- arm hitting object
Suppose I strike an object with my hand and I stop moving my hand as soon as I make contact with the object. This sends the object moving in a straight line with some velocity.
Part 1: Is it valid to say the following? (assuming no friction is present)
$m_{hand} * v_{hand} = m_{obj} * v_{obj}$
Part 2: And if friction was present, is it valid to assume that momentum will be conserved in the time delta immediately following the collision (for an infinitesimally small time delta)?
A:
Momentum is not conserved at all here. If you apply a force to stop your hand then you have exerted an external force to the hand-object system. Therefore your equation in part 1 is incorrect, and you can't apply momentum conservation.
If you knew the impulse you provide to your hand to stop it, then you could incorporate that into the change in momentum.
$$p_0=m_hv_h$$
$$p_f=m_{\text {obj}}v_{\text {obj}}$$
$$p_f=p_0+J$$
where $J$ is the additional impulse you have supplied to your hand. Notice how if your hand happened to stop on it's own due to the collision you have $J=0$ and now momentum is conserved.
| {
"pile_set_name": "StackExchange"
} |
Q:
I am having lots of trouble trying to get light to shine through a window
I cannot figure out why the light won't shine through the window in my .blend file (linked here).
I've made the glass transparent using the BDSF Transparent Shader. On top of this, all materials are allowing transparent shadows.
The only thing that works is if I uncheck "Cast Shadows" on the light material. Can anyone help me figure this out? Thank you in advance.
A:
It looks like your problem is in your Glass material, if I make it simple and plug it into the Surface socket of the Output node, it works, so maybe plug this way and revise the node organization:
| {
"pile_set_name": "StackExchange"
} |
Q:
Undefined namespace prefix in Nokogiri and XPath
I am trying to parse Youtube Gdata to see if video with given id exists. But there isn't normal tag but with namespace. On the link http://gdata.youtube.com/feeds/api/videos?q=KgfdlZuVz7I there is tag:
<openSearch:totalResults>1</openSearch:totalResults>
There is namespace openSearch:
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
but I dont know how to deal with it in Nokogiri and Ruby.
Here is part of code:
xmlfeed = Nokogiri::HTML(open("http://gdata.youtube.com/feeds/api/videos?q=#{video_id}"))
xmlfeed.at_xpath("openSearch:totalResults")
It gives error:
Undefined namespace prefix: openSearch:totalResults
A:
I'm not sure why, but it seems that you have to drop the namespace prefix to get the node:
xmlfeed.at_xpath("//totalresults")
Also note that I added the double forward slash, which scopes the search over the whole document (it won't work without it).
UPDATE:
Based on this answer: How do I get Nokogiri to understand my namespaces? I'd guess that the namespace (openSearch:totalResults) is not correctly declared as an attribute on the root node of the document, and hence Nokogiri is just ignoring it, which is why the selector above works but the namespaced one doesn't.
| {
"pile_set_name": "StackExchange"
} |
Q:
Load PNG and read pixels in PHP without GD?
I have a need to read in the exact unaltered pixel data (ARGB) from a truecolour PNG file, preferably from PHP.
Unfortunately the GD library in PHP messes with the alpha channel (reducing it from 8-bit to 7-bit), making it unusable.
I'm currently assuming that my options are either:
Implement my own raw PNG reader to extract the necessary data.
Use some less-broken language/library and call it from the PHP as a shell process or CGI.
I'd be interested to hear any other ideas, though, or recommendations for one way over the other...
Edit: I think #1 is out. I've tried passing the IDAT data stream to gzinflate(), but it just gives me a data error. (Doing the exact same thing, with the exact same data, outside of PHP produces the expected result.)
A:
How about ImageMagick?
<?php
$im = new Imagick("foo.png");
$it = $im->getPixelIterator();
foreach($it as $row => $pixels) {
foreach ($pixels as $column => $pixel) {
// Do something with $pixel
}
$it->syncIterator();
}
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does livehttpheaders show my login and password and how can I prevent it?
I was looking at the livehttpheaders plugin for Firefox and decided to test my login page. I noticed that the parameters shown inside of it contain my login and password. For example:
username=sarmenhb&password=thepassword&submit=Login
in plain English.
I don not see this on other sites.
What can I be doing wrong? I see this as a security flaw. The login page, all it does is validate and log in the user. All fields are ran through mysql_real_escape_string (in case that is relevant).
A:
The information has to get to the server from the client some how. Use SSL if you are worried about security.
Even if you do an MD5 hash in Javascript, this does not help because it is trivial to submit the hash to the login page, and the hash effectively becomes the password. All things are plain text until they, or the transport, is encrypted. POST the variables, use SSL.
To add from my comment below. You may not see the headers for other-sites because they may use AJAX, POST method or another client-side mechanism to authenticate.
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Como reemplazar etiquetas con JavaScript?
Quiero reemplazar unas etiquetas específicas mediante el uso de JavaScript.
La etiquetas que quiero reemplazar son estas <!-- y -->. Entre estas dos etiquetas tengo código que se ejecutará cuando cargue por completo la página.
Este es mi código:
function listen(){
var html = document.getElementsByTagName('html')[0];
[].slice.call(html).forEach(function(el, i){
el.innerHTML.replace('<!--', '<script>').replace('-->', '</script>');
});
}
window.addEventListener('DOMContentLoaded', function(){
listen();
}, false);
A:
Extrae el contenido del script entre <!-- --> usando expresiones regulares, luego, creas un elemento script y lo añades al final del body para su ejecución.
Ejemplo
let scriptText = "<!-- alert('Hola'); -->";
let matches = scriptText.match(/<!--(.*?)-->/);
let code = matches[1].trim();
let script = document.createElement('script');
script.textContent = code;
document.body.appendChild(script);
Sin embargo, no le veo ningún sentido a lo que haces, a no ser que realices algún proceso cuando cargue la página y luego añadas los scripts. Simplemente no hagas eso; si quieres cargar scripts al final del parseo y carga del DOM utiliza el atributo defer en los scripts, como lo indica @Lorthas.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails run a method with the browser closed
I am looking to do something I am not sure is possible in Rails.
I want to execute a method on a button click and then have the method run continuously even with the browser closed until a terminate button is pressed that will stop it.
essentially I am looking how to code:
1) a wrapper that runs a method periodically (every hour)
2) a way to execute the code even with the browser closed
If its relevant I am planning to host on AWS.
A:
You can use Cron Jobs for this purpose. Refer https://launchschool.com/blog/cron-jobs-and-rails
Cron is a piece of software written for *nix-type operating systems to help with the scheduling of recurring tasks.
You can start editing your cron tasks using the crontab command:
crontab -e
Once you’re in the editor, you can start creating and editing cron tasks. To schedule a task, you need to define when the task will run, then define the command to trigger that task.Once you have your schedule defined, you can follow it with any valid bash command.
To run an existing rake task, you can change your directory to your application root, then call the rake task, it would look some thing like this:
0 0 * * * cd /my/app/root && /path/to/bundle exec rake some_task
| {
"pile_set_name": "StackExchange"
} |
Q:
RSpec/Capybara - Testing a page for a table
Does anyone know what matcher I can use to check a page in capybara to see if it contains a html table? And then maybe a matcher to check if that table has specific content inside?
expect(page).to have_content(table)
anything like this? :s
A:
@MilesStanfield answers will work fine if there's only one table on the page. If there are multiples and you want to check that a table containing specific content exists you can do
expect(page).to have_css('table', text: 'content to check')
A:
describe 'table' do
it 'exists' do
expect(page).to have_css 'table'
end
it 'has something inside' do
within 'table' do
expect(page).to have_text 'foo bar'
end
end
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Click event not working while position in css is absolute in jquery
Code is as follows:
$('#navigationLink').on('touchstart', function() {
//debugger;
var navi = $(this).find('p').attr('navi');
if (navi == 'tryit') {
alert('try');
}
if (navi == 'view') {
alert('view');
}
if (navi == 'next') {
alert('next');
}
});
.pos_next {
position: absolute;
bottom: 2%;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="navigationLink" class="col-xs-12 align_center pos_next">
<p class="page_4_titles font_futura_bold clr_black" navi="next">Next Question</p>
</div>
Please check in fiddle for more info https://jsfiddle.net/Lf0f8a4u/
A:
On the computer, you dont have the event touchstart. It is mousedown or click.
$('#navigationLink').on('click', function() {
debugger;
var navi = $(this).find('p').attr('navi');
if (navi == 'tryit') {
alert('try');
}
if (navi == 'view') {
alert('view');
}
if (navi == 'next') {
alert('next');
}
});
.pos_next {
position: absolute;
bottom: 2%;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="navigationLink" class="col-xs-12 align_center pos_next">
<p class="page_4_titles font_futura_bold clr_black" navi="next">Next Question</p>
</div>
Information
If you want to have a compatible version for the computer and the mobile browsers you could use $('').on('touchstart click', function....
The difference between touchstart and click is, that the touchstart is fired directly in mobile browsers as click on your computer. The click-Event has a 300ms delay on the iPhone Safari, because they check if the user want to doubble click, for the zoom gesture.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert a json response into yaml in bash
I read data from a json file with jq. I wanna append the results into a yaml file, but I dont get it working. I am quite new to shell programming. My goal is to append that "users" to an existing "users"-Array in a yaml file.
This is my json file:
#$DEFAULTS_FILE
{"users":
[
{"name":"pi",
"gecos": "Hypriot Pirate",
"sudo":"ALL=(ALL) NOPASSWD:ALL",
"shell": "/bin/bash",
"groups":"users,docker,video",
"plain_text_passwd":"pi",
"lock_passwd":"false",
"ssh_pwauth":"true",
"chpasswd": {"expire": false}
},
{"name":"admin",
"gecos": "Hypriot Pirate",
"sudo":"ALL=(ALL) NOPASSWD:ALL",
"shell": "/bin/bash",
"primary-group": "users",
"groups":"users,docker,adm,dialout,audio,plugdev,netdev,video",
"ssh-import-id":"None",
"plain_text_passwd":"pi",
"lock_passwd":"true",
"ssh_pwauth":"true",
"chpasswd": "{expire: false}",
"ssh-authorized-keys": ["ssh-rsa abcdefg1234567890 [email protected]"]
}
]
}
I filter it with that:
cat $DEFAULTS_FILE | jq .users
I have no clue how to convert that json into a yaml.
My expected result should be:
users:
- name: pi
gecos: "Hypriot Pirate"
sudo: ALL=(ALL) NOPASSWD:ALL
shell: /bin/bash
groups: users,docker,video
plain_text_passwd: pi
lock_passwd: false
ssh_pwauth: true
chpasswd: { expire: false }
- name: admin
primary-group: users
shell: /bin/bash
sudo: ALL=(ALL) NOPASSWD:ALL
groups: users,docker,adm,dialout,audio,plugdev,netdev,video
ssh-import-id: None
I tried to use a second tool called yq which is similar to jq and can write yaml files. But I have no positive progress.
EDIT
I know that I can add content to the yaml with that:
yq w -i "my.yml" "users[+]" "some content"
But I dont know how to merge my json into that.
Any help or hint would be nice, thank you in advance...
A:
I'm not sure what rules you're using to get to your expected result. It seems like you're randomly applying different rules to how the values are being converted.
As I understand it, scalar values are just output as is (with potential encoding), objects are output as key/value pairs, and array objects are output with a - for every item. The indentation associates what's part of what.
So based on those rules if you're going to use jq:
def yamlify:
(objects | to_entries[] | (.value | type) as $type |
if $type == "array" then
"\(.key):", (.value | yamlify)
elif $type == "object" then
"\(.key):", " \(.value | yamlify)"
else
"\(.key):\t\(.value)"
end
)
// (arrays | select(length > 0)[] | [yamlify] |
" - \(.[0])", " \(.[1:][])"
)
// .
;
Then to use it, add it to your .jq file and use it:
$ jq -r yamlify input.json
users:
- name: pi
gecos: Hypriot Pirate
sudo: ALL=(ALL) NOPASSWD:ALL
shell: /bin/bash
groups: users,docker,video
plain_text_passwd: pi
lock_passwd: false
ssh_pwauth: true
chpasswd:
expire: false
- name: admin
gecos: Hypriot Pirate
sudo: ALL=(ALL) NOPASSWD:ALL
shell: /bin/bash
primary-group: users
groups: users,docker,adm,dialout,audio,plugdev,netdev,video
ssh-import-id: None
plain_text_passwd: pi
lock_passwd: true
ssh_pwauth: true
chpasswd: {expire: false}
ssh-authorized-keys:
- ssh-rsa abcdefg1234567890 [email protected]
Here's another variation that aligns the values
def yamlify2:
(objects | to_entries | (map(.key | length) | max + 2) as $w |
.[] | (.value | type) as $type |
if $type == "array" then
"\(.key):", (.value | yamlify2)
elif $type == "object" then
"\(.key):", " \(.value | yamlify2)"
else
"\(.key):\(" " * (.key | $w - length))\(.value)"
end
)
// (arrays | select(length > 0)[] | [yamlify2] |
" - \(.[0])", " \(.[1:][])"
)
// .
;
$ jq -r yamlify2 input.json
users:
- name: pi
gecos: Hypriot Pirate
sudo: ALL=(ALL) NOPASSWD:ALL
shell: /bin/bash
groups: users,docker,video
plain_text_passwd: pi
lock_passwd: false
ssh_pwauth: true
chpasswd:
expire: false
- name: admin
gecos: Hypriot Pirate
sudo: ALL=(ALL) NOPASSWD:ALL
shell: /bin/bash
primary-group: users
groups: users,docker,adm,dialout,audio,plugdev,netdev,video
ssh-import-id: None
plain_text_passwd: pi
lock_passwd: true
ssh_pwauth: true
chpasswd: {expire: false}
ssh-authorized-keys:
- ssh-rsa abcdefg1234567890 [email protected]
A:
function yaml_validate {
python -c 'import sys, yaml, json; yaml.safe_load(sys.stdin.read())'
}
function yaml2json {
python -c 'import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin.read())))'
}
function yaml2json_pretty {
python -c 'import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin.read()), indent=2, sort_keys=False))'
}
function json_validate {
python -c 'import sys, yaml, json; json.loads(sys.stdin.read())'
}
function json2yaml {
python -c 'import sys, yaml, json; print(yaml.dump(json.loads(sys.stdin.read())))'
}
More Bash tricks at http://github.com/frgomes/bash-scripts
A:
With yq version 3.3.2:
cat $DEFAULTS_FILE | yq r -P -
yq a yaml wrapper for jq
r read
-P --prettyPrint
- from STDIN
| {
"pile_set_name": "StackExchange"
} |
Q:
Code First Mapping and Repositories
I am learning the repository pattern and entity framework. I have a question regarding how to map my classes with EF 6 Code First (Existing Db). I know there a lot of questions about this (and I've readed maany of them) but still it's hard for me to understand something, which appears to be "logic" but it's getting me crazy (maybe I have readed too many different opinions...)
Problem (Example)
A table Processes which stores different processes like offer, receipt, order etc.. One of the columns of the table is AddDate which represents when this process was added to the DB.
Now I want to write a library to access this DB to use it in different apps, since it's the core Db in the company.
In the library I want to expose for example a ProcessRepository with a method GetByAddDateRange which returns the processes added after, before or in a given time range.
Question
So, now EF with CodeFirst to an existing DB first generates for me a class for every table with a property for every field. So I have a class Process (from now ProcessEntity) with a property AddDate.
Now in my "domain model", the classes that I want to use in my businnes logic etc, I want to have a class Process (from now ProcessDomain) but this should not have an AddDate property, since it's not important for the "object" or is part of its "properties".
So now how should I do then if I want to get ProcessDomains from my ProcessRepository using this AddDate as condition?
If I use directly ProcessEntity as "domain model" (class generated by EF) and if I understand it right, I have to have a property called AddDate since I will need it in my repo when doing sth like Return _dbContext.Set(Of Process).Where(Func(s)s.AddDate>addDate) or not?
I could (like I've read) have a class ProcessEntity and ProcessDomain and map manually between them in my repository. If I understand it right the repo should return the expected type for the layer above, in this case should return my domainModel class.
Do I understand it?
So for me the first option appears just in close to all scenarios useless, since you have to have specific properties in your classes. so it doesn't matter how I try to look at the problem I always see the need to map manually when using an existing db.
Maybe I am missing sth or understanding sth wrong, so please let me know.
A:
Your EF entities need to have properties for all the database columns you want to use, which includes those you want to filter by. This means that your EF class that corresponds to that table must have that AddDate property. If you want a class that doesn't have that property then you need to define another class.
Many developers/teams will do that anyway. We do mostly ASP.NET MVC work in my office and we have an EF model that corresponds to the database and repositories that return types from that, then we have a service layer that maps those EF entities to data transfer objects (DTOs). The DTOs may map 100% to a corresponding entity but they may also be missing some properties and/or have extra properties. There may also be DTOs that don't correspond to a single entity. We usually use web services between app and database so the DTOs are as efficient as they can be for reduced data transfer.
We have our own tool to generate the DTOs based on the EF model. We will then adjust the generated code as required. If we need to add members, we generally do so in a partial class, so future regeneration doesn't affect that code. If we need to remove members then we have no choice but to edit the generated code. We also use AutoMapper to map data between EF entities and DTOs and vice versa.
| {
"pile_set_name": "StackExchange"
} |
Q:
Skip deploying or stop web application if servlet context initialization fails
In our project, we have several Spring-based modules which are deployed on WAS as web applications. We need to skip deployment, or stop a module if its Spring context initialization fails (i.e. ContextLoaderListener#contextInitialized or DispatcherServlet#init throws an exception). Now, if such happens, app is got deployed and starts, but returns HTTP 500 for any request.
Websphere 8.5.5
Related question: https://stackoverflow.com/a/272747/3459206
A:
This APAR seems to be relevant:
https://www-01.ibm.com/support/docview.wss?uid=swg1PI58875
From the APAR text:
Listener exceptions typically should not stop the application
from starting up for service. However, some applications depend
on their listeners to do the necessary setup before the
application is started for service. Such applications prefer to
stop the application from starting up when there is any
exception in their listeners.
Problem conclusion
The WebContainer Container code was modified to provide an
option to stop the application when there is any listener
exception during the application starting up process.
A new WebContainer custom property needs to be set to enable the
behavior provided by this APAR:
For Full Profiles
com.ibm.ws.webcontainer.stopappstartuponlistenerexception = true
(default is false)
For Liberty Profile
stopappstartuponlistenerexception=true
The fix for this APAR is currently targeted for inclusion in
WebSphere Application Server fix packs 8.5.5.11 and 9.0.0.2,
and Liberty 16.0.0.3
See the APAR link for additional information.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is Eclipse asking to declare strictfp inside enum
I was trying out enum type in Java. When I write the below class,
public class EnumExample {
public enum Day {
private String mood;
MONDAY, TUESDAY, WEDNESDAY;
Day(String mood) {
}
Day() {
}
}
}
Compiler says: Syntax error on token String, strictfp expected.
I do know what's strictfp but would it come here?
A:
You have maybe forgotten to add semicolon after last enum constant.
public enum Element {
FIRE,
WATER,
AIR,
EARTH, // <-- here is the problem
private String message = "Wake up, Neo";
}
A:
The enum constants must be first in the enum definition, above the private variable.
Java requires that the constants be defined first, prior to any fields or methods.
Try:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY;
private String mood;
Day(String mood) {
}
Day() {
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL - Join two queries together efficiently
I have two SQL queries that query different tables and return similar fields:
User - Role - Category - Points
and
User - Role - Category - Target
My queries look like this:
select
acs.UserID,
acs.RoleID,
acs.CategoryID,
sum(acs.Points)
from acs
and
select
tb.UserID,
tb.RoleID,
tb.CategoryID,
sum(
(
(DATEDIFF(dd, (case when @start >= tb.StartDate then @start else tb.StartDate end), (case when @end <= tb.EndDate then @end else tb.EndDate end)) + 1)
) * tb.dailyMed
) as Target
from tb
What I would like to end up with is something like this:
User - Role - Category - Points - Target
Each of the individual queries take less than 1 second to run but when I try to combine them using an inner join it takes over 3 mins to run.
I was hoping there is a more efficient way of doing this but I cannot seem to find one.
*EDIT
My Inner join looks like this
select
acs.UserID,
acs.RoleID,
acs.CategoryID,
sum(acs.Points),
t.Target
from
dbo.ActualCacheSale acs
inner join
(select
tb.UserID,
tb.RoleID,
tb.CategoryID,
sum(
(
(DATEDIFF(dd, (case when @start >= tb.StartDate then @start else tb.StartDate end), (case when @end <= tb.EndDate then @end else tb.EndDate end)) + 1)
) * tb.dailyMed
) as Target
from
dbo.TargetBucket tb
) t on
t.UserID = acs.UserID and
t.RoleID = acs.RoleID and
t.CategoryID = acs.CategoryID
A:
Try
select
aa.UserId,
aa.Roleid,
aa.CategoryId
Sum(aa.Points) as Points,
Sum(aa.Target) as Target
from
(
select
acs.UserID,
acs.RoleID,
acs.CategoryID,
sum(acs.Points) as Points
null as target
from acs
union all
select
tb.UserID,
tb.RoleID,
tb.CategoryID,
0 as points
sum(
(
(DATEDIFF(dd, (case when @start >= tb.StartDate then @start else tb.StartDatee end),
(case when @end <= tb.EndDate then @end else tb.EndDate end)) + 1)
) * tb.dailyMed
) as Target
from tb) as aa
group by
aa.UserId,
aa.Roleid,
aa.CategoryId
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery value change event
I have some code,when I click the button it show me some message.It works on IE good,but dont works on ff or chrome,somebody tell why?Sorry for my poor english.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title> New Document </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
$(function(){
$("#test").bind("input propertychange",function(){
alert("abc");
});
});
function ff()
{
document.getElementById('test').value=Math.random();
</script>
</head>
<body>
<input id="test"></input>
<input id='btn' value="tt" type="button" onclick="ff()" />
</body>
</html>
A:
There are some errors in the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title> New Document </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
$(function () {
$('#btn').on('click', function () {
$('#test').val(Math.random());
$('#test').trigger('change');
}); //missing ending }
$('#test').bind("change paste keyup", function () { // change to a proper listener
alert("abc");
});
});
</script>
</head>
<body>
<input id="test" type="text" value="" />
<!-- ^ Specify a "type" -->
<input id='btn' value="tt" type="button" />
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem. Convergence. Banach space. Weak topology
Let E be a Banach space and let $(X_n)$ be a sequence such that $X_n \rightharpoonup x$ in the weak topology σ(E,E'). Set:
$S_n=\frac{1}{n}\sum_{k=1}^n(-1)^kX_k$
Does $Sn \rightharpoonup x $ in the weak topology σ(E,E')?
========================================
I was thinking that I should write something like this:
let $T \in E'$:
$T(S_n)=\frac{1}{n}\sum_{k=1}^n(-1)^kT(X_k)$
$|T(S_n)-T(x)| \le \frac{1}{n}\sum_{k \le n}(-1)^k |T(X_n)-T(x)| \le \frac{1}{n}\sum_{k \le n}|T(X_n)-T(x)|$
$ \forall \epsilon >0: \exists N$ such that $\forall n>N$:
$|T(X_n)-T(x)| < \epsilon$
$|T(S_n)-T(x)| \le \frac{1}{n}\sum_{k \le N}|T(X_n)-T(x)|+\epsilon$
for n sufficiently large:
$|T(S_n)-T(x)|\le2\epsilon$
=> $Sn \rightharpoonup x $ in the weak topology σ(E,E')
==============================
Is this right? Can you tell me where I am wrong, please?
A:
$S_n$ converge weakly to $0$:
Let $y\in E'$, $\epsilon > 0$ and $n_0$ the rank where $\forall k > n_0, |\langle x_k-x, y \rangle |\leq \epsilon$
Then
$$\langle S_n, y \rangle = \langle \frac{n_0}{n} S_{n_0} + \frac{1}{n} \sum_{k=n_0+1}^n (-1)^k x_k , y \rangle$$
$$ = \frac{1}{n} \langle n_0s_{n_0}, y \rangle + \frac{1}{n}\sum_{k=n_0+1}^n (-1)^k \langle (x_k-x) , y \rangle + \frac{1}{n} \langle \sum_{k=n_0+1}^n (-1)^k x , y \rangle $$
Hence
$$|\langle S_n, y \rangle| \leq \frac{1}{n} C + \epsilon + \frac{1}{n} \langle x,y\rangle \to \epsilon$$
And this is true for every $\epsilon$, so it converge to $0$ for each $y\in E'$
| {
"pile_set_name": "StackExchange"
} |
Q:
Use Ffmpeg on android with linux commands
I'm new programmer for android. I want to use ffmpeg with android.
But my question is can I use ffpmeg on android programming with Linux commands?
for example use this ffmpeg code :
ffmpeg -framerate 1/5 -i img%03d.png -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4
on android programming??
A:
Of course you can. Build your ffmpeg binary with pie support for Android version above API 16.
Use Runtime or Process to execute the commands.
In my old experiences, commands can not access external storage resources. So be careful not directly manipulate external storage files (input or output) in ffmpeg command.
| {
"pile_set_name": "StackExchange"
} |
Q:
Need help passing props to jsx (adobe jsx) file from js file in React
I used create-cep-extension which is an npm built on create-react-app. It builds a bootstrapped extension/panel that works in any of the Adobe CC apps. I'm using mine in Adobe Premiere Pro (PPRO). I can't figure out how to pass props to a function in the index.jsx. This jsx file is Adobe's jsx which has nothing to do with a react jsx file and looks nothing like it. I think it's basically a very old version of javascript.
I can access the jsx file and run the code in it with this command:
loadExtendscript('./extendscript/index.jsx');
I can't pass any props this way though.
I can also execute general jsx commands to PPRO with this command:
evalExtendscript('alert(app.version)')
This is a typical command I would use in an actual jsx file but again I can't figure out how to access a function in the index.jsx and pass props to it.
Here is the code I would like to work:
main.js
let profileObj = {
message: 'ExendScript connected'
};
if (inCEPEnvironment()) {
evalExtendscript('parseObj(' + JSON.stringify(profileObj) + ')')
.then(result => alert(result))
.catch(error => alert(error))
}
index.jsx
function parseObj(obj){
alert(obj.message);
// alert('hello');
};
I've tried everything I could possibly think of over the last 2 weeks without success.
Here is a link to the documentation for create-cep-extension where they show examples for "evalExtendscript" and "loadExtendscript":
https://github.com/fusepilot/create-cep-extension
A:
You need to add your jsx script path in the manifest, using the <ScriptPath> tag inside resources:
<DispatchInfoList>
<Extension Id="com.your.extension.id">
<DispatchInfo >
<Resources>
<ScriptPath>./extendscript/index.jsx</ScriptPath>
Then, you have acces to all inside your index.jsx and included files:
var myParam1 = 25;
var myParam2 = 52;
evalScript(`myFunction(${myParam1}, ${myParam2})`)
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.