text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
python user permissions
I have a question related to user permissions in python. I have a project that uses the file system to store information about specific tasks. Of course this can be edited/deleted if user wants to. Now say a user starts the program using sudo sh start.sh. He then does some operations and data is stored. Now if anyone else or even the same user will start the program without sudo rights when trying to delete/modify those file a permission denied OSError is raised. Now this seems logical but my question is:
Does python offer any way to choose the permissions when writing/creating a file/folder? More precisely can you create files that will be accessible to all users from sudo ?
Does python offer any way to request a users permission when starting the program/ during program execution?
Regards,
Bogdan
A:
Looks like you need os.fchown().
I don't know what you mean by your second question - do you want to ask for a root password and use it to gain access to a file that the normal user wouldn't have access to?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Difference between fastLm and fastLmPure functions from RcppArmadillo
Here is an example:
require(Rcpp)
require(RcppArmadillo)
require(zoo)
require(repmis)
myData <- source_DropboxData(file = "example.csv",
key = "cbrmkkbssu5bn96", sep = ",", header = TRUE)
dolm = function(x) coef(fastLmPure(as.matrix(x[,2]), x[,1]))
myCoef = rollapply(myData, 260, dolm, by.column = FALSE)
summary(myCoef) # 80923 NA's
dolm2 = function(x) coef(fastLm(x[,1] ~ x[,2] + 0, data = as.data.frame(x)))
myCoef2 = rollapply(myData, 260, dolm2, by.column = FALSE)
summary(myCoef2) # 0 NA's
In the example above first method with fastLmPure produces NAs in output, while second method with fastLm doesn't.
Here is the link to fastLm & fastLmPure functions written in R:
https://github.com/RcppCore/RcppArmadillo/blob/master/R/fastLm.R
And here is the link to underlying fastLm function written in C++:
https://github.com/RcppCore/RcppArmadillo/blob/master/src/fastLm.cpp
From these links and RcppArmadillo's documentation it's not obvious to me what causes the difference in outputs? Why there is no NAs in second ouput? And the most important question what routine / part of code prevents NAs from appearance in the second method and how is it implemented?
A:
You are calling two different functions with two different interfaces.
In particular, fastLm() when used via a formula y ~ X will rely on the R internal (and slow !!) functions to create a vector and matrix for you corresponding to fastLm(X, y).
Here is a trivial example setting things up:
R> data(mtcars)
R> lm(mpg ~ cyl + disp + hp + wt - 1, data=mtcars)
Call:
lm(formula = mpg ~ cyl + disp + hp + wt - 1, data = mtcars)
Coefficients:
cyl disp hp wt
5.3560 -0.1206 -0.0313 5.6913
R> fastLm(mpg ~ cyl + disp + hp + wt - 1, data=mtcars)
Call:
fastLm.formula(formula = mpg ~ cyl + disp + hp + wt - 1, data = mtcars)
Coefficients:
cyl disp hp wt
5.356014 -0.120609 -0.031306 5.691273
R> fastLm(mtcars[, c("cyl","disp","hp","wt")], mtcars[,"mpg"])
Call:
fastLm.default(X = mtcars[, c("cyl", "disp", "hp", "wt")], y = mtcars[,
"mpg"])
Coefficients:
cyl disp hp wt
5.356014 -0.120609 -0.031306 5.691273
R>
Now lets add an NA in both the left- and right-hand sides. For ease of indexing we will use an entire row:
R> mtcars[7, ] <- NA
R> lm(mpg ~ cyl + disp + hp + wt - 1, data=mtcars)
Call:
lm(formula = mpg ~ cyl + disp + hp + wt - 1, data = mtcars)
Coefficients:
cyl disp hp wt
5.3501 -0.1215 -0.0332 5.8281
R> fastLm(mpg ~ cyl + disp + hp + wt - 1, data=mtcars)
Call:
fastLm.formula(formula = mpg ~ cyl + disp + hp + wt - 1, data = mtcars)
Coefficients:
cyl disp hp wt
5.350102 -0.121478 -0.033184 5.828065
R> fastLm(na.omit(mtcars[, c("cyl","disp","hp","wt")]), na.omit(mtcars[,"mpg"]))
Call:
fastLm.default(X = na.omit(mtcars[, c("cyl", "disp", "hp", "wt")]),
y = na.omit(mtcars[, "mpg"]))
Coefficients:
cyl disp hp wt
5.350102 -0.121478 -0.033184 5.828065
R>
And here is the kicker: the results are still the same between all methods provided we are consistent about the missing values.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python for item in listA AND listB
This question may be very straightforward and obvious to some people, but for whatever reason I have been unable to find the answer online. I did not find my answer by tinkering with IDLE and trying to understand how it worked. How does a for loop work when multiple items are specified?
a = [1,2,3,4,5]
b = [6,7,8,9,0]
for item in a and b:
print 'why does this setup give the list b but nothing from a?'
Followup Questions:
1) What might happen with other operators, such as or and not?
2) Is this proper usage, even? If so, is it messy, unsafe, or frowned upon?
A:
So, you have two lists:
>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,0]
... and you want to iterate over a and b. So what is a and b, exactly?
>>> a and b
[6, 7, 8, 9, 0]
That might look odd, but it's the result of two facts about Python:
Every object is either True-ish or False-ish. For example:
>>> bool(a)
True
>>> bool(b)
True
In fact, all lists except the empty list [] are True-ish.
Python uses short-circuit evaluation, which means that, for a and b, it:
Checks whether a is True-ish or False-ish
If a is False-ish, evaluates to a
If a is True-ish, evaluates to b
Following those rules, you should be able to see why a and b evaluates to [6, 7, 8, 9, 0] in your case (and following the same rules for combinations of the actual values True and False will show you that short-circuit evaluation does make sense).
If what you want to actually do is iterate trough the items in a and then those in b, you can just use the + operator to concatenate them:
>>> for item in a + b:
... print item,
...
1 2 3 4 5 6 7 8 9 0
As for your followup questions:
What might happen with other operators, such as or and not?
or's rules for short-circuit evaluation are different (you can look them up for yourself or just follow the link above), and in your case a or b evaluates to [1, 2, 3, 4, 5] (in other words, a).
not always returns True for a False-ish value and False for a True-ish value, and since you can't iterate over True or False, you'll get a TypeError.
Is this proper usage, even? If so, is it messy, unsafe, or frowned upon?
Well, there's nothing illegal about it, but as you can see, it doesn't do what you want. There are circumstances where (ab)using short-circuit evaluation to choose an iterable over which to iterate might be helpful, but this isn't one of them.
A:
As you have discovered, for loops don't work when multiple items are specified! What you're getting is an iteration over a and b. a and b returns something True if both items are true; in this case, it's the rightmost operand, since it knows it's true. The correct way to do this is with itertools.chain:
for item in itertools.chain(a, b):
print 'now we get both lists'
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Problems again with child processes in Java
I am on Ubuntu 14.04.
I am trying to run something like ps aux | grep whatevah through Java's class ProcessBuilder. I create two child processes and I make them communicate synchronously, but for some reason, I can not see anything in the terminal.
This is the code:
try {
// What comes out of process1 is our inputStream
Process process1 = new ProcessBuilder("ps", "aux").start();
InputStream is1 = process1.getInputStream();
BufferedReader br1 = new BufferedReader (new InputStreamReader(is1));
// What goes into process2 is our outputStream
Process process2 = new ProcessBuilder("grep", "gedit").start();
OutputStream os = process2.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
// Send the output of process1 to the input of process2
String p1Output = null;
while ((p1Output = br1.readLine()) != null) {
bw.write(p1Output);
System.out.println(p1Output);
}
// Synchronization
int finish = process2.waitFor();
System.out.println(finish);
// What comes out of process2 is our inputStream
InputStream is2 = process2.getInputStream();
BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
String combOutput = null;
while ((combOutput = br2.readLine()) != null)
System.out.println(combOutput);
os.close();
is1.close();
is2.close();
} catch (IOException e) {
System.out.println("Command execution error: " + e.getMessage());
} catch (Exception e) {
System.out.println("General error: " + e.getMessage());
}
(The System.out.println(p1Output); is just for me to check, the print that has to work is the last one, printing the result of ps aux | grep whatevah.)
I've tried several things, the less silly include:
If I comment everything regarding process2, I get the result of ps aux printed on the terminal
If I run the program as is, it prints nothing to the terminal.
If I uncomment the waitFor call, only ps aux gets printed.
If change the commands to, for example, ls -al and ls -al, then both get printed.
I tried changing "aux" for "aux |" but still nothing is printed.
Closed the buffers, also nothing
etc.
Any help will be sorely appreciated.
Cheers!
EDIT
Minutes after accepting Ryan's amazing answer I made my last try to make this code work. And I succeeded! I changed:
while ((p1Output = br1.readLine()) != null) {
bw.write(p1Output);
System.out.println(p1Output);
}
for:
while ((p1Output = br1.readLine()) != null) {
bw.write(p1Output + "\n");
System.out.println(p1Output);
}
bw.close();
and it works! I remember closing the buffer before, so I don't know what went wrong. Turns out you should not stay awake until late trying to make a piece of code work XD.
Ryan's answer down here is still amazing, though.
A:
Given the advice in the comments, the important thing to note is the necessity to use threads to process input/output for a process in order to achieve what you want.
I've used the link posted by jtahlborn and adapted this solution that you might be able to use.
I created a simple example that will list files in a directory and grep through the output.
This example simulates the command ls -1 | grep some from a directory called test with three files somefile.txt someotherfile.txt and this_other_file.csv
EDIT: The original solution didn't really fully use the "pipe" methodology, as it was waiting fully for p1 to finish before starting p2. Rather, it should start them both, and then the output of the first should be piped to the second. I've updated the solution with a class that accomplishes this.
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
// construct a process
ProcessBuilder pb1 = new ProcessBuilder("ls", "-1");
// set working directory
pb1.directory(new File("test"));
// start process
final Process process1 = pb1.start();
// get input/error streams
final InputStream p1InStream = process1.getInputStream();
final InputStream p1ErrStream = process1.getErrorStream();
// handle error stream
Thread t1Err = new InputReaderThread(p1ErrStream, "Process 1 Err");
t1Err.start();
// this will print out the data from process 1 (for illustration purposes)
// and redirect it to process 2
Process process2 = new ProcessBuilder("grep", "some").start();
// process 2 streams
final InputStream p2InStream = process2.getInputStream();
final InputStream p2ErrStream = process2.getErrorStream();
final OutputStream p2OutStream = process2.getOutputStream();
// do the same as process 1 for process 2...
Thread t2In = new InputReaderThread(p2InStream, "Process 2 Out");
t2In.start();
Thread t2Err = new InputReaderThread(p2ErrStream, "Process 2 Err");
t2Err.start();
// create a new thread with our pipe class
// pass in the input stream of p1, the output stream of p2, and the name of the input stream
new Thread(new PipeClass(p1InStream, p2OutStream, "Process 1 Out")).start();
// wait for p2 to finish
process2.waitFor();
} catch (IOException e) {
System.out.println("Command execution error: " + e.getMessage());
} catch (Exception e) {
System.out.println("General error: " + e.getMessage());
}
}
}
This is a class that will be used to simulate a process pipe. It uses some loops to copy bytes around, and could be more efficient, depending on your needs, but for the illustration, it should work.
// this class simulates a pipe between two processes
public class PipeClass implements Runnable {
// the input stream
InputStream is;
// the output stream
OutputStream os;
// the name associated with the input stream (for printing purposes only...)
String isName;
// constructor
public PipeClass(InputStream is, OutputStream os, String isName) {
this.is = is;
this.os = os;
this.isName = isName;
}
@Override
public void run() {
try {
// use a byte array output stream so we can clone the data and use it multiple times
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// read the data into the output stream (it has to fit in memory for this to work...)
byte[] buffer = new byte[512]; // Adjust if you want
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
// clone it so we can print it out
InputStream clonedIs1 = new ByteArrayInputStream(baos.toByteArray());
Scanner sc = new Scanner(clonedIs1);
// print the info
while (sc.hasNextLine()) {
System.out.println(this.isName + " >> " + sc.nextLine());
}
// clone again to redirect to the output of the other process
InputStream clonedIs2 = new ByteArrayInputStream(baos.toByteArray());
buffer = new byte[512]; // Adjust if you want
while ((bytesRead = clonedIs2.read(buffer)) != -1) {
// write it out to the output stream
os.write(buffer, 0, bytesRead);
}
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
// close so the process will finish
is.close();
os.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
This is a class that was created for handling process output, adapted from this reference
// Thread reader class adapted from
// http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html
public class InputReaderThread extends Thread {
// input stream
InputStream is;
// name
String name;
// is there data?
boolean hasData = false;
// data itself
StringBuilder data = new StringBuilder();
// constructor
public InputReaderThread(InputStream is, String name) {
this.is = is;
this.name = name;
}
// set if there's data to read
public synchronized void setHasData(boolean hasData) {
this.hasData = hasData;
}
// data available?
public boolean hasData() { return this.hasData; }
// get the data
public StringBuilder getData() {
setHasData(false); // clear flag
StringBuilder returnData = this.data;
this.data = new StringBuilder();
return returnData;
}
@Override
public void run() {
// input reader
InputStreamReader isr = new InputStreamReader(this.is);
Scanner sc = new Scanner(isr);
// while data remains
while ( sc.hasNextLine() ) {
// print out and append to data
String line = sc.nextLine();
System.out.println(this.name + " >> " + line);
this.data.append(line + "\n");
}
// flag there's data available
setHasData(true);
}
}
The produced output is:
Process 1 Out >> somefile.txt
Process 1 Out >> someotherfile.txt
Process 1 Out >> this_other_file.csv
Process 2 Out >> somefile.txt
Process 2 Out >> someotherfile.txt
To show that piping is really working, changing the command to ps -a | grep usr the output is:
Process 1 Out >> PID PPID PGID WINPID TTY UID STIME COMMAND
Process 1 Out >> I 15016 1 15016 15016 con 400 13:45:59 /usr/bin/grep
Process 1 Out >> 15156 1 15156 15156 con 400 14:21:54 /usr/bin/ps
Process 1 Out >> I 9784 1 9784 9784 con 400 14:21:54 /usr/bin/grep
Process 2 Out >> I 15016 1 15016 15016 con 400 13:45:59 /usr/bin/grep
Process 2 Out >> 15156 1 15156 15156 con 400 14:21:54 /usr/bin/ps
Process 2 Out >> I 9784 1 9784 9784 con 400 14:21:54 /usr/bin/grep
Seeing the grep command in process 2's output shows that the piping is working, with the old solution I posted, this would be missing.
Note the handling of the error stream, which is always good practice, even if you don't plan to use it.
This is a quick and dirty solution that could benefit from some additional thread management techniques, but it should get you what you want.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Would modern body armor be much more useful for creatures that only cared to protect their heart
Let's imagine a supernatural creature that can walk off all damage unless their heart is hit. (think Mr Sinister. The damage is done, it's just not lethal) These creatures exist in modern times, have similar anatomy to us, and any damage to their heart is as lethal as it is to us.
Modern armor is heavy, bulky, and does a poor job of protecting it's wearer from direct gunfire. Even a poorer job against military grade gunfire. Now let's imagine that only the heart matters. Maybe we don't need the large vest anymore? just a single frontal plate made of a much tougher, heavier material? Would anything reasonable for humans to wear be able to stand up to modern assault weapons?
Let's also assume that the shooters know what they are doing. They know where to aim, and if the armor becomes part of "the meta" they would adjust their ammo. Would it still make sense to try to wear protection if you were most likely to face FMJs or whatever the proper counter would be?
Notes. I understand that people can be shot from other angles, but let's assume that most gunfire would be from the front. (that does not mean that if you think that fire coming from the front would actually hit from other angles you should not mention that) I also understand that nothing is going to stand up to a 50cal, let's only consider normal weapons up to assault rifles
A:
I have to point out that modern military body armor does a wonderful job protecting the wearer from direct gunfire, and it is specially designed to defeat military weapons.
The US military uses armor consisting of ridged plates able to defeat 7.62mm rounds, the type commonly used in the AK-47. Surrounding the plates and covering areas not protected by plates, you'll find kevlar panels able to defeat some small caliber weapons, as well as providing protection from shrapnel.
For a creature that only needs to protect its heart, I would still recommend it wears standard military body armor. The ballistic plates are designed to protect the vital organs, but shrinking those plates would expose the heart to gunfire from off-angle attacks (45 degrees). Bullets also tend to bounce around inside the body, so it is possible for a round to hit in the hip and then redirect up through the chest cavity, for example. Because of this, maximizing protection is always a good idea.
I wouldn't expect any type of armor to defeat a .50 though. The sheer kinetic force would likely crush the chest cavity, destroying the heart if you were able to stop it.
Your creatures would gain the advantage of shedding helmets though. A standard plate carrier (unlike a vest, it only carries plates, and doesn't have the bulk or restrictions to movement) equipped with side plates would be my recommendation.
Source: Former Infantryman with some experience relating to body armor and the effects of weapons on the human body.
A:
The problem with limited protection is that your opponent can disable you (shoot your legs and arms off, for example) and then you are unable to defend yourself or get away.
At that point they can, at leisure, get at your heart easily and all you get to do is watch !
This also raises the question of how your creature survive if I can blow it's brains to smithereens. Is it still alive just because it's heart is OK ?
So all things considered, you still want as much protection as possible.
Others have already commented on the limitations of modern body armor, but I'd also add that if a bullet can enter the body, even if it misses the heart, it can still damage the heart.
When a bullet enters the body it does not drill a neat little tunnel, it causes massive shock waves to travel outward from the path of the bullet. This can cause damage to organs not actually directly in the path of the bullet. There's a "nice" demonstration of this effect in this video.
So, again, you want to protect as much as possible, because even near misses are a bad idea.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to arrange files within Xcode application groups?
In X code, I have added 3 groups named
* Classes
* COCOS2d
* Images
Under images, I have added 40 files. But all images under IMAGEs group aren't sorted by name.
I want to sort them, but I didn't found any option.
A:
Select all the images in the group tree under your images group, then choose Edit > Sort > By Name from the menu.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
GCP - moving VMs across projects with the Google Cloud SDK
I want to move some VMs across projects on GCP using the Cloud SDK.
I'd like the process on a high level, and then possibly also some links out to the relevant docs, although I can RTFM when I know what the general high-level steps are.
I think what I want to do is
Create a snapshot
Save it somewhere
Create two Cloud SDK contexts?
Prepare a destination in the context for the new project
Copy the snapshots over to the new context and its associated storage
Rehydrate from the copied snapshot in the new project once everything is copied.
Please help. I'm new with this stuff and want to know whether this is really how it should be done.
Thanks!
A:
You can use this guide
Quick summary of steps needed
Detach the boot disk from the VM that you intend to move by deselecting “Delete boot disk on instance delete” and terminating the VM
Create an image from the detached boot disk
Upload the image to Google Cloud Storage and share it with the new project
Create a custom image under the new project based on the image you uploaded to Google Cloud Storage
Create a new VM instance under the new project based on the custom image
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Number theory!Polynomial modules
From Fermats theorem we know that for every $a \in \mathbb{Z}$, $$a^p\equiv a \mod{p}$$. But the polynomial $x^p$ it is not equal to the polynomial $x$( as a Congruence ). Why?Also when you want to solve a polynomial equation with modules you use that fermats theorem to simplify the polynomial.Doesnt that contradicts that $x^p$ is not equal to $x$. SInce for every $a \in \mathbb{Z}$ $$a^p\equiv a \mod{p}$$
A:
The polynomial $x^2+x$ is always divisible by 2, but as polynomials $x^2+x\not\equiv0\pmod2$ -- for one thing, the degree on the left is different from the degree on the right.
Similarly, even though $x^p-x$ is zero mod $p$ for any $x$, as polynomials, $x^p$ and $x$ are different.
Basically "are equivalent as polynomials" is a fine-grained tool where "are equal at all integer $x$" is courser. If you know that $P(x)$ and $Q(x)$ are equivalent (mod $p$) as polynomials then you know that they take on the same value (mod $p$) for all integer $x$, but you can't conclude the converse.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does our site ask people who haven't upvoted a question in a while to upvote questions?
On other sites, especially those I haven't visited in a while (weeks to months), I'll get a screen-wide drop-down that says something along the lines of, "you haven't upvoted any questions in a while, remember OPs need love too!"
I've not seen that here, but maybe I'm active enough that I never see it. I was prompted to ask this question by a comment left by @willk, encouraging upvotes to the question. Which I thought was a good idea.
I'd create a community promotion ad, but those require too much effort to get the necessary traction.
Do we have an automated "hey! Upvote a question why doncha!" as I've seen on other sites?
A:
The "Welcome back!" banner is only shown under specific circumstances, as outlined here:
The message [...] only appears if
you haven't been seen on the target site for 24 hours, and
you hold a valid user cookie on the target site, and
your account has more than 15 rep on the target site, and
you arrive on a question from a search engine, and
you have not already voted on this particular question and answers
For this message, you're probably not getting it either because you don't ever get to this site via a search engine or you're here every day.
There's also another message:
[I]f you haven’t voted on at least one question in the last 15 votes you cast — you’ll now get the “you haven’t voted on questions in a while; questions need votes too!” reminder every time you vote until you do.
This comes from the Vote For This Question or The Kitten Gets It blog post, which tells us that the best way to get people to vote for questions is blackmail that threatens one or more kittens.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
0 byte file appears when Capturing screen by screencap
I'm having trouble with capturing the screen of un-rooted phone.
I've tried the command at my computer:
adb shell /system/bin/screencap -p /sdcard/out.png
and this worked well.
However, whenever I try to use this command at my application like this :
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] str ={"/system/bin/screencap","-p","/sdcard/out.png"};
try {
Process ps = Runtime.getRuntime().exec(str);
try {
ps.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show(); }
}
I always get 0 byte of out.png. I think there is no error on the source code, but I can't understand why this kind of error occurs.
Please help me with this problem.
Thanks.
A:
Search logcat for somethig like that
perrmission failure: android.permission.READ_FRAME_BUFFER from uid=10113 pid=2934
113 PermissionCache D checking android.permission.READ_FRAME_BUFFER for uid=10113 => denied (294 us)
113 SurfaceFlinger E Permission Denial: can't read framebuffer pid=2934, uid=10113
If you get that error that means permission problem.
Even if you add the READ_FRAME_BUFFER permissions it still wouldn't work.
Generally, That means the application doesn't have permissions to read the framebuffer and must be compiled with system certificate or use su to get root privileges.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Orientability on Manifolds
So I'm having some issues with the definition of orientability. I'll take the case of $\mathbb R$ for now. I know there's supposed to be only 2 orientations on a smooth, connected manifold, and for $\mathbb R$ I'm guessing these arise from the frames $x \rightarrow \frac{\partial}{\partial x}$ and $x \rightarrow -\frac{\partial}{\partial x}$. However what about the frame $x \rightarrow \frac{\partial}{\partial x}$ for $x \geq 0$ and $x \rightarrow -\frac{\partial}{\partial x}$ $x \leq 0$? Or for that matter literally any choice of $\frac{\partial}{\partial x}$ or $-\frac{\partial}{\partial x}$ for whatever $x$? These all give frames because they are clearly global sections and since the dimension is 1 they are bases for each tangent space. Then since the frame is global there is no problem with 2 sections in the frame disagreeing on their orientation as there is just 1 section and we can just define the pointwise orientation on $\mathbb R$ to be the one given by this random assignment.
A:
Your assignment is not continuous around $0$, so it does not define a section. You could try to patch it by mapping $x$ to $x\frac{\partial}{\partial x}$, but then this does not yield a frame at $0$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should we tell students to never replace parts of an expression by their limits when taking a limit?
Let me explain. Suppose we want to calculate $\lim\limits_{n\to\infty} n^2-n$. Since this limit is indeterminate, one way to do it is to write it as $\lim\limits_{n\to\infty} n^2(1-1/n)$. Since $n^2$ goes to infinity and $1-1/n$ goes to $1$, the limit is $\infty$. If this was part of a bigger expression, we would leave it as it is and then at the end look at the limits of all the individual factors. This is the way I've learned it and the way I've always done it.
However, I've noticed that some students do the following:
$$\lim\limits_{n\to\infty} n^2-n = \lim\limits_{n\to\infty} n^2(1-1/n) = \lim\limits_{n\to\infty} n^2 = \infty$$
It is the second equality I'm concerned with. It's not, strictly speaking, wrong: after all, all the limits here are equal to each other. And yet I've been telling them not to do it. My way is to do whatever you want with your expression, and then take all limits in a single step. Now that I think about it, however, I can't find a reason not to let the $1/n$ go to $0$ before taking the rest of the limit: all the equalities are correct, and it simplifies the expression.
Is there any reason why the students should be discouraged from doing this? Or am I just enforcing a rule for no reason?
A:
The important thing is whether students' reasoning is logically valid — and in particular, that they only use the conclusion of a theorem after they've checked that all its hypotheses hold — not whether they follow any particular arbitrary rules or procedures. In this case, the relevant theorem is the following:
Theorem. Let $f$ and $g$ be real-valued functions defined on a subset of the real line, and let $c$ be either a real number or $\pm \infty$. If $\lim_{t \to c} g(t)$ exists and is equal to a nonzero real number, then $\lim_{t \to c} f(t) g(t)$ exists if and only if $\lim_{t \to c} f(t)$ exists, in which case $$\lim_{t \to c} f(t) g(t) = [\lim_{t \to c} f(t)] \cdot [\lim_{t \to c} g(t)].$$
In the example you gave, the problem isn't that the students fail to adhere to the (needless) rule of taking all limits in a single step. The problem is that they omit an important part of the reasoning: since $\lim_{n \to \infty} (1 - 1/n)$ exists and is equal to $1$,
$$
\lim_{n \to \infty} n^2 (1 - 1/n) = (\lim_{n \to \infty} n^2) \cdot [\lim_{n \to \infty} (1 - 1/n)] = (\lim_{n \to \infty} n^2) \cdot 1 = \lim_{n \to \infty} n^2.
$$
In Steven Gubkin's example, neither $n$ nor $1/n$ has a limit that exists and is a nonzero real number, so the theorem doesn't apply. In both cases, the key is to use precise, logically valid reasoning.
A:
To extend the answer by Daniel Hast: One theorem one might want to use is:
If $(a_n)_{n\in\mathbb N}$ and $(b_n)_{n\in\mathbb N}$ are convergent sequences then
$$\begin{align}
\lim_{n\to\infty} (a_n \pm b_n) &= \lim_{n\to\infty} a_n \pm \lim_{n\to\infty} b_n \\
\lim_{n\to\infty} (a_n \cdot b_n) &= \lim_{n\to\infty} a_n \cdot \lim_{n\to\infty} b_n \\
\lim_{n\to\infty} \frac{a_n}{b_n} &= \frac{\lim_{n\to\infty} a_n}{\lim_{n\to\infty} b_n}
\end{align}$$
For the last equation one also needs $\lim_{n\to\infty} b_n \neq 0$.
Now, one can do something like $$\lim_{n\to\infty} \tfrac 1n + \sqrt[n]{4}=\lim_{n\to\infty} \tfrac 1n + \lim_{n\to\infty} \sqrt[n]{4}=0+1=1 \qquad(1)$$
The problem here is, that one applies the above theorem before showing, that the subsequences converge. So a better way to do it would be:
$$\lim_{n\to\infty} \tfrac 1n = 0 \land \lim_{n\to\infty} \sqrt[n]{4} = 1 \Rightarrow \lim_{n\to\infty} \tfrac 1n + \sqrt[n]{4}=\lim_{n\to\infty} \tfrac 1n + \lim_{n\to\infty} \sqrt[n]{4}=0+1=1\qquad (2)$$
(2) is the way to actually write down the proof and (1) is the way to find the proof (This need to be taught to students because they sometimes think that a proof and the solution process are the same). (2) also prevents you from failures because $\lim_{n\to\infty} a_n=\infty$ means, that $(a_n)$ diverges. I say to students:
$\infty$ is no real number. So $\lim_{n\to\infty} a_n=\infty$ means, that one cannot apply the above theorem, because $(a_n)$ diverges. But $\lim_{n\to\infty} a_n=\infty$ sometimes behave in computing with limits like it would converges. For example $\lim_{n\to\infty}(a_n+b_n)=\lim_{n\to\infty}(a_n+b_n)=\lim_{n\to\infty}a_n+\lim_{n\to\infty}b_n$ if one has limits of the form $\infty+\infty$ or $\infty+c$ [Of course one need to introduce the relevant theorems here]. But for $\infty-\infty$ one can never apply the above theorem. So if one limit is $\infty$ one needs to be careful for limits of the form $\infty-\infty$, $\infty\times 0$, $\frac{ \infty}{\infty}$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to filter data based on time values in pandas?
I am new to Python. I am working on pandas package to analyse the work load pattern. My dataframe contains two columns with start and end time of work. I would like to filter rows of dataframe between particular start time and end time. For e.g after 7:00:00 am and before 18:00:00 pm. I tried using the following :
(df['STime'] > '7:00:00') & (df['ETime'] < '18:00:00')
But it returns False for all rows.
A:
You are just comparing the values that's why you are getting only False values
Use this expression with dataframe.
df=df[(df['STime'] > '7:00:00') and (df['ETime'] < '18:00:00')]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Windows batch file to delete directories without video files
I use Plex and when you click the "delete" button, it removes ONLY the video file. If the video file happened to come in a folder and with subtitles, all of that junk will be left behind. So I'm trying to create a scheduled task batch file that will run once a day that will clean up all the left over junk. Here is what I have come up with so far, but it doesn't seem to work as expected :(
rem setting folder variables
set "mymov=E:\Movies\My"
set "hermov=E:\Movies\Her"
set "themmov=E:\Movies\Them"
set folders=%mymov% %hermov% %themmov%
set folder=nul
set delete=no
for %%f in (%folders%) do (
cd /D %%f
for /R %%d in (.) do (
set folder=%%~fd
for %%m in (*.mkv *.mp4 *.wtv *.avi) do (
if exist %%~fd\%%m (
goto :break
else (
set delete=yes
)
)
:break
if %delete%==yes (rd /S /Q %folder%)
set delete=no
)
)
**UPDATE1: With the help of Stephan and Rishav, I have put together a solution:
@echo off
setlocal EnableDelayedExpansion
rem setting folder variables
set "mymov=E:\Movies\My"
set "hermov=E:\Movies\Her"
set "themmov=E:\Movies\Them"
set folders="%mymov%" "%hermov%" "%themmov%"
for %%f in (%folders%) do (
cd /D %%f
for /D %%d in (*.*) do (
set keep=no
for %%m in (mkv mp4 wtv avi) do if exist %%~fd\*.%%m set keep=yes
if !keep!==no rd /S /Q "%%~fd"
)
)
**UPDATE2: I would actually like to expand on this. Is there a way I could just specify a root folder, ex. "E:\Movies", and have it intelligently decipher which is a junk folder and which is a folder that has sub-folder that has legit video files? For instance. If I set one of my movies folders as "E:\Movies\My" and it has a bunch of movie folders with video files in each (unless it's been deleted, then my script would remove that folder), but what about trilogies? Let's say I had "The Hobbit" inside my "E:\Movies\My" folder, but it didn't have a valid video file because it's a container for the 3 Hobbit movies - my script would delete the entire "The Hobbit" folder, in turn, deleting all 3 movies :( I was hoping there was someone out there that knows a ton more than I do about cmd scripting and could drop a knowledge bomb on this. Maybe try to figure out how to work backwards. Like, if it finds a video file, that entire tree is safe and nothing will delete.
A:
reverse your logic:
...
set keep=no
for %%m in (avi mp4 wtf mkv) do if exist "*.%%m" set keep=yes
if "!keep!"=="no" rd /S /Q "%%~fd"
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to split a dataframe column based on a character and retain that character?
I'm having trouble figuring out how to split a dataframe column based on a character and retaining that character string. Here's some example data:
df = pd.DataFrame(
{"sexage" : ['m45', 'f43']}
)
What I'd like is a separate column with the male/female letter and a separate column with the age.
When I do df['sexage'].str.split('m|f', expand=True), there's no value in the first column. But when I do df['sexage'].str.split('(m|f)', expand=True) I get an extra blank column that I don't want.
I know I can select them by position with df['sexage'].str[0] and df['sexage'].str[1:] but I was wondering if I could do this with regex instead.
A:
Try extract
df.sexage.str.extract('(\D+)(\d+)')
output:
0 1
0 m 45
1 f 43
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WCF Service - authentication / SSPI error
When I run my WCF service on my local machine, it works fine. When I deploy the same files to our test server, I get this error when my test client tries to connect to the WCF service:
Security Support Provider Interface (SSPI) authentication failed. The
server may not be running in an account with identity 'host/Server01'.
If the server is running in a service account (Network Service for
example), specify the account's ServicePrincipalName as the identity
in the EndpointAddress for the server. If the server is running in a
user account, specify the account's UserPrincipalName as the identity
in the EndpointAddress for the server.
What does this mean and what area should I be looking to fix? I played around with the web.config identity section, but I'm still unsure what is needed.
A:
I got a similar error before but the message is somewhat different
Right click on the application pool the web site is running under, click on Property then go to the Identity tab. Try to put the "host/Server01" identity in and see if that helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change recessed CFL lights to LED
I have the CFL recessed lights in my kitchen but i want to change them to LED, some one at home depot told me that i will need to change the can. Can someone help or guide me to a video or instructions how can i remove the old can with the new one ?
A:
The question is if the can has a built-in ballast for the florescent light. If the can uses standard screw-in CFL bulbs, then you can just replace the bulb (and probably the trim ring) with a retrofit LED module designed for use in a incandescent can.
On the other hand, if the florescent light has two or four pins to connect into the can, then the can is designed specifically for florescent and includes the ballast for the florescent light. In this case, you will need to replace the can (or modify the can, removing the ballast and rewiring it, which is probably not worth the effort).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
install perl module Net::SSLeay through cpan
I have tried to install Net::SSLeay though cpan to install Email::Send::SMTP::TLS but I am getting the following error.
cpan[5]> install Net::SSLeay
Running install for module 'Net::SSLeay'
Running make for M/MI/MIKEM/Net-SSLeay-1.49.tar.gz
Has already been unwrapped into directory /home/ubuntu/.cpan/build/Net-SSLeay-1.49-VDZ57t
Could not make: Unknown error
Running make test
Can't test without successful make
Running make install
Make had returned bad status, install seems impossible
A:
On ubuntu, try
sudo apt-get install libnet-ssleay-perl
sudo apt-get install libcrypt-ssleay-perl
A:
In Ubuntu 12.04
sudo apt-get install libssl-dev
This resolved the issue for me
A:
On Centos, here's my solution:
sudo yum install perl perl-CPAN perl-Net-SSLeay perl-IO-Socket-SSL
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Minecraft bukkit plugin right click item
I am making a plugin for a server I am developer on and I was developing a plugin!
I wanted to do commands to spawn a boss egg in by doing /boss give lvl <lvl> slime after you did the command it would give you an item that you can right click to spawn the boss in! Well like all new developers stuff doesn't always go the way you think it does. Here's my code I put in for checking if a player right click air or a block with the item SLIME_BALL in the players hand.
@EventHandler
public void onPlayerClicks(PlayerInteractEvent event) {
Player player = event.getPlayer();
Action action = event.getAction();
if (action.equals(Action.RIGHT_CLICK_AIR) || action.equals(Action.RIGHT_CLICK_BLOCK)) {
if (player.getItemInHand().getType() == Material.SLIME_BALL) {
player.sendMessage("You have right click a slime ball!");
}
}
}
A:
Given that you are not seeing any stack traces in your logs, I would concur that your event listener is not registered. Let's say your listener class is called MyEventHandler it would be registered in onEnable() method, something similar to this
class MyPlugin extends JavaPlugin {
...
public void onEnable() {
Listener myEvtHnd = new MyEventHandler();
Bukkit.getPluginManager().registerEvents( myEvtHnd, this );
...
}
}
In general, your handler looks appropriate. PlayerInteractEvent provides a convenience method getItem() that returns the player's current item-in-hand. However, regardless of which method is used, you must check that the ItemStack returned is not null, which will happen if the player has no item in-hand.
@EventHandler
public void onPlayerClicks(PlayerInteractEvent event) {
Player player = event.getPlayer();
Action action = event.getAction();
ItemStack item = event.getItem();
if ( action.equals( Action.RIGHT_CLICK_AIR ) || action.equals( Action.RIGHT_CLICK_BLOCK ) ) {
if ( item != null && item.getType() == Material.SLIME_BALL ) {
player.sendMessage( "You have right click a slime ball!" );
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
could not able to spawn(ssh) using expect
while executing
$expect filename.exp user pwd ip
I got the error
could not execute "ssh -l user ip": no such file or directory
The contents of filename.exp are this:
#!/opt/sfw/bin/expect -D
set OMC_Usr [lindex $argv 0]
set OMC_Pwd [lindex $argv 1]
set OMC_IP [lindex $argv 2]
set cmd "ssh -l $OMC_Usr $OMC_IP"
spawn $cmd
expect "Password:"
send "$OMC_Pwd\r"
interact
help me to proceed
Thanks...
A:
The problem is that spawn needs the command and its arguments passed to it as multiple Tcl arguments, just like the standard Tcl exec command. The fix is to do this directly:
spawn ssh -l $OMC_Usr $OMC_IP
Or, if you prefer (and you've got Tcl 8.5):
set cmd "ssh -l $OMC_Usr $OMC_IP"
spawn {*}$cmd
Or, if you've got 8.4 or before:
eval spawn [lrange $cmd 0 end]
But don't do this:
eval spawn $cmd
because that will break unexpectedly if you have a Tcl metacharacter in the username (or IP address, but that's very unlikely).
Of course, the real fix is to set up an RSA keypair and use ssh-agent to manage it. Like that, you won't need to pass passwords on any command line; that's important because the command line of a process is public information about the process. Really. You can find it out with something trivial like ps -efww (or the equivalent for your OS). Environment variables are just as insecure too; there's an option to ps to show them too.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to extract source table using sql?
I'm trying to write a query that extracts and transforms data from a table and then insert those data into target table and that whole table data should be in single column in target table.below is the query i wrote
INSERT INTO Table2(column1) VALUES
(SELECT * FROM Table1);
table 1
id | ename | email | country |
1 d .. ..
2 v .. ..
3 s .. ..
4 n .. ..
in table2
src_data | src_column | src_tablename
1 eid
2 eid
3 eid
4 eid
d ename
v ename
s ename
n ename
email1 email
email2 email
email3 email
email4 email
country1 country
country2 country
country3 country
country4 country
how can i achieve this ...can you plz suggest me to get this
A:
This:
INSERT INTO table2
SELECT id, 'id', 'table1' FROM table1
UNION SELECT ename, 'ename', 'table1' FROM table1
UNION SELECT email, 'email', 'table1' FROM table1
UNION SELECT country, 'country', 'table1' FROM table1
uses hardcoded names of the columns and the table.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Maximum number of solutions to $f(z)=az+b$ when $f''(z)$ has strictly positive real part $\forall z \in \mathbb{C}$
Suppose $f :\mathbb{C}\to \mathbb{C}$ is a holomorphic function such that the real part of $f''(z)$ is strictly positive $\forall$ $z\in \mathbb{C}$. What is the maximum possible number of solutions to the equation $f (z)=az+b$, as $a$ and $b$ vary over all complex numbers?
The question is asking for the number of solutions to $f(z)=az+b$ given that $f''(z)$ has a strictly positive real part.
At first I take the derivative of $f(z)$, but it doesn't work. Consider for example
$$f(z)=e^z-\left (\frac{z^2}{2!}+\frac{z^3}{3!}+\frac{z^4}{4!}+\cdots \right )$$
which after cancelation give back $f(z)=z+1$.
But differentiating twice gives
$$e^z-1-z-\frac{z^2}{2!}-\frac{z^3}{3!}-\cdots$$
so in the end it gives $0$. However, $f''(z)$ should have a positive real part. I tried thinking but got no example that will give $f''(z)$ a positive real part.
A:
Hint: If $f$ is an entire function and $\Re f''$ is positive then $f''$ is a constant. So $f(z)$ has the form $\alpha+\beta z+\gamma z^{2}$. Also $\Re f''(z)=2 \gamma >0$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pin item when scrolling up
So I have the following screen:
I am looking for a way to make it possible that when the user scrolls up, the widget which contains the progress bar and those 4 data fields (ItemHeader) will scroll up, but the search container (SearchTextField) will be pinned (to the top). Of course when the user will scroll down it should reappear.
All the solutions that I have found address cases where there is a use of tabs. Code added below, Thanks!
Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: MyAppBar(
true,
title: constructParentName,
parentTitle: siteParentName,
),
endDrawer: MyDrawer(),
body: _isLoading
? Center(
child: CircularProgressIndicator(),
)
: Column(
children: <Widget>[
ItemHeader("24", "23", "33"), //This is the widget I would like to hide while scrolling up
SearchTextField(controller),
Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int i) {
return filter == null || filter == ""
? ItemDetail(
itemId: subconstructs[i].subconstructId,
itemName: subconstructs[i].subconstructName,
tasksDone: subconstructs[i].tasksDone,
tasksRejected: subconstructs[i].tasksRejected,
tasksPending: subconstructs[i].tasksPending,
authToken: authToken,
constructParentId: constructParentId,
siteParentId: siteAncestorId,
callBack: () {
return PageEnum.Subconstructs;
},
)
: subconstructs[i]
.subconstructName
.toString()
.toLowerCase()
.contains(filter.toLowerCase())
? ItemDetail(
itemId: subconstructs[i].subconstructId,
itemName: subconstructs[i].subconstructName,
tasksDone: subconstructs[i].tasksDone,
tasksRejected: subconstructs[i].tasksRejected,
tasksPending: subconstructs[i].tasksPending,
authToken: authToken,
constructParentId: constructParentId,
siteParentId: siteAncestorId,
callBack: () {
return PageEnum.Subconstructs;
},
)
: new Container();
},
itemCount: subconstructs.length,
),
),
],
),
bottomNavigationBar: buildBottomNavBar(),
);
A:
I just wrap your header container in one Column Widget.
class ListViewDemo extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return ListViewDemoState();
}
}
class ListViewDemoState extends State<ListViewDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("ListView"),
),
body: Column(
children: <Widget>[
Column(
children: <Widget>[
Container(
color: Colors.red,
child: Text(
" Header1",
style: new TextStyle(fontSize: 16.0, color: Colors.black),
),
),
Container(
color: Colors.blue,
child: Text(
" Header2",
style: new TextStyle(fontSize: 16.0, color: Colors.black),
),
),
],
),
Expanded(
child: ListView.builder(
itemCount: 100,
itemExtent: 50.0,
itemBuilder: (BuildContext context, int index) {
return ListTile(title: Text("$index"));
}),
)
],
));
}
}
Approach 2
import 'package:flutter/material.dart';
import 'dart:math' as math;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('List Demo')),
body: CollapsingList(),
),
);
}
}
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
_SliverAppBarDelegate({
@required this.minHeight,
@required this.maxHeight,
@required this.child,
});
final double minHeight;
final double maxHeight;
final Widget child;
@override
double get minExtent => minHeight;
@override
double get maxExtent => math.max(maxHeight, minHeight);
@override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return new SizedBox.expand(child: child);
}
@override
bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
return maxHeight != oldDelegate.maxHeight ||
minHeight != oldDelegate.minHeight ||
child != oldDelegate.child;
}
}
class CollapsingList extends StatelessWidget {
SliverPersistentHeader makeHeader(String headerText) {
return SliverPersistentHeader(
pinned: true,
delegate: _SliverAppBarDelegate(
minHeight: 150.0,
maxHeight: 150.0,
child: Container(
color: Colors.lightBlue, child: Center(child: Text(headerText))),
),
);
}
@override
Widget build(BuildContext context) {
return CustomScrollView(
slivers: <Widget>[
SliverFixedExtentList(
itemExtent: 150.0,
delegate: SliverChildListDelegate(
[
Container(
color: Colors.red,
child: Center(
child: Text(
"Header Section 1",
style: new TextStyle(fontSize: 16.0, color: Colors.black),
),
),
)
],
),
),
makeHeader('Header Section 2'),
SliverFixedExtentList(
itemExtent: 50.0,
delegate:
SliverChildBuilderDelegate((BuildContext context, int index) {
return new Container(
alignment: Alignment.center,
child: new Text('List item $index'),
);
}, childCount: 100)),
],
);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Send Sms With Genymotion
I'm new android developer and I want to Test an app works with sms service . i want to test my app with Genymotion emulator but I cant find a way to send message !
Is there any way to send and receive SMS with Genymotion emulator ?
A:
No, for the moment, you cannot send/receive SMS with Genymotion.
This is still in the "todo list" of the Genymotion dev team (I'm part of it).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Divide two numbers and return fraction in swift
I know this is a simple question, but i would like to get a result like this.
3/6 = 0.500000
Divide two numbers and return quotient and reminder in a single variable, how can i achieve above in swift ?
A:
To get the quotient and remainder of a division, you can use the quotientAndRemainder(dividingBy:) function.
3.quotientAndRemainder(dividingBy: 6) // (quotient 0, remainder 3)
If you want to get the floating point result of a division, use the / operator on two floating point numbers.
Either do
let result = 3.0 / 6.0 // 0.5
or if your integers are coming from variables, do
let result = Double(3.0) / Double(6.0) // 0.5
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Use Javascript to verify 10 digit phone number
I've got some Javascript code that is trying to verify an entered phone number actually consists of 10 digits, regardless of format. It doesn't seem to be working.
I used similar Javascript code to verify an email address entry, and it worked.
Here is the HTML and JS for the phone number:
Phone Number
<input type="text" name="phone number" id="phone_number" oninput="return validate_number()"><br><br>
<script>
var number = document.getElementById("phone_number");
function validateNumber(val) {
var re = /^\d{3}-\d{3}-\d{4}$/;
console.log(re.test(val))
return re.test(val);
}
function validate_number() {
if (validateNumber(number.value.replace(/\D/g,""))) {
document.getElementById("phone_number_valid").style.visibility = "visible";
document.getElementById("phone_number_valid").style.height = "initial";
document.getElementById("phone_number_invalid").style.visibility = "hidden";
document.getElementById("phone_number_invalid").style.height = "0";
} else {
document.getElementById("phone_number_invalid").style.visibility = "visible";
document.getElementById("phone_number_invalid").style.height = "initial";
document.getElementById("phone_number_valid").style.visibility = "hidden";
document.getElementById("phone_number_valid").style.height = "0";
}
</script>
<div id="phone_number_invalid" class="error_verify">
<p style="color:red">Invalid phone number.</p>
</div>
<div id="phone_number_valid" class="error_verify">
<p style="color:green">Valid phone number.</p>
</div>
And here is the related CSS:
.error_verify {
visibility: hidden;
height:0;
}
A:
You call validateNumber with the input, with all non-digit characters removed:
if (validateNumber(number.value.replace(/\D/g,""))) {
So, your regex, which contains dashes, definitely won't match:
var re = /^\d{3}-\d{3}-\d{4}$/;
Since you don't care about the format at all, it sounds like all you need to check is whether there are exactly 10 digits in the phone number. Either change your regex to just 10 digits:
var re = /^\d{10}$/;
Or, even easier, just check whether the number of digit characters is 10:
if (number.value.match(/\d/g).length === 10)) {
const numInput = document.getElementById("phone_number");
const validDiv = document.querySelector('#phone_number_valid');
const invalidDiv = document.querySelector('#phone_number_invalid');
function validate_number() {
if ((numInput.value.match(/\d/g) || []).length === 10) {
validDiv.style.visibility = "visible";
validDiv.style.height = "initial";
invalidDiv.style.visibility = "hidden";
invalidDiv.style.height = "0";
} else {
invalidDiv.style.visibility = "visible";
invalidDiv.style.height = "initial";
validDiv.style.visibility = "hidden";
validDiv.style.height = "0";
}
}
<input type="text" name="phone number" id="phone_number" oninput="return validate_number()"><br><br>
<div id="phone_number_invalid" class="error_verify">
<p style="color:red">Invalid phone number.</p>
</div>
<div id="phone_number_valid" class="error_verify">
<p style="color:green">Valid phone number.</p>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pip install only pure-python packages
Is there a way to configure pip to install only pure-python packages with pure-python dependencies? I'd like to be able to write a python project that is compatible with both Jython and CPython.
A:
Looking through the file that implements the various command line options for pip and reading the documentation, it would appear that none of these options have the ability to exclude packages based on this criterion. --no-binary and --only-binary seem to deal with compilation in general rather than excluding packages with non-python content.
https://github.com/pypa/pip/blob/de6e4b5c9ea942e6c961066f1ad7f5398b730dfa/pip/cmdoptions.py
The python wheel PEP has metadata that shows what part of the package is a purelib and gets expanded into site-packages, and a Root-Is-Purelib boolean field which seems to indicate that the entire package is pure python. https://www.python.org/dev/peps/pep-0491/ It might be possible to configure pip to exclude everything but wheels and then filter the wheels based on metadata.
The deprecated --use-wheel flag seems to cause pip to prefer wheels, but not to exclude non-wheels. There does not seem to be a way to block wheels from being installed based on their metadata.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how do I know what n(positive integer) is when user types ./a.out -n?
How do I make an command line argument a variable?
That is, for example, how do I know what n(positive integer) is when user types ./a.out -n?
I know I can use strcmp(argv[1], "-1") strcmp(argv[1], "-100") but is there a simpler way to implement this?
A:
You can use
strtol(argv[1]) or atoi(argv[1])
to get the integer no need to compare it as a string and see.
PS: atoi(NULL) will cause UB.
Check the code below:
int main(int argc, char **argv)
{
int n;
if( argc >2)
return 1;
if(argv[1][0] == '-')
n = atoi(argv[1] +1);
else
n= atoi(argv[1]);
printf("%d\n",n);
return 0;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JQuery find last child in given div
I want to develop a web application where you can specify a question and then provide a choice of multiple answers. I require extra answer 'boxes' to be added when the plus button is clicked, but only added to the specific formRow (see code).
I have tried the JQuery last function but it will always add after the answer box with id=4.
HTML:
<div class="formRow">
<a href="#" title="" class="Remove smallButton" style="float:right;"><img src="images/icons/color/cross.png" alt="" /></a>
<label>Multiple Choice: </label>
<div class="formRight" style="height:28px;">Question1: <input type="text" class="MCQuestion" QID="'+QID+'" /><a href="#" title="" class="AddAns smallButton" style="margin-left:5px;padding: 1px 3px;"><img src="images/icons/color/plus.png" alt="" /></a></div>
<div class="formRight MCAns" id="1">Answer 1: <input type="text" class="MCAnswer"/><a href="#" title="" class="DelAns smallButton" style="margin-left:5px;padding: 1px 3px;"><img src="images/icons/color/cross.png" alt="" /></a></div>
<div class="formRight MCAns" id="2">Answer 2: <input type="text" class="MCAnswer"/><a href="#" title="" class="DelAns smallButton" style="margin-left:5px;padding: 1px 3px;"><img src="images/icons/color/cross.png" alt="" /></a></div>
<div class="clear"></div>
</div>
<div class="formRow">
<a href="#" title="" class="Remove smallButton" style="float:right;"><img src="images/icons/color/cross.png" alt="" /></a>
<label>Multiple Choice2: </label>
<div class="formRight" style="height:28px;">Question2: <input type="text" class="MCQuestion" QID="'+QID+'" /><a href="#" title="" class="AddAns smallButton" style="margin-left:5px;padding: 1px 3px;"><img src="images/icons/color/plus.png" alt="" /></a></div>
<div class="formRight MCAns" id="3">Answer 1: <input type="text" class="MCAnswer"/><a href="#" title="" class="DelAns smallButton" style="margin-left:5px;padding: 1px 3px;"><img src="images/icons/color/cross.png" alt="" /></a></div>
<div class="formRight MCAns" id="4">Answer 2: <input type="text" class="MCAnswer"/><a href="#" title="" class="DelAns smallButton" style="margin-left:5px;padding: 1px 3px;"><img src="images/icons/color/cross.png" alt="" /></a></div>
<div class="clear"></div>
</div>
Javascript
$(document).ready(function() {
$("body").on("click", ".AddAns", function(event) {
$(".MCAns").last().after("New Answer Optition"); //Tried this first
$(".MCAns :last-child").after("New Answer Optition"); //Then this
});
});
A:
Use this :
$(document).ready(function() {
$("body").on("click", ".AddAns", function(event) {
$(this).closest('.formRow').find('.MCAns').last().after("New Answer Optition");
});
});
The probleme with your code is that you are selecting every MCAns and take the last one. You should take the last of .formRow add button you clicked.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Saving an XML file to a specific folder
I am trying to write code that will save an XML file to a location, so I attempted using
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"settings.xml");
which returns the directory "C:\Users\myName\Desktop\ProgramFolder\assembly\settings.xml" I am using this code to give me a general idea of where the user is executing my program since it is a portable program. Now knowing where the program is being executed I want to create my file in the directory "ProgramFolder\Settings" which already exists. I am just not sure how I can go about doing this
A:
Try this
string propertyFile = @"C:\Users\myName\Desktop\ProgramFolder\assembly\settings.xml";
string propertyFolder = propertyFile.Substring(0, propertyFile.LastIndexOf("\\") + 1);
string newXML = propertyFolder + "newXML.xml";
//XmlDocument doc name of xml document in code
doc.Save(newXML);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NDB Expando Model with dynamic TextProperty?
I'm trying to do:
MyModel({'text': db.Text('text longer than 500 byets')})
But get:
BadValueError: Indexed value fb_education must be at most 500 bytes
I'm thinking this is just a carry over from this issue with the old db api.
https://groups.google.com/forum/?fromgroups#!topic/google-appengine/wLAwrjtsuks
A:
First create entity dynamically :
kindOfEntity = "MyTable"
class DynamicEntity(ndb.Expando):
@classmethod
def _get_kind(cls):
return kindOfEntity
then after to assign Text Properties run time/dynamically as shown below
dbObject = DynamicEntity()
key = "studentName"
value = "Vijay Kumbhani"
textProperties = ndb.TextProperty(key)
dbObject._properties[key] = {}
dbObject._values[key] = {}
dbObject._properties[key] = textProperties
dbObject._values[key] = value
dbObject.put()
then after key properties assign with Text properties
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Monad transformers with identity monad
What's the point in using a Monad transformer with the Identity monad rather than just using the "standard" version of the transformer?
Is it more flexible?
A:
Back in mtl 1.0 we had both
newtype State s a = State { runState :: s -> (a, s) }
and
newtype StateT s m a = StateT { runStateT :: s -> m (a, s) }
However, this meant anybody who had to implement instances for things like MonadState wound up duplicating effort.
In transformers (and the now defunct monads-fd and monads-tf) Ross Paterson decided to use the simpler approach of only offering the latter and using Identity as the base monad.
This led to reduced implementation effort in maintaining the mtl and removed the fact that there were two different ways to implement the State monad. It did, however, make the internals of the mtl harder to teach, because you need to understand the transformers versions right out of the gate and don't get the simplified version as training wheels.
When the old mtl was retired and monads-fd became mtl 2.0, using the existing transformers this design decision was carried over.
I personally liked having the separate simple monads for pedagogical purposes at least, but there were far more people on the other side of the debate.
A:
From the Documentation: Computationally, there is no reason to use the Identity monad instead of the much simpler act of simply applying functions to their arguments. The purpose of the Identity monad is its fundamental role in the theory of monad transformers. Any monad transformer applied to the Identity monad yields a non-transformer version of that monad.
As i understand it, getting the non-transformer version of a monad from a monad transformer by applying the identity monad is exactly the thing that the identity monad is there for. There is no advantage over just using the non-transformer monad, yet sometimes you have to use a monad transformer, e.g. when a function you want to use requires it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove hyperlinks in uiwebview
I am trying to load a html page through UIWebview.I need to disable all the hyperlinks in webview and make its color to normal text color i.e i need to disable webpage detection.Is that possible
Thanks in advance
A:
Use this UIWebView method
– stringByEvaluatingJavaScriptFromString:
To use Javascript.
Then use "document.getElementsByTagName('a')" to get an Array of elements and do want you want (change the href, change the color etc.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
why does sparklyr::spark_apply fail when specifying numeric schema
Given a spark connection sc
iris_spk <- copy_to(sc, iris)
Next I'll take a silly example for spark_apply
iris_spk %>%
spark_apply(
function(x) {
data.frame(A=c("a", "b", "c"), B=c(1, 2, 3))
},
group_by = "Species",
columns = c("A", "B"),
packages = FALSE
)
# # Source: table<sparklyr_tmp_3e96258604cd> [?? x 3]
# # Database: spark_connection
# Species A B
# <chr> <chr> <dbl>
# 1 versicolor a 1.00
# 2 versicolor b 2.00
# 3 versicolor c 3.00
# 4 virginica a 1.00
# 5 virginica b 2.00
# 6 virginica c 3.00
# 7 setosa a 1.00
# 8 setosa b 2.00
# 9 setosa c 3.00
So far, so good. However https://stackoverflow.com/a/46410425/1785752 suggests that I can improve performance by specifying an output schema instead of just output column names. So I tried:
iris_spk %>%
spark_apply(
function(x) {
data.frame(A=c("a", "b", "c"), B=c(1, 2, 3))
},
group_by = "Species",
columns = list(A="character",
B="numeric"),
packages = FALSE
)
But then things go wrong:
Error: org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 26.0 failed 4 times, most recent failure: Lost task 1.3 in stage 26.0 (TID 133, ml-dn38.mitre.org, executor 3): java.lang.RuntimeException: Error while encoding: java.lang.RuntimeException: java.lang.String is not a valid external type for schema of double
if (assertnotnull(input[0, org.apache.spark.sql.Row, true]).isNullAt) null else staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString, validateexternaltype(getexternalrowfield(assertnotnull(input[0, org.apache.spark.sql.Row, true]), 0, A), StringType), true) AS A#256
if (assertnotnull(input[0, org.apache.spark.sql.Row, true]).isNullAt) null else validateexternaltype(getexternalrowfield(assertnotnull(input[0, org.apache.spark.sql.Row, true]), 1, B), DoubleType) AS B#257
at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder.toRow(ExpressionEncoder.scala:290)
at org.apache.spark.sql.SparkSession$$anonfun$3.apply(SparkSession.scala:581)
at org.apache.spark.sql.SparkSession$$anonfun$3.apply(SparkSession.scala:581)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:409) at scala.collection.Iterator$$anon$11.next(Iterator.scala:409)
... and so on
Am I specifying the schema incorrectly?
A:
Ah! I think that the group_by column does not inherit it's schema from the input data frame, but needs to be declared along with the rest. I just tried
iris_spk %>%
spark_apply(
function(x) {
data.frame(A=c("a", "b", "c"), B=c(1, 2, 3))
},
group_by = "Species",
columns = list(Species="character",
A="character",
B="numeric"),
packages = FALSE
)
which worked (same result as the first try above)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why ptrace doesn't attach to process after setuid?
I have a problem with my Linux daemon program. It starts with root privileges, does some configuration, then permanently drops privileges by switching to some user and group and continues working. The switch to the non-privileged user is done like this:
void switch_to_user_group(std::string const& username, std::string const& groupname)
{
// Switch to user/group
gid_t gid = getgid();
if (!groupname.empty())
{
gid = get_group_id(groupname);
if (0 != setgid(gid))
{
std::cout << "Failed to switch to group " << gid << std::endl;
std::abort();
}
}
if (!username.empty())
{
uid_t uid = get_user_id(username);
if (initgroups(username.c_str(), gid) != 0)
{
std::cout << "initgroups failed" << std::endl;
std::abort();
}
if (0 != setuid(uid))
{
std::cout << "Failed to switch to user " << uid << std::endl;
std::abort();
}
}
}
The switch performs correctly, I can see the process in ps and top running under my user. The problem is that I can't attach to this process from gdb, even after it has dropped the privileges. The output is:
Attaching to process 15716
Could not attach to process. If your uid matches the uid of the target
process, check the setting of /proc/sys/kernel/yama/ptrace_scope, or try
again as the root user. For more details, see /etc/sysctl.d/10-ptrace.conf
ptrace: Operation not permitted.
I'm running gdb under the same user the process switched to, and I am able to attach to other processes that were initially started under under that user. I tried this on Kubuntu 13.10 (YAMA is disabled), Debian 6 and 7 with the same result.
So my questions are:
Why can't ptrace attach to a process that has the same effective and real UID as gdb?
Is it possible to drop privileges of my program in a way so that I can attach to it from the unprivileged gdb? How?
Thanks.
A:
I found the solution on my own.
There is a 'dumpable' flag in the kernel for every process. When the process performs setuid or setgid (at least, in my case, when the process drops privileges) this flag gets cleared and normal users can't attach to this process with a debugger, and the process crashes also do not produce a crash dump. This is done for security reasons to protect any sensitive data obtained with elevated privileges that may be in the process memory.
To solve the problem the process can explicitly allow debugging by setting the 'dumpable' flag to 1.
prctl(PR_SET_DUMPABLE, 1);
This has to be done after the setgid/setuid calls.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cannot make first ACL example
I want to load My ACL plugin to the application, and just start working with ACL
I follow this tutorial to start learning ACL.
I make like this
class My_ACL extends Zend_Acl {
public function __construct() {
$this->addRole(new Zend_Acl_Role('member'));
$this->addRole(new Zend_Acl_Role('admin'));
//discussions is a module name
$this->add(new Zend_Acl_Resource('discussions'));
//privileges is a module name
$this->add(new Zend_Acl_Resource('privileges'));
//default is a the default mdule
$this->add(new Zend_Acl_Resource('default'));
//allow admin every thing
$this->allow('admin');
//tmp just for testing
$this->allow('member');
}
and in the plugin I delete every thing and just keep an echo statement
class Application_Plugin_Acl extends Zend_Controller_Plugin_Abstract {
private $_acl = null;
public function __construct() {
$this->_acl = new My_ACL();
}
public function preDispatch(Zend_Controller_Request_Abstract $request) {
$role = (Zend_Auth::getInstance()->hasIdentity()) ? 'admin' : 'member';
echo $this->_acl->isAllowed($role, $request->getModuleName() . ':' . $request->getControllerName() . ':' . $request->getActionName());
}
but when I try to access any url for the system this error occur
Fatal error: Uncaught exception 'Zend_Acl_Exception' with message 'Resource 'default:error:error' not found' in
D:\ZendFramework\library\Zend\Controller\Plugin\Broker.php on line 312
( ! ) Zend_Acl_Exception: Resource 'default:error:error' not found in D:\ZendFramework\library\Zend\Acl.php on line 365
}
A:
add this line
if($request->getControllerName() == 'error') return ;
after
$role = (Zend_Auth::getInstance()->hasIdentity()) ? 'admin' : 'member';
Basically whenever application error occurs ZF changes request object to module default , error controller and its error action . For that case you have not created any resource .
By doing what I say you will be able to see 'Application Error' page which will help you fix the first problem .
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a python datastructure that would allow efficient range queries?
Say, you had a list of integers, e.g.
foo = [3,9,23,54,77,123,...]
Is there an efficient datastructure that would allow queries like
x = everything in foo between 10 and 100
so that
x == [23,54,77]
or
x = everything < 50
giving
x = [3,9,23]
etc?
A:
Assuming these integers are already sorted it's not a data structure that you want, but an algorithm: that is, binary search. In Python this is provided by the bisect module.
So, for example, to find all the members that are less than 50:
from bisect import bisect_left
i = bisect_left(foo, 50)
result = foo[:i]
A:
There is the range function (or xrange in python 2):
foo = [3,9,23,54,77,123]
x = [y for y in foo if y in range(10,101)]
# x = [23,54,77]
If there's an infinite number on one side, use the operators and add float(y).is_integer() to match only integers:
x = [y for y in foo if y < 50 if float(y).is_integer()]
# x = [3,9,23]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SSRS (SQL2014) - hide a chart when a multi-value parameter is selected
On one SSRS report, I have a parameter called "Machine". User can select one or several machines in the list.
When only one machine is selected, I want to show a chart.
When several machines are selected, the data shown on the chart makes no sense, so I want to hide the chart.
Do you know how can I detect that user select only one or several machines? Which expression could I use in the "visibility" parameter of the chart?
Thanks in advance.
A:
In the visibility property of the chart, use the expression:
=(Parameters!ParameterName.Count > 1)
This will hide the chart when more than one value is selected.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I tell my program to save in ~
I'm using a program which processes some data and then saves it to a file. It is possible to specify the directory in which the data is saved, however the program is badly written, so if I put ~ it is unable to interpret the result and says that no directory named /~ is found.
I want to be able to give this program to my colleagues and have them run it. I could just directly specify to save in /home/my_username/, but then they would also get "no directory found" when they try to run it, because their home folders have different names.
Can I specify ~ in some other way that my colleagues can run the program and have it save their data in their own respective home directories?
A:
Note that ~ is expanded by the shell to the value of ${HOME}, you can't enter that as input to a program and expect it to automatically translate it to ${HOME} (unless you specify it as a command-line option to the program, which gives the shell a chance to perform the substitution).
If you want to write to the home directory, you could have your program look up the ${HOME} environment variable. Then whoever it is, and where ever home is, you'll get the right answer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP: How to compare images without storing the files themselves?
I'm building an app that's kind of a canvas-paint art generator. The details aren't important - what is important is ensuring that the same image is never saved twice.
It's fine if the same image is generated more than once, but before it gets saved I need to check all images to-date for an identical copy. Eventually there are going to be thousands - even millions - of these images, so it's pretty unreasonable to store the raw files and check every single one against the active. Is there a way to reduce an image file to a unique key or string?
I considered some kind of SHA conversion - it would be really easy to check an image's hash against a table of logged hashes - but there is a distressing lack of information on the topic, and SHA has a small possibility of duplicates. Any help is appreciated - thanks!
A:
You may be able to use the hash_file function to perform this. (it's a pecl extension)
$hash = hash_file("sha256", $filename);
Basically collisions with the hash will be possible but highly unlikely. To further guard against them you can add on additional attributes like the size of the file to the hash.
$hash = hash_file("sha256", $filename)."-".filesize($filename);
Now collisions are only possible with two files of the exact same size that produce the same hash.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using jQuery to hide/show products using a switch statement and radio buttons
So I have a store web page and I'm trying to add jQuery to select and show specific items when a radio button is selected using a switch function. For some reason it is not working. When I run the code it's not doing anything and just shows all the products listed no matter what radio button is selected. I can't seem to figure out why it's not working. Any suggestions?
<div class="section group">
<div class="col span_1_of_6">
</div>
<div class="col span_1_of_6">
<div>
<h4>Filter</h4>
</div>
<div>
Category:<br />
<input type="radio" name="category_filter" value="all" checked="checked"> All</input><br />
<input type="radio" name="category_filter" value="accessory"> Accessory<br />
<input type="radio" name="category_filter" value="hardware"> Hardware<br />
<input type="radio" name="category_filter" value="mobile"> Mobile App<br />
<input type="radio" name="category_filter" value="software"> Software<br />
</div>
</div>
<div class="col span_3_of_6">
<h4>Products</h4>
<div class="product_listing" data-category="accessory" data-quantity="9">
<a href="detail.html">
<div class="product_image">
<img src="img/backpack.jpg" alt="Backpack thumbnail" />
</div>
<div class="product_info">
<div class="product_name">The NeverNot Backpack</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$75.00</div>
</div>
</a>
</div>
<div class="product_listing" data-category="accessory" data-quantity="100">
<a href="detail.html">
<div class="product_image">
<img src="img/bag.jpg" alt="Bag thumbnail" />
</div>
<div class="product_info">
<div class="product_name">The NeverNot Bag</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$45.00</div>
</div>
</a>
</div>
<div class="product_listing" data-category="software">
<a href="detail.html">
<div class="product_image">
<img src="img/nevernot_business.jpg" alt="NeverNot Premium thumbnail" />
</div>
<div class="product_info">
<div class="product_name">NeverNot Premium 1-month Subscription</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$8.00</div>
</div>
</a>
</div>
<div class="product_listing" data-category="software">
<a href="detail.html">
<div class="product_image">
<img src="img/nevernot_business.jpg" alt="NeverNot Business thumbnail" />
</div>
<div class="product_info">
<div class="product_name">NeverNot Business Subscription</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$125.00</div>
</div>
</a>
</div>
<div class="product_listing" data-category="mobile">
<a href="detail.html">
<div class="product_image">
<img src="img/nevernot_premium.jpg" alt="NeverNot Premium thumbnail" />
</div>
<div class="product_info">
<div class="product_name">NeverNot for iPad</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$4.99</div>
</div>
</a>
</div>
<div class="product_listing" data-category="software">
<a href="detail.html">
<div class="product_image">
<img src="img/nevernot_business.jpg" alt="NeverNot Premium thumbnail" />
</div>
<div class="product_info">
<div class="product_name">NeverNot Premium 1-year Subscription</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$39.00</div>
</div>
</a>
</div>
<div class="product_listing" data-category="mobile">
<a href="detail.html">
<div class="product_image">
<img src="img/nevernot_premium.jpg" alt="NeverNot Premium thumbnail" />
</div>
<div class="product_info">
<div class="product_name">NeverNot for iPhone</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$1.99</div>
</div>
</a>
</div>
<div class="product_listing" data-category="mobile">
<a href="detail.html">
<div class="product_image">
<img src="img/nevernot_premium.jpg" alt="NeverNot Premium thumbnail" />
</div>
<div class="product_info">
<div class="product_name">NeverNot for Android</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$1.99</div>
</div>
</a>
</div>
<div class="product_listing" data-category="hardware" data-quantity="2">
<a href="detail.html">
<div class="product_image">
<img src="img/scanner.jpg" alt="Scanner thumbnail" />
</div>
<div class="product_info">
<div class="product_name">ScanSnap NeverNot Edition</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$225.00</div>
</div>
</a>
</div>
<div class="product_listing" data-category="hardware" data-quantity="12">
<a href="detail.html">
<div class="product_image">
<img src="img/stylus.jpg" alt="Stylus thumbnail" />
</div>
<div class="product_info">
<div class="product_name">NeverNot Stylus</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$75.00</div>
</div>
</a>
</div>
<div class="product_listing" data-category="accessory" data-quantity="7">
<a href="detail.html">
<div class="product_image">
<img src="img/wallet.jpg" alt="Wallet thumbnail" />
</div>
<div class="product_info">
<div class="product_name">Wallet</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.</p>
<div class="product_price">$35.00</div>
</div>
</a>
</div>
</div>
<div class="col span_1_of_6">
</div>
</div>
</div>
</div>
$(document).ready( function() {
var products = $('.product_listing');
var low_quantity = products.filter(function () {
return $(this).data('quantity') < 20;
});
$(low_quantity).addClass("inventory_low");
var accessory_products = products.filter(function () {
return $(this).data('category') == 'accesory';
});
var hardware_products = products.filter(function () {
return $(this).data('category') == 'hardware';
});
var mobile_products = products.filter(function () {
return $(this).data('category') == 'mobile';
});
var software_products = products.filter(function () {
return $(this).data('category') == 'software';
});
$('input').on('change', function () {
switch($(this).val()) {
case 'all':
products.show();
break;
case 'accessory':
products.hide();
accessory_products.show();
break;
case 'hardware':
products.hide();
hardware_products.show();
break;
case 'mobile':
products.hide();
mobile_products.show();
break;
case 'software':
products.hide();
software_products.show();
break;
}
}
}
A:
So .show() function can’t take any arguments or elements -what ever you need to call it- so products.show(accesory_products); is totally wrong beacuse what it will do is: do nothing with the argument you give and show products. Thats what it is, so make it like this accesory_products.show(); hope it helps !
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change JTable row foreground
I am trying to color to RED, the foreground when a time is around some condition, but is painting the foreground of ALL rows(should be only seven).What i am doing wrong?Code below:
class RedRenderer extends DefaultTableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
BigDecimal time=new BigDecimal(jTable.getModel().getValueAt(row, 17).toString());
if(time.compareTo(new BigDecimal(2))<=0){
setForeground(Color.red);
setBackground(Color.white);
}else{
setBackground(null);
}
return this;
}
}
A:
Have you tried explicitly setting the foreground color to something different if the current row doesn't match your criteria?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I copy the content of a cell in the output pane where the latter is detached from the query window in pgAdmin III?
How can I copy the content of a cell in the output pane where the latter is detached from the query window in pgAdmin III?
When the output pane is not detached from the query window, I can use control + C, but it doesn't seem to work when it is detached.
Here is a screenshot showing the output pane detached from the query window:
I use pgAdmin III 1.20.0 with Windows 7 SP1 x64 Ultimate (English).
A:
For reasons best known to the designers of PgAdmin3, it's apparently not possible to do this.
The Cut/Copy and Paste options become greyed out when the window is floating. The logic behind this escapes me (wracks brain.... no, no good).
The only thing that I can think of is to use the green write arrow with the floppy and save your data to a file and dig out your data element that way - cumbersome I know. Or, you could just re-dock the window which does work.
If you'd like to file a feature request on the PgAdmin site, I'll gladly file a "me-too" if you provide the link back here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails Controller not creating new record
I have a definition
def create
@person = Person.new(params.require(:firstname, :lastname, :job).permit(loc))
@person.save
redirect_to @person
When I try to save a new person I get the following error:
ArgumentError in PeopleController#create
wrong number of arguments (5 for 1)
Is there an issue with the way I coded it? I also tried separating out each element with a separate ".require".
A:
Typically you want something like params.require(:person).permit(:firstname, :lastname, :job, :loc) then have your Person model validate the required attributes.
As for your issue, my guess is if you check your params you will see something like {person: {firstname: "first", lastname: "last", job: 1, loc: "somewhere"}} coming through and that is why your Person.new is raising that error.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Tell GraphicsMagick to keep tRNS chunk for alpha values when writing out a file
I am using GraphicsMagick to reduce the file size of PNG images. Some PNG files have their alpha values conveyed in a tRNS chunk to optimize their file size. The problem is GM is writing these files out as RGBA PNG's which is radically increasing their file size, as much more space is needed to store the alpha channel.
Does anyone know how to specify to GraphicsMagick or even ImageMagick to use the original alpha encoding rather than defaulting to RGBA?
A:
I have found out from the maintainers of GraphicsMagick that this functionality has not yet been implemented in ImageMagick or GraphicsMagick. However, the feature is being implemented right now so it may be available in the near future.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Use RedirectToAction in Web API
I am using RedirectToAction in my ASP.Net WebAPI application and I tried the following one.
return RedirectToAction("AuthenticateUser", "AuthenticationServiceWebApi", new RouteValueDictionary
{
{"userName", model.UserName},
{"password", model.Password}
});
This generates the redirection as below.
127.0.0.1:81/authenticationservicewebapi/authenticateuser/admin/admin@123
But, since I am using WebAPI, I need to be the URL like below.
127.0.0.1:81/api/authenticationservicewebapi/authenticateuser/admin/admin@123
How do I do this?
A:
If the user is not authenticated you should not redirect. There usually is no interactive user at the other end so you should really return HTTP Status Code 401 instead of redirect.
There is no equivalent in ASP.NET Web API.
If you insist doing it then here it is:
You throw HttpResponseException:
var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Found);
httpResponseMessage.Headers.Location = new Uri(myAddress, UriKind.Relative);
throw new HttpResponseException(httpResponseMessage);
A:
I'm not sure how your routing, Web API action signature look like so I will try to guess.
A few things don't really add up here (why would you pass the password in the url?)
but...
Given your url structure I'd guess your routing is something like:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}/{id2}",
defaults: new { id = RouteParameter.Optional, id2 = RouteParameter.Optional }
);
Then given that, I guess your authenticateuser must be something like:
public HttpResponseMessage AuthenticateUser([FromUri]string id, [FromUri]string id2)
If so, then to redirect to this from an MVC controller you need:
return Redirect(
Url.RouteUrl("DefaultApi",
new { httproute = "",
controller = "AuthenticationServiceWebApi",
action = "AuthenticateUser",
id = model.UserName,
id2 = model.Password
}));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PC created magic items and how to scale charges
If a player is to create a magic item that can cast spells but because they do not have the specific spell they want to use a spell they already have. However, I am not sure how to scale this properly.
For example, the Wand of Magic Missiles has 7 charges and each time you cast magic missile (level 1 spell) it costs 1 charge
So at first it seems as though 1 spell level is 1
The Staff of the Magi can cast fireball at 7th level for 7 charges which matches the charge costs for the Wand of Magic Missiles.
So if a character in a high level campaign wanted to swap out a spell from the Staff of the Magi, for Finger of Death for example, would it cost 7 charges or should it cost more as a scaled up fireball is a lot weaker than an actual level 7 spell.
A:
Gauging from the lists on all the staves with which I have read the pattern seems to be one charge per level of the spell slot used to cast the spell. If you look at the Fireball 7th level(7c) version and the Wall of Fire(which is a level 4 spell it takes 4c) stands to reason that Finger of Death would take as many charges as the level in which you would want it cast.
To your point there is not much of a power discrepancy between a lvl 7 Fireball and a Finger of Death since one is single target and the other is AoE so potentially the Fireball can cause much more damage overall.
There seems to be a discrepancy on the Conjure Elemental ability though, it states 7c to use but this could be an error and is intended for the casting of at a 7th level slot.
There is no hard RAW details on this but it is extrapolated from the staves.
Wands play by different rules obviously. They cost one charge for the base cast and in the case of some like Magic Missiles (DMG 211) as you mentioned it costs an additional charge to add the equivalent of a spell slot to the casting.
One other thing to consider is the length of time to create a legendary item is quite long. If you go by the guidelines from the DMG it would take a single caster greater than 54 years to create a Staff of the Magi. DMG p129
500,000 / 25g per day = 54.795 years. This is prior to the optional rules in Xanathar's Guide to Everything on crafting.
A:
The official sources have no guidance on this, and are inconsistent
The example you use, the Staff of the Magi, does not follow any clear rules about its charges. For example, it has 7 charges of Conjure Elemental (5th level), 7 charges of Fireball (at 7th level), but only 2 charges of Knock (2nd level).
As an aside, I would imagine that higher level spells should have fewer charges, as they are more powerful.
The only guidance in the DMG on creating magic items states (referring to a table on page 285):
This column of the table indicates the highest-level spell effect the item should confer, in the form of a once-per-day or similarly limited property. For example, a common item might confer the benefit of a 1st-level spell once per day (or just once, if it's consumable). A rare, very rare, or legendary item might allow its possessor to cast a lower-level spell more frequently.
That's as much as you get on the number of charges.
Make cost scale with charges
If you're having players make magic items, you might run into the problem that the items are too powerful. For example, if a wizard casts fireball a few times every day, and makes a wand of fireball, they're effectively getting free spell slots from the wand. Additionally, allowing them to make the item themselves means that they can tailor it to be much more powerful for their character.
The DMG provides no guidance on how magic items are made, so I'm assuming you have some homebrew rules for that. I'd suggest that the cost, whatever it may be, scales exponentially with the number of charges. A 1-charge wand might cost 100 gp, but 2 charges might be 200, 3 charges might be 400, 4 charges cost 800, and so forth. One of my DMs builds magic items this way, and it works to make magic items that are useful but not overpowered.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
date.getFullYear is not a function inside while()
I run this in node.js v11.6.0
const now = new Date(Date.now());
let date = now;
date.setFullYear(date.getFullYear() - 1);
let str = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
while(!data[str]){
date = date.setDate(date.getDate() - 1);
str = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
}
And get:
trail.js:15 str = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
TypeError: date.getFullYear is not a function
inside the while loop date.setDate() works but date.getFullYear() is not a function all of a sudden.
A:
When you call date.setDate(date.getDate() - 1); you're assigning the return value of setDate which is an integer to date. That's why you can't call .getFullYear later, since numbers don't have that method.
From MDN:
Return Value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the
given date (the Date object is also changed in place).
while(!data[str]){
date.setDate(date.getDate() - 1);
str = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
}
Have in mind that date.getMonth() returns an integer number, between 0 and 11. If you want to format it correctly you can check:
Format JavaScript date as yyyy-mm-dd
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to call a function ASA the app runs in flutter?
I have an application that do login with the help of firestore database and I want to do autologin so I made a boolean and set it to false in the database and made the login function set it to true as he or she sign in, so I want to check if the person have already signed in or not as the app runs, any ideas :) ?
here my code:
void getUserData() async {
try {
var firebaseUser = await FirebaseAuth.instance.currentUser();
firestoreInstance
.collection("Students")
.document(usernameController.text)
.get()
.then((value) {
setState(() {
email = (value.data)['email'];
password = (value.data)['password'];
gender = (value.data)['gender'];
loggedin = (value.data)['token'];
});
});
} catch (e) {
print(e.toString);
}
}
A:
You dont have to use a boolean to check if the user is logged in or not. Firebase authentication already offers that. You can check inside the initState:
@override
void initState() {
super.initState();
FirebaseAuth.instance.currentUser().then((res) {
print(res);
if (res != null) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Home(uid: res.uid)),
);
}
else
{
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SignUp()),
);
}
});
}
Checks if there is a current user or not and navigates to the required page.
If you have different types of users, then you have to identify them in the database. So authenticate in firebase authentication, and use a userType field in the database:
void registerToFb() {
firebaseAuth
.createUserWithEmailAndPassword(
email: emailController.text, password: passwordController.text)
.then((result) {
firestoreInstance.collection("users").document(result.user.uid).setData({
"email": emailController.text,
"name": nameController.text,
"userType" : "Students"
}).then((res) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Home(uid: result.user.uid)),
);
});
}).catchError((err) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error"),
content: Text(err.message),
actions: [
FlatButton(
child: Text("Ok"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
});
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Possible to solve $A + P^{-1}AP = B$?
Is it possible to solve for a matrix $A$ in an equation involving a matrix similar to $A$, of the form
$$A + P^{-1}AP = B$$?
The solution I'd be looking for would be for $A$ in terms of $P$ and $B$, ideally.
EDIT: Thanks for the existing answers! Just to add, in the particular case I'm trying to solve, P is diagonal.
A:
If you pre-multiply both sides by $P$ you end up with a Sylvester equation - see the Wikipedia entry here:-
$$PA+AP=PB$$
Suppose $P$ is an $n\times n$ diagonal matrix:-
$$P=\left(\begin{array}{cccc} p_1 & 0 & \cdots & 0\\ 0 & p_2 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & p_n \end{array}\right)$$
and matrices $A$ and $B$ are given by
$$A=\left(\begin{array}{cccc} a_{11} & a_{12} & \cdots & a_{1n}\\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{n1} & a_{n2} & \cdots & a_{nn} \end{array}\right)$$
$$B=\left(\begin{array}{cccc} b_{11} & b_{12} & \cdots & b_{1n}\\ b_{21} & b_{22} & \cdots & b_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ b_{n1} & b_{n2} & \cdots & b_{nn} \end{array}\right)$$
Then (using the Kronecker product formulation, and after some manipulation) we end up with a relationship between column $k\in\{1,2,\cdots,n\}$ of $A$ (denote as $A_{k}=[a_{1k},a_{2k},\cdots,a_{nk}]^T$) and column $k$ of $PB$ (denote as $[PB]_{k}=[p_1b_{1k},p_2b_{2k},\cdots,p_nb_{nk}]^T$) as follows:-
$$(P+p_kI)A_{k}=[PB]_{k}\Rightarrow A_{k}=(P+p_kI)^{-1}[PB]_k$$
where $I$ is the $n\times n$ identity matrix, so that $P+p_kI$ is a diagonal matrix.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Data frame: loop over participants/observations and write column to text file
I'm trying to loop over the participants in a data frame and then write a different column (text) to individual .txt files, so that I ultimately end up with one .txt file per participant containing all the text they produced (a participant can have several observations rows!)
Searching stackoverflow, this is what I have so far:
dataframe <- data.frame(part_id = rep(seq(1:3), 2), text = c("test1",
"test2", "test3", "test4", "test5", "test6"))
dataframe <- dataframe %>% arrange(part_id)
for(i in dataframe$part_id) {
subset[i] <- dataframe[dataframe$part_id == i,]$text
write.table(i, paste(i, ".txt", sep=""),
col.names = FALSE, row.names = FALSE, sep = "\t")
}
It works insofar as the loop produces individual text files (.txt), but instead of the text, they contain the part_id.
Any help is welcome and much appreciated!
A:
Because in write.table(i, file_path) you're writing i (which is the part_id) into the file, change it to write.table(subset[i], file_path) will do the work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sending data via request header vs sending data via request body
What is the difference between sending data through the request header and sending data through the request body. Under what circumstances, we have to send the data through the header/body and when shouldn't we send the data through header/body ?
A:
It is usually a good idea to use the headers for metadata and the body for the data that is used by the business logic.
Some points to consider:
1) If the data is sent via HTTP instead of HTTPS, the proxy servers can modify the headers.
2) If you are using the REST protocol for communication among microservices, interoperability could be important. Most APIs usually do not provide the capability to add/modify custom headers.
3) It is better to have the data that is used by routers/firewalls in the HTTP header and limit the body to application specific information.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как при делении двух целых чисел типа int получить вещественное число?
Всем привет.
int a = 22;
int b = 7;
var result = a / b;
Console.WriteLine( "{0} / {1} = {2}", a, b, result );
Результат равен 3, а мне-то нужно 3,142857143. Как это реализовать?
A:
var result = (double) a / b;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to set environment variable with Sceptre pre hooks
I'm trying to set an environment variable using sceptre !cmd hooks(before create/update), which can be then resolved by sceptre_user_data with !environment_variable resolver within the same config file.
The command works well, when executed from shell, but for some reason, the !cmd hook doesn't perform assignment during runtime
Don't know, if I'm missing anything here
hooks:
before_create:
- !cmd "export OBJECT_VERSION=$(aws s3api put-object --body file --bucket bucket-name --key path --query 'VersionId')"
sceptre_user_data:
ObjectVersion: !environment_variable OBJECT_VERSION
A:
Unfortunately you'd need a custom resolver for that at the moment
sceptre_plugins_cmd_extras.py
import os
import subprocess
from sceptre.resolvers import Resolver
class CmdResolver(Resolver):
"""
Resolver for running shell commands and returning the value
:param argument: Name of the environment variable to return.
:type argument: str
"""
def resolve(self):
"""
Runs a command and returns the output as a string
:returns: Value of the environment variable.
:rtype: str
"""
return subprocess.check_output(self.argument, shell=True)
setup.py
from setuptools import setup
setup(
name='sceptre-plugins-cmd-extras',
description="Extra Sceptre Plguins (Hook & Resolver) for subprocess",
keywords="sceptre,cloudformation",
version='0.0.1',
author="Cloudreach",
author_email="[email protected]",
license='Apache2',
url="https://github.com/cloudreach/sceptre",
entry_points={
'sceptre.resolvers': [
'cmd = sceptre_plugins_cmd_extras:CmdResolver',
],
},
py_modules=['sceptre_plugins_cmd_extras'],
install_requires=["sceptre"],
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators"
"Natural Language :: English",
"Environment :: Plugins",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7"
]
)
But you'd then need to make your command idempotent (something like)
sceptre_user_data:
ObjectVersion: !cmd aws s3api get-object --bucket bucket-name --key path --query 'VersionId' || aws s3api put-object --body file --bucket bucket-name --key path --query 'VersionId'
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should we have a bitcoin-canon tag?
While looking over this question, it occurred to me that not every one would have heard of the famous "Bitcoin pizza" event, and so I suggested to @David Perry to add a link "to build up the Bitcoin Canon". I'm following the general idea that Canon is the formative material that shapes a given subject. Wikipedia has an example of Western Culture Canon that illustrates the kind of content that qualifies.
Since we are expecting this site to become one of the definitive resources about Bitcoin, it might help future researchers looking over old posts to be able to identify, or subsequently tag, significant Bitcoin moments and references with a "bitcoin-canon" tag.
Maybe it's all a bit above our station, but I thought I'd put it forward for discussion.
A:
Such a tag would seem appropriate for a discussion forum, but not for a Q&A site like this.
A:
I don't this is useful. I think we should focused on building a knowledge base and expert community first, leave the canon to the wiki/forums/reddit.
I'm not saying we should close questions like "How much did the first Bitcoin pizza cost", just that there's no need to make a fuss about it and tag it as canon.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pandas set date as day(int)-month(str)-year(int)
I am trying to change the formatting of a date column
original: 2020/05/22
Desired outcome: 22/may/2020
so far I've done:
.to_datetime
dt.strftime('%d-%m-%Y')
converting into: 22/05/2020
how can I get the middle part to convert into alphabetical?
A:
Try this, all the format codes are given here date formats:
df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%d/%b/%Y')
print(df)
Date
0 22/May/2020
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Run middleware after Gorilla mux handling
I'm trying to use Golang middleware to run after handling Gorilla Mux routing, in order to change the response of each request.
Code sample see below. Currently it returns 'run before, run test', goal is to return 'run before, run test, run after' using the runsafter middleware.
Is something like this possible with Gorilla Mux?
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func runsbefore(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("run before, "))
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func runsafter(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("run after, "))
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func runtest(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("run test, "))
}
func main() {
fmt.Println("Server starting on port 8000")
r := mux.NewRouter()
r.HandleFunc("/", runtest).Methods("GET")
http.ListenAndServe(":8000", runsbefore(r))
// something like: http.ListenAndServe(":8000", runsbefore(r(runsafter)))
}
A:
Use
http.ListenAndServe(":8000", runsAfter(runsbefore(r)))
and fix the error in runsAfter:
func runsafter(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
w.Write([]byte("run after, "))
}
return http.HandlerFunc(fn)
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use php console in Symfony2
I found the console and run it like this:
root@valugi-laptop:/var/www/sandbox/hello# php console
Symfony version 2.0.0-DEV - hello
Usage:
Symfony [options] command [arguments]
Options:
--help -h Display this help message.
--quiet -q Do not output any message.
--verbose -v Increase verbosity of messages.
--version -V Display this program version.
--color -c Force ANSI color output.
--no-interaction -n Do not ask any interactive question.
--shell -s Launch the shell.
Available commands:
help Displays help for a command (?)
list Lists commands
assets
:install
bundle
:pharize
container
:graphviz
doctrine
:generate-proxies
init
:application
:bundle
router
:debug Displays current routes for an application
:dump-apache
But I cannot run any of those commands. I am trying like this:
php console Symfony -h
But I get
[InvalidArgumentException]
Command "Symfony" is not defined.
Any suggestions?
A:
Console is used like this: $ php app/console [command name]
A:
Find myself an answer.
root@valugi-laptop:/var/www/sandbox/hello# chmod 777 /var/www/sandbox/src/Bundle
root@valugi-laptop:/var/www/sandbox/hello# php console init:bundle "Bundle\\ValugiBundle"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are the differences between an "Hack & Slash" and a "Beat 'em up"?
What are the differences between an "Hack & Slash" and a "Beat 'em up"? I would like to know what makes the difference between these two types of game because they look the same to me.
A:
I don't have any sources for this other than years of playing, but, for me:
A beat-'em-up is like Streets of Rage or River City Rampage. There may be some items and character progression, but the majority of combat is determined by player reflexes and ability to read and react to the immediate combat environment. Player commands are "low level" - e.g. "swing weapon", "turn left" - and advanced play involves stringing these actions together fluidly to create combos appropriate for the situation. Time is often measure in frames.
A hack-and-slash is like Diablo or Ys. Combat is still real-time but a lot of strategic planning occurs before combat by preparing weapons and abilities and dexterity does not play as large a role. Player commands are "high level" - e.g. "attack this monster", "cast this spell" - and advanced play involves looking deeper for synergies during planning and managing resource pools (HP, mana). Time is often measured in seconds.
The distinction between the genres is fuzzy and often hard and pointless to determine. Dark Souls is usually called a hack-and-slash but its combat is slow and methodical, and so reading and positioning skills also come into play. Devil May Cry comes from a long line of beat-'em-up designs but still involves ahead-of-time planning in weapon and item choice. Something like God of War seems to sit right between the two terms, with a variety of weapons and long-duration attacks but little lockdown and plenty of cancelling opportunities.
A:
Wikipedia seems to think that hack and slash refers to hand to hand combat focused RPGS, whereas beat 'em ups are action oriented games focussing on hand to hand combat, so "Kingdoms of Amalur: Reckoning" is probably hack and slash whereas "Bayonetta" is probably a beat 'em up. What they seem to have in common is progression through a large number of melee battles with multiple NPC enemies to achieve the goal of the game.
Wikipedia sadly fails to quote sources for this assertion.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Grouping types of bugs by date and priority
I currently have a table Bugs that looks like this:
|ID |Priority |Created |Updated |Status |Category
|X123 |Major |01/01 |01/03 |Open |A
|X145 |Normal |01/01 |01/02 |Closed |B
|X678 |Minor |01/03 |01/03 |Open |C
|X763 |Major |01/02 |01/03 |Closed |C
All columns are varchar(25) except Created and Updated, which are dates.
I need to create a view with the following format:
|Date |Major |Normal |Minor |Category
|01/01 |4 |3 |4 |A
|01/01 |3 |5 |2 |B
|01/01 |2 |4 |7 |C
|01/02 |7 |3 |4 |A
|01/02 |3 |9 |5 |B
|01/02 |1 |6 |3 |C
Where the numbers under Major, Normal, and Minor are the count of CURRENTLY OPEN bugs of that priority on a given date. By currently open, I mean this: open bugs are active on the interval Created-GETDATE(), closed bugs are active on the interval Created-Updated.
I have a list of all the dates I need through this query:
WITH D AS
(
SELECT Dates AS DateValue
FROM DatesTable
WHERE Dates >= '2012-03-23'
AND Dates <= GETDATE()
),
Any ideas of how I might do this? I've played with the idea of a pivot query and grouping, but I've not been able to cover everything I need. Your help is greatly appreciated!
EDIT: The Bugs table with example data
CREATE TABLE [dbo].[Bugs](
[ID] [varchar](25) NOT NULL,
[Priority] [varchar](25) NOT NULL,
[Updated] [date] NOT NULL,
[Created] [date] NOT NULL,
[Status] [varchar](25) NOT NULL,
[Category] [varchar](25) NOT NULL,
) ON [PRIMARY]
INSERT INTO Bugs VALUES (X123, Major, 01/01/12, 01/03/12, Open, A)
INSERT INTO Bugs VALUES (X145, Normal, 01/01/12, 01/02/12, Closed, B)
INSERT INTO Bugs VALUES (X678, Minor, 01/03/12, 01/03/12, Open, C)
INSERT INTO Bugs VALUES (X763, Major, 01/02/12, 01/03/12, Closed, C )
A:
This is what I tested at last:
SELECT d.Dates as Date,
SUM(CASE Priority WHEN 'Major' THEN 1 ELSE 0 END) as Major,
SUM(CASE Priority WHEN 'Normal' THEN 1 ELSE 0 END) as Normal,
SUM(CASE Priority WHEN 'Minor' THEN 1 ELSE 0 END) as Minor,
b.Category
FROM Bugs b
INNER JOIN DatesTable d ON d.Dates >= b.Created
WHERE (Status = 'Closed' AND d.Dates <= Updated OR Status = 'Open')
AND d.Dates <= GETDATE() AND d.Dates >= '2012-01-01'
GROUP BY d.Dates, b.Category
ORDER BY d.Dates
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VHDL Logic produces wrong result when using higher frequencies
I don't have much experience with VHDL, so excuse me if it's stupid boring question, but I couldn't find appropriate answer. I have code that is a bit simplified here.
process (sys_clk, reset):
begin
if reset = '0' then
-- reseting code
elsif rising_edge(sys_clk) then
if data_ready = '1' and old_data_ready = '0' then -- rising edge of asynchronous sig
-- update few registers, and assigning values to few signals
elsif error_occured = '1' and old_error_occurred = '0' then
-- update few registers, and assigning values to few signals (same registers and signal as above)
end if;
old_data_ready <= data_ready;
old_error_occured <= error_occured;
end if;
end process;
Signal is kept much longer high than period of sys_clk is, but it's not know for how long. It varies.
These IFs result in two (one each) registers and an AND circuit. I believe you know that.
This worked, but very badly. The were errors to often. So I made special project using two processes. One active on rising edge of data_ready and one on error_occured. But I could use it just to increment and decrement to separate counters. I used that to verify that problem with my code is that sometimes this rising edge detection does not work. sys_clk is 27MHz, and I made much bigger project using that same frequency and they worked well. But there was no detection of rising edge of asynchronous signals this way. So I reduced frequency to 100kHz, because I don't really need higher frequencies. And that solved my problem.
But just for curiosity, what is the best way to test for rising edge of asynchronous signal when few of these signal affect same registers and device needs to work on higher frequencies?
I use Altera Quartus II and Cyclone II FPGA.
A:
If the signal you are sampling is truly asynchronous, you have to deal with the issue of metastability. If the data_ready signal is in a metastable state exactly on sys_clk's rising edge, old_data_ready and the first if-statement might see different versions of data_ready. Also, you have an asynchronous reset. If the reset signal is released exactly when the data_ready is changing, it may result in data_ready being sampled to different values though out your system. A simulator will not reveal metastability problems, because the code is logically correct.
To circumvent these problems, have asynchronous reset between modules, but synchronous within.
Also, synchronize any signal coming from a different clock domain. A synchronizer is a couple of flip flops placed closely together. When the signal passes through the FFs, any metastability issues will be resolved before it reaches your logic. There is a formula for calculating mean time between failure (MTBF) due to metastability in FPGAs. I won't recite it, but what is basically says is that using this simple method reduces MTBF from seconds to billions of years.
VHDL synchronizer:
process(clk, rst) is
begin
if(rising_edge(clk)) then
if(rst = '0') then
data_ready_s1 <= '0';
data_ready_s2 <= '0';
else
data_ready_s1 <= data_ready;
data_ready_s2 <= data_ready_s1;
end if;
end if;
end process;
Use data_ready_s2 in your module.
Then you constrain the path between the flipflops in the UCF file:
TIMEGRP "FF_s1" = FFS("*_s1") FFS("*_s1<*>");
TIMEGRP "FF_s2" = FFS("*_s2") FFS("*_s2<*>");
TIMESPEC TS_SYNC = FROM "FF_s1" TO "FF_s2" 2 ns DATAPATHONLY;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP upload file to API
I am trying to use an API and I am not getting anywhere. The documention says "The document to fax is written directly to the Request Input Stream in binary format"
I have tried using examples from the web like....
$xSendURL = 'http:/example.com/default.ashx?OPT=SendFax&UserName=johndoe...';
# New data
$data = array('FileData' => '@/DATA/html/sites/support/FAAPI/TEST.TIF');
# Create a connection
$ch = curl_init();
# Setting our options
curl_setopt($ch, CURLOPT_URL, $xSendURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
# Get the response
$response = curl_exec($ch);
curl_close($ch);
But when I check the file that is created on the server the contents of the file is the path that I defined for the $data variable. (@/DATA/html/sites/support/FAAPI/TEST.TIF)
I am very new at php. I looked into php://input and php://outout but I am not sure if that would work.
On the URL that I use to invoke the API I pass the filename, username, and security tokens I am not sure how I would grab the Request Input Stream to upload the file after opening the URL.
Any help is appreciated.
Thanks
A:
I would try using file_get_contents() with a specialized stream. It works as follows:
Create a "context" which is a description how a HTTP request should be formed:
use a POST request
send an additional header with Content-Type: image/tiff
include contents of the tiff file
Request the API URL using the specified context.
Skeleton code:
$data = file_get_contents('/DATA/html/sites/support/FAAPI/TEST.TIF');
$options = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: image/tiff',
'content' => $data,
)
);
$context = stream_context_create($options);
$result = file_get_contents($xSendURL, false, $context);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to display object's List property in listview
I'm currently having a problem in displaying some stuff in ListView. I have a normal C# Student class and a Classroom class. In Classroom class contains a List of Student classes which is shown below:
public class Classroom
{
int classroomid {set;get;}
List<Students> students{set;get;}
}
My question is if I bind my DataSource of the ListView to a List of objects of Classroom, how do I render the Student lists in the ListView?
<ListView>
<ItemTemplate>
<asp:Label Text='<%# Eval("classroomid") %>'></asp:Label>
<asp:Label Text='<%# Eval("students") %>'</asp:Label>
<asp:Label Text='<%# Eval("students.name") %>'</asp:Label>
</ItemTemplate>
</ListView>
The code above essentially explains that what I'm trying to achieve, or possibly displays the student's details such as name or etc. Is there any way to achieve that? I do understand that nested ListView works, but I'm not sure how is the implementation.
Thank you for your help in advance. :-)
A:
You could use string.Join:
<asp:Label runat="server" ID="LblStudents"
Text='<%# string.Join(",", (List<string>)Eval("students")) %>'>
</asp:Label>
Edit: I missed that Student is a custom type. So you should better do this in the ListView's ItemDataBound event for readability.
But it should work also on aspx:
<asp:Label runat="server" ID="LblStudents"
Text='<%# string.Join(",", ((List<Student>)Eval("students")).Select(s=>s.Name)) %>'>
</asp:Label>
in codebehind:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label LblStudents = (Label)e.Item.FindControl("LblStudents");
Classroom cr = e.Item.DataItem as Classroom;
if (cr != null && cr.students != null && cr.students.Count > 0)
{
LblStudents.Text = string.Join(",", cr.students.Select(s => s.Name));
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Resize Facebook "Like" button iframe to fit contents
I am using Facebook's "Like" button (http://developers.facebook.com/docs/reference/plugins/like/) on my site (standard iframe version, not XFBML) and want it to float in the page text (inline). The problem is that the button can have various states, depending on whether you "liked" yourself, how many likes there are, language etc., and each of those states has a different width. I want the size of the button's iframe to be only as big as the iframe's contents, allowing the button to float inline with no ugly spacing around. Every solution I have found involves fixing the width of the iframe or surrounding DIV.
Note: This question is NOT a duplicate of How can I make the Facebook Like button's width automatically resize?. I want not fixed but dynamic width.
A:
I encountered the same issue. The thing that makes this difficult is that you can't use javascript on the contents of an iframe containing a page from a different domain.
It's only a partial solution, but this may be of some help. You can determine how many times the page has been "liked" and adjust the style using Javascript (shown here using jQuery) accordingly:
jQuery(document).ready(function($) {
var shareUrl = window.location.href;
$.getJSON('http://graph.facebook.com/?id=' + escape(shareUrl) + '&callback=?', function(data) {
if (data.shares) { //if the tip of the day has been "liked" at least once
$('#fblike').addClass('hasLikes');
}
});
});
Example styling:
#fblike.hasLikes iframe {
width: 87px !important;
}
You could similarly get other information from the Facebook Graph that could help you determine the width, or perhaps create your own custom display code (although at minimum you'd still need to use the provided iFrame for the "Like" button itself; you'd just turn off all the extras)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Too big number of $(window).height() on wordpress
I'm creating dynamic posisition of tooltip, I have tested code on jsfiddle first before put my code to my site (build with wordpress on localhost), on jsfiddle my script is works but when I put code to my site, It's not works (not dynamically on chrome) because different result of $(window).height(). You can check this fiddle and try to mouse enter to a link (first link) and then see log at console, the result of window height is wh :667 but on my site window height is wh :12024 and wh : 11970 (changeable)
jQuery(document).ready(function ($) {
$('a[rel="bookmark"]').mouseenter(function () {
console.log($(window).height());
})
});
also using this
jQuery(function($){
$(window).ready(function(){
console.log($(window).height());
});
$(window).on('resize', function(){
console.log($(window).height());
});
});
Google Chrome
jsfiddle : 667
my site (wordpress) : 12024 - changeable
Mozilla
jsfiddle : 602
my site : 585
I'm sure, I have added strict doctype.
I found this explanation
$(window).height() is the height of the viewport that shows the
website. (excluding your toolbars and status bar and stuff like this)
$(document).height() is the height of your document shown in the
viewport. If it is higher than $(window).height() you get the
scrollbars to scroll the document
I think on my site result $(window).height() is scrollbars to scroll the document on chrome (fyi my site have a long page). If it is like that, how can I get height of the viewport on my site, is there another way to get same result (actual) height of the viewport every browser (chrome, mozilla, opera etc) ?
note : I don't think for use screen.height because it can result display of screen (include toolbar of browser)
A:
It took me hours/days to debug this baby, but I finally got it. Believe or not, but I haven't had such bug for YEARS!! What a nasty bug.
I am not saying you had the exact problem, however, this thread is exactly what I was facing. I was 100% sure that my html is set to strict.
However, as soon as I did "Inspect element" in Chrome, the actual definition of strict DOCTYPE was gone. So I checked other websites, and I immediately realized that there is something extremly fishy going on, this shouldn't be happening. Who ate my strict doctype?
Not only that, but I noticed that the contents of HEAD moved to <body> and other weird things were happening.
I did what any reasonable human would do, I speculated that all my time was wasted on this stupid UTF-8 BOM, as I've had many problems with that in the past. Oh boy was I correct.
Everything started to work flawlessly, after I've switched to UTF-8 without bom. Notice that the interesting thing is: my website seemed to work 100%, even with messed up HTML(I never noticed that browser interpreted it way incorrectly).
Why was my file encoded as UTF-8 with bom at first place & why should it even affect browser? I have no idea.
A:
Ok, I got it. I'm using pure javascript
replace $(window).height() with window.innerHeight
$(window).load(function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
console.log(y);
});
Chrome :
jsfiddle : 667
my site : 667
Mozilla
jsfiddle : 602
my site :602
https://stackoverflow.com/a/11744120/1297435
|
{
"pile_set_name": "StackExchange"
}
|
Q:
¿Cómo obtener un arreglo asociativo usando consultas preparadas con mysqli?
A veces hay consultas que traen varias columnas y resulta tedioso tener que vincular el resultado de cada columna a una variable. En esos casos uno podría preferir almacenar el conjunto de resultados en un arreglo usando por ejemplo el método fetch_assoc.
Con una consulta obtenida mediante query, (consultas no preparadas), no hay ningún problema. Pero cuando se trata de consultas preparadas mysqli hace las cosas verdaderamente difíciles y no entiendo por qué.
Investigando, creí dar con la solución... El Manual de PHP describe el método get_result, como el mejor camino para obtener un conjunto de resultados proveniente de una consulta preparada dentro de un array asociativo.
Peeeero esta nota del Manual hace que tu relación con mysqli sea irreconciliable:
Disponible sólo con mysqlnd.
mysqlnd no viene instalado en todos los sistemas... y dicha limitación no es válida cuando intentas dar alguna respuesta a dudas planteadas aquí.
La pregunta
¿Cómo almacenar un conjunto de resultados en un array asociativo en mysqli usando consultas preparadas si no tenemos mysqlnd instalado?
En este código yo implementé una función mi_fetchassoc que hace el trabajo, pero no es lo ideal... también en ella debo especificar cada vez cómo se llaman las columnas.
function mi_fetchassoc($stmt)
{
if($stmt->num_rows>0)
{
$rs = array();
$md = $stmt->result_metadata();
$params = array();
while($field = $md->fetch_field()) {
$params[] = &$rs[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
if($stmt->fetch())
return $rs;
}
return null;
}
A:
Encontré esta respuesta en SO, con unos ejemplos interesantes, quizás te puede servir.
Ejemplo:
Aquí hay una solución más ordenada basada en el mismo principio:
function Arreglo_Get_Result( $Statement ) {
$RESULT = array();
$Statement->store_result();
for ( $i = 0; $i < $Statement->num_rows; $i++ ) {
$Metadata = $Statement->result_metadata();
$PARAMS = array();
while ( $Field = $Metadata->fetch_field() ) {
$PARAMS[] = &$RESULT[ $i ][ $Field->name ];
}
call_user_func_array( array( $Statement, 'bind_result' ), $PARAMS );
$Statement->fetch();
}
return $RESULT;
}
Nota: se podría incorporar a una clase utilitaria, para poder usarla desde cualquier parte del programa.
Normalmente sin mysqInd harías:
$sql = "SELECT * FROM books WHERE ean = ?";
$id=4;
//Preparar la consulta
$stmt=$mysqli->prepare($sql);
//Evaluar si tuvo éxito
if ($stmt) {
$stmt->bind_param("i", $id);
$stmt->execute();
$Resultado = get_result($stmt);
while ($row = array_shift($Resultado)) {
# trabajos con los datos
}
}
Normalmente con mysqInd harías:
$sql = "SELECT * FROM books WHERE ean = ?";
$id=4;
//Preparar la consulta
$stmt=$mysqli->prepare($sql);
//Evaluar si tuvo éxito
if ($stmt) {
$stmt->bind_param("i", $id);
$stmt->execute();
$Resultado = $stmt->get_result();
while ($row = $Resultado->fetch_array()) {
# trabajos con los datos
}
}
Nota: el uso y la sintaxis son casi idénticos. La diferencia principal es que la función de reemplazo devuelve una matriz de resultados, en lugar de un objeto de resultado.
@A.Cedano lo ha probado y funciona perfectamente, aquí puedes ver una respuesta por el más completa (¿Cómo aseguro mi conexión de PHP a MySQL?).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make jQuery functions run in order when a button is pressed?
I have a .click() function that performs certain actions when a button is clicked. I want it to display a loading image, run some "stuff", then delete the loading image when the "stuff" is done.
Example of Javascript code:
$("#button").click(
function(){
shoeLoadingImage();
/**************************************************************************
*
* other actions to be performed after showLoadingImage() is finished
*
**************************************************************************/
//Whats below should only to be triggered after above actions above are finished
hideLoadingImage();
}
);
By using a couple of suggestions here I came up with a solution. It works, but I'm sure there is a better way to do this since my loading.gif is frozen when it is loaded. FYI: the other actions listed under success: function(){} contains some actions that take some time to complete which is the whole purpose of this loading image.
$("#highlight").click(
function(){
$.ajax({
beforeSend: function(){ showLoadingImage(); },
success: function(){
/**************************************************************************
*
* other actions to be performed after showLoadingImage() is finished
*
**************************************************************************/
},
complete: function (){ hideLoadingImage(); }
});
});
A:
If there is no ajax call involved your code looks good. Otherwise if showLoadingImage is an ajax call you should do
$("#button").click(
function(){
showLoadingImage();
);
var showLoadingImage = function(){
$.ajax({
success: function(){
/**************************************************************************
*
* other actions to be performed after showLoadingImage() is finished
*
**************************************************************************/
hideLoadingImage(); //only to be triggered after above actions are finished
})
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android based programming...loops
this may be a very simple question. I was working through a tutorial and I didn't bookmark the page so I can't go back to it.
Never the less I'm stumped by one small part of the java language which is potentially very simple but I'm new to it. What does the following mean, and can it be amended to count higher?
for(int i=c.getCount()-1; i>=0; i--)
I believe it's an integer counter, which assigns a the value of c.getCount to i, then subtracts one, makes i equal nothing and then adds 1 to i again... is this right? I need to increase this beyond one, so is that possible.
A:
This is a for loop of decrement!
Here the value of i would be initialized to c.getCount()-1
And then it checks if that is greater than or equal to zero and gets in to the loop.
After executing the loop contents, i count is decremented to 1. i--
And then again checks for the condition and runs the loop. The loop runs until the i value becomes lesser than 0.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Terminal not working on Yosemite
Not sure about the Yosemite version because "About this mac" option doesn't work too. Terminal, X11, Screenshot to name a few, don't work.
Used to work fine since I updated from Lion a few months ago.
This message shows up in "console" when I try to open one of those options:
23/1/18 21:36:52,032 com.apple.xpc.launchd[1]:
(com.apple.Terminal.11392[853]) Service exited with abnormal code: 1
I found this answer from 2014:
You installed another version of bash,right? The default login shell
is /bin/bash. you can change it following these steps,
go to "System Preferences" > "Users & Groups" click the "padlock" icon
and authenticate right-click the icon for your user and select
"Advanced Options..." change the value for "Login shell"
My default login shell is "/bin/bash" so I assume that this user didn't had the same problem after update to Yosemite.
At this point I'm completely lost with my poor knowledge on IT...
Thanks in advance!
A:
Troubleshooting is a process of elimination and often requires some patience. In your case the best option may be to just reinstall macOS, but before doing that there's a few things we can try.
The first thing I'd probably do is start your Mac in Safe Mode and test to see if you can use your system
Boot into Safe Mode
Follow these steps to boot your Mac into Safe Mode:
Fully shut down your Mac
Restart your Mac
Immediately press the Shift key and keep it down
Let go of the Shift key when you see the login window (NOTE: If you have FileVault enabled you may need to log in twice).
Take a note of what happens (i.e. can you launch Terminal, view About this Mac, etc)
Exit Safe Mode by restarting your Mac as normal
Again, take a note of what happens (i.e. can you launch Terminal, view About this Mac, etc)
Once you've booted into Safe Mode, let me know how you went and we'll go from there. Primarily we need to establish if everything works okay in Safe Mode or not, and whether things get back to normal afterwards.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Wrong japanese characters
I have some problems in cocoa with some japanese characters. I try to print this character:
But it prints this:
This happens with more characters and I have no idea why.
I know that this doesn't happen with HiraginoKaku and HiraginoMaru fonts, but it happens with all the rest and should not.
Any idea?
Here the character (not image) to test: 写
Thanks in advance!
David
A:
Well, I got a solution. The thing is that I had the following code in the AppDelegate:
- (void)applicationWillFinishLaunching:(NSNotification *)notification
{
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil] forKey:@"AppleLanguages"];
}
Which forces the app to show everything in English, dialogs included, but it affects the Japanese characters.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to read Dropbox Public folder Images in HTML
I want to read all images from a dropbox public folder in a loop using jquery loop and display them.
I have tried displaying single images Simple Image like this
"https://dl.dropboxusercontent.com/s/9d7ri25ku7xlj9u/WALL-E%20%281%29.jpg?dl=0"
but if I have unknown number of images in dropbox public folder how can I access them all from dropbox??
Any starting point??
Thanks
A:
Dropbox Public folders don't currently offer any way to list all of the files contained in them, so there isn't a real way to do this. (Also, your sample link isn't a Public folder link anyway, but rather a "shared link". Public folder links used '/u/' instead of '/s/'.)
Anyway, one workaround here is to maintain your own index of all of the desired links as a single, pre-determined link. That is, you can host and update a text file at a specific link which would contain all of the other links. When necessary, you would download that index file to get the current list of links.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Drawing values from a lognormal distribution of a GBM
I'm looking at a GBM with parameters
$$
r=0.05 \\
\sigma=0.2 \\
K=130\\
T=0.25\\
S_0 = 100
$$
This is a process that is lognormally distributed with mean and variance given by
$
\mu = S_0e^{r T+0.5\sigma^2 T}\\
Var = S_0^2e^{2r T + \sigma^2T}(e^{\sigma^2 T}-1)
$
I'm trying to generate values from this distribution. However, the values I get are quite:
r = 0.05
sigma = 0.2
K = 130
T = 0.25
S0 = 100
import numpy as np
mean = S0*np.exp(r*T)
var = np.sqrt((S0**2)*np.exp(2*r*T)*(np.exp((sigma**2)*T)-1))
np.random.lognormal(mean, np.sqrt(var))
Drawing values from $f(x)$ gives me something around $10^{45}$ (!) Can anybody spot my error in the above?
A:
Assuming that your GBM is given by
$$S_{T}=S_{0}e^{(r -{\frac {\sigma ^{2}}{2}})T+\sigma W_{T}}$$
then its mean and variance are:
$${Mean=S_{0}e^{r T},}$$
$$
{Variance=S_{0}^{2}e^{2r T}\left(e^{\sigma ^{2}T}-1\right)}{\displaystyle}$$
You cannot paste these values directly into np.random.lognormal because in this case the parameters $\mu$ and $\sigma^2$ do not represent the mean and variance of the random variable. You actually need to simulate $W_T\sim N(0,T)$ and plug these values into $S_T$.
For the Normal distribution it is only by coincidence that the estimator for $\mu$ and $\sigma$ are the mean and variance; the same does not hold for the Lognormal distribution https://docs.scipy.org/doc/numpy-1.14.1/reference/generated/numpy.random.lognormal.html:
"Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from."
To simulate from the Lognormal distribution of $S_T$, note that $\ln S_T$ is normally distributed:
$$\ln S_{T}=\ln S_{0}+(r -{\frac {\sigma ^{2}}{2}})T+\sigma W_{T}\sim N(\ln S_{0}+(r -{\frac {\sigma ^{2}}{2}})T,\sigma T)$$
Hence you need to call:
np.random.lognormal(ln S_0+(r-sigma^2/2)*T, sigma*T)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
erratic results for numpy/scipy eigendecompositions
I am finding that scipy.linalg.eig sometimes gives inconsistent results. But not every time.
>>> import numpy as np
>>> import scipy.linalg as lin
>>> modmat=np.random.random((150,150))
>>> modmat=modmat+modmat.T # the data i am interested in is described by real symmetric matrices
>>> d,v=lin.eig(modmat)
>>> dx=d.copy()
>>> vx=v.copy()
>>> d,v=lin.eig(modmat)
>>> np.all(d==dx)
False
>>> np.all(v==vx)
False
>>> e,w=lin.eigh(modmat)
>>> ex=e.copy()
>>> wx=w.copy()
>>> e,w=lin.eigh(modmat)
>>> np.all(e==ex)
True
>>> e,w=lin.eigh(modmat)
>>> np.all(e==ex)
False
While I am not the greatest linear algebra wizard, I do understand that the eigendecomposition is inherently subject to weird rounding errors, but I don't understand why repeating the computation would result in a different value. But my results and reproducibility are varying.
What exactly is the nature of the problem -- well, sometimes the results are acceptably different, and sometimes they aren't. Here are some examples:
>>> d[1]
(9.8986888573772465+0j)
>>> dx[1]
(9.8986888573772092+0j)
The difference above of ~3e-13 does not seem like an enormously big deal. Instead, the real problem (at least for my present project) is that some of the eigenvalues cannot seem to agree on the proper sign.
>>> np.all(np.sign(d)==np.sign(dx))
False
>>> np.nonzero(np.sign(d)!=np.sign(dx))
(array([ 38, 39, 40, 41, 42, 45, 46, 47, 79, 80, 81, 82, 83,
84, 109, 112]),)
>>> d[38]
(-6.4011617320002525+0j)
>>> dx[38]
(6.1888785138080209+0j)
Similar code in MATLAB does not seem to have this problem.
A:
The eigenvalue decompositions satisfy A V = V Lambda, which is all what is guaranteed --- for instance the order of the eigenvalues is not.
Answer to the second part of your question:
Modern compilers/linear algebra libraries produce/contain code that does different things
depending on whether the data is aligned in memory on (e.g.) 16-byte boundaries. This affects rounding error in computations, as floating point operations are done in a different order. Small changes in rounding error can then affect things such as ordering of the eigenvalues if the algorithm (here, LAPACK/xGEEV) does not guarantee numerical stability in this respect.
(If your code is sensitive to things like this, it is incorrect! Running e.g. it on a different platform or different library version would lead to a similar problem.)
The results usually are quasi-deterministic --- for instance you get one of 2 possible results, depending if the array happens to be aligned in memory or not. If you are curious about alignment, check A.__array_interface__['data'][0] % 16.
See http://www.nccs.nasa.gov/images/FloatingPoint_consistency.pdf for more
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using LINQ to find duplicates across multiple properties
Given a class with the following definition:
public class MyTestClass
{
public int ValueA { get; set; }
public int ValueB { get; set; }
}
How can duplicate values be found in a MyTestClass[] array?
For example,
MyTestClass[] items = new MyTestClass[3];
items[0] = new MyTestClass { ValueA = 1, ValueB = 1 };
items[1] = new MyTestClass { ValueA = 0, ValueB = 1 };
items[2] = new MyTestClass { ValueA = 1, ValueB = 1 };
Contains a duplicate as there are two MyTestClass objects where ValueA and ValueB both = 1
A:
You can find your duplicates by grouping your elements by ValueA and ValueB.
Do a count on them afterwards and you will find which ones are duplicates.
This is how you would isolate the dupes :
var duplicates = items.GroupBy(i => new {i.ValueA, i.ValueB})
.Where(g => g.Count() > 1)
.Select(g => g.Key);
A:
You could just use Jon Skeet's DistinctBy and Except together to find duplicates. See this Response for his explanation of DistinctBy.
MyTestClass[] items = new MyTestClass[3];
items[0] = new MyTestClass { ValueA = 1, ValueB = 1 };
items[1] = new MyTestClass { ValueA = 0, ValueB = 1 };
items[2] = new MyTestClass { ValueA = 1, ValueB = 1 };
MyTestClass [] distinctItems = items.DistinctBy(p => new {p.ValueA, p.ValueB}).ToArray();
MyTestClass [] duplicates = items.Except(distinctItems).ToArray();
It will only return one item and not both duplicates however.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rxjs prevent subscribe in subscribe
I have an array of objects. I need to get array if ids, then call 2 APIs, then close the modal window.
My code is:
from(this.alerts)
.pipe(map(alert => alert._id))
.subscribe(alertIds => zip(
this.alertApi.someCall1(alertIds, ...),
this.alertApi.someCall2(alertIds, ...),
).subscribe(() => {
this.activeModal.close();
}),
);
Do you have any idea with preventing subscribe inside subscribe?
A:
Use switchMap rxjs operator to avoid nested subscriptions.
from(this.alerts)
.pipe(
map(alert => alert._id),
switchMap(alertIds => zip(
this.alertApi.someCall1(alertIds, ...),
this.alertApi.someCall2(alertIds, ...)
))
)
.subscribe(() => {
this.activeModal.close();
);
More information on switchMap operator can be found here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to set dropdown overlap other elements in materialize
I'm trying to set a dropdown to overlap other elements in materialize.
The problem I'm having is with the last collection item and its dropdown.
When you open the dropdown, it is placed underneath the other elements.
How can I have it overlap instead?
Here is demo jsfiddle:
https://jsfiddle.net/hgyj9r88/
<ul class="collection">
<li class="collection-item avatar">
<img src="images/yuna.jpg" alt="" class="circle">
<span class="title">Title</span>
<p>First Line <br>
Second Line
</p>
<a href="#!" class="secondary-content"><i class="material-icons">grade</i></a>
</li>
<li class="collection-item avatar">
<i class="material-icons circle">folder</i>
<span class="title">Title</span>
<p>First Line <br>
Second Line
</p>
<a href="#!" class="secondary-content"><i class="material-icons">grade</i></a>
</li>
<li class="collection-item avatar">
<i class="material-icons circle green">insert_chart</i>
<span class="title">Title</span>
<p>First Line <br>
Second Line
</p>
<a href="#!" class="secondary-content"><i class="material-icons">grade</i></a>
</li>
<li class="collection-item avatar">
<i class="material-icons circle red">play_arrow</i>
<span class="title">Title</span>
<p>First Line <br>
Second Line
<!-- Dropdown Trigger -->
<a class='dropdown-button btn' href='#' data-activates='dropdown1'>Drop Me!</a>
<!-- Dropdown Structure -->
<ul id='dropdown1' class='dropdown-content'>
<li><a href="#!">one</a></li>
<li><a href="#!">two</a></li>
<li class="divider"></li>
<li><a href="#!">three</a></li>
</ul>
</p>
<a href="#!" class="secondary-content"><i class="material-icons">grade</i></a>
</li>
</ul>
A:
The class .collection has overflow: hidden; if you set overflow: visible; to the ul you will see the dropdown.
Here is the jsfiddle working https://jsfiddle.net/hgyj9r88/2/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a .NET equivalent to Rails Console?
Rails Console is so useful for direct sanity-checking of your model. Is there an ASP.NET MVC equivalent?
Is it possible to mimic Rails Console behaviour using LinqPAD?
A:
Not really, since you're not inside the running application in the same way as with the Rails Console. - As Lloyd shows in his answer, it seems to be very much possible. Still seems that it's easier to use the Immediate Window if it is sufficient for what you are trying to achieve.
LINQPad is great anyway and I use it similarly to how I use the Ruby Interactive Ruby Shell (IRB).
The Immediate Window in the Visual Studio debugger can get you close to the same experience as the Rails Console gives. I hope that C# 5.0 will get us even closer because as of now you can't use lambda expressions and such.
A:
awesome - I discovered LinqPAD 4.38.03 (latest beta version) works perfectly well as a Rails Console substitute!
My ASP.NET MVC3 project is based on Entity Framework 4.2 (using the "database first" approach) which Linqpad integrates nicely with. I am able to reference my assembly as a connection and query the model, controller, repositories etc. interactively, just like in Rails Console!
These were my steps
In the Connection manager (to the left) click "Add connection"
click the radio labelled "use a typed data context from your own assembly"
click "Entity Framework dbContext POCO (4.1/4.2)", then "next"
use "browse" to locate the "path to custom assembly" (in your project)
click "choose" to select the dbContext class from your assembly
click "choose" to locate your project config file in "path to application config file"
type an optional connection name, click "next"
Finally, in your query window select your new assembly connection as the "Database" and that's it! You can now work with your assembly interactively.
For example, to inspect and test a controller: (first, in Query Properties, add a reference to System.Web.Mvc)
var controller = MyProject.Controllers.CustomerController();
controller.Index().Dump();
to "post" some data
var customer = new Customer() {name = "Brian"};
controller.Create(customer);
to see your new Customer in the database
Customers.Dump();
or if you have a repository
var repo = new Repository();
repo.GetCustomers().Dump();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Strange error checking if directory exists with Bash script
Here's a bash script I'm working on:
dir="~/path/to/$1/folder"
if [ -d "$dir" ]; then
# do some stuff
else
echo "Directory $dir doesn't exist";
exit 1
fi
and when I run it from the terminal:
> ./myscript.sh 123
Directory ~/path/to/123/folder doesn't exist
But that folder clearly does exist. This works normally:
> ls ~/path/to/123/folder
What am I doing wrong?
A:
The problem is that bash performs tilde expansion before shell parameter substitution, so after it substitutes ~/path/to/folder for $dir, it doesn't try to expand the ~, so it looks for a directory literally named with a tilde in it, which of course doesn't exist. See section 3.5 of the bash manual for a more detailed explanation on bash's expansions.
A:
try:
dir="$HOME/path/to/$1/folder"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fit a function to data so that fit is always equal or less than the data
I have a set of measurement data and I try to fit there a function (a Exp[b x] + c Exp[d x] - o). I have two problems:
The fit function does not converge nor after $500$ iterations.
The fit function always has to be equal or less than the data points.
Thank you for your help!
fitdata = {{-0.826333, 9.72503}, {-0.796121, 9.61975}, {-0.765909, 8.25744},
{-0.735697, 7.40448}, {-0.705485, 5.38543}, {-0.675273, 5.15899},
{-0.645061, 4.9356}, {-0.614848, 4.67804}, {-0.584636, 4.28955},
{-0.554424, 4.73144}, {-0.524212, 4.93957}, {-0.494, 4.80621},
{-0.463788, 5.77301}, {-0.433576, 3.39416}, {-0.403364, 1.73309},
{-0.373152, 1.4862}, {-0.342939, 1.4212}, {-0.312727, 1.49505},
{-0.282515, 1.35071}, {-0.252303, 1.28845}, {-0.222091, 1.25183},
{-0.191879, 1.43158}, {-0.161667, 1.39557}, {-0.131454, 1.40259},
{-0.101242, 1.36108}, {-0.0710303, 1.2265}, {-0.0408181, 1.23474},
{-0.0106061, 1.24481}, {0.0196061, 1.26526}, {0.0498182, 1.32446},
{0.0800303, 1.31866}, {0.110242, 1.35345}, {0.140455, 1.45935},
{0.170667, 1.58142}, {0.200879, 1.64947}, {0.231091, 1.72851},
{0.261303, 1.79931}, {0.291515,1.53534}, {0.321727, 1.76849},
{0.351939, 2.56439}, {0.382152, 3.65875}, {0.412364, 1.30584},
{0.442576, 2.4179}, {0.472788, 3.02307}, {0.503, 1.58539},
{0.533212, 1.45324}, {0.563424, 1.4743}, {0.593636, 1.42791},
{0.623849, 1.44165}, {0.654061, 1.56433}, {0.684273, 1.68152},
{0.714485, 2.1933}, {0.744697, 2.30194}, {0.774909, 2.29156},
{0.805121, 2.62207}, {0.835333, 3.09906}, {0.865546, 3.17169},
{0.895758, 4.08508}, {0.92597, 7.48046}, {0.956182, 4.48303},
{0.986394, 4.11621}, {1.01661, 4.18457}, {1.04682, 4.72107},
{1.07703, 5.77667}, {1.10724, 6.35589}, {1.13745, 6.41082},
{1.16767, 7.43164}, {1.19788, 9.28222}};
@ All - The bigger the choice, the harder it is to choose. Thank you for incredible nice and quick answers!
A:
Let's first solve it without constraints.
Using fitdata from your question one needs to set reasonable starting values.
You may have to experiment (I like to use Manipulate) to get in the ball park.
nlm = NonlinearModelFit[fitdata, a*Exp[b*x] + c*Exp[d*x] + o,
{{a, 0.1}, {b, 3}, {c, 0.3}, {d, -4}, {o, 1}}, x]
yields
nlm["BestFitParameters"]
(* {a -> 0.127629, b -> 3.38374, c -> 0.310767, d -> -4.07292,
o -> 1.02299} *)
Now plot it
Show[ListPlot[fitdata, PlotStyle -> Black],
Plot[nlm[x], {x, -1, 1.5}, PlotStyle -> Red]]
Constrained Solution
In order to implement the constraints we will create a list (one for each point) using Map.
Map[a*Exp[b*#[[1]]] + c*Exp[d*#[[1]]] + o <= #[[2]] &, fitdata]
I won't print the result here but you can see it in your notebook.
Now we want to include those constraints in the optimization. One form is to wrap the model in a list and add the constraints separated by commas. This can be done if we Apply the function Sequence to the list.
nlmConstrained = NonlinearModelFit[fitdata, {a*Exp[b*x] + c*Exp[d*x] + o,
Sequence @@Map[a*Exp[b*#[[1]]] + c*Exp[d*#[[1]]] + o <= #[[2]] &,
fitdata]}, {{a, 0.05}, {b, 4}, {c, 0.1}, {d, -5}, {o, 0.7}}, x]
the result is
nlmConstrained["BestFitParameters"]
(* {a -> 0.0579711, b -> 4.02179, c -> 0.0963365, d -> -5.49028,
o -> 0.725906} *)
and plotting it shows that the constraints are satisfied.
Show[ListPlot[fitdata, PlotStyle -> Black],
Plot[nlmConstrained[x], {x, -1, 1.5}, PlotStyle -> Red]]
I was pleasantly suprised to find that solver was fast despite having 68 constraints imposed.
A:
This answer provides two solutions both use Quantile regression.
The first uses sort of brute force fitting with a family of curves.
The second is similar to the one by Jack LaVigne, but uses QuantileRegressionFit on the second step, which in this case seems to be more straightforward.
This command loads the package QuantileRegression.m used below:
Import["https://raw.githubusercontent.com/antononcube/MathematicaForPrediction/master/QuantileRegression.m"]
1. QuantileRegressionFit only
Generate a family of functions:
funcs = Table[Exp[k*x], {k, -6, 6, 0.002}];
Length[funcs]
(* 6001 *)
Do Quantile regression fit with the family of functions:
qfunc = First@QuantileRegressionFit[fitdata, funcs, x, {0.01}]
(* 0. + 0.0125232 E^(-5.398 x) + 0.0930724 E^(-5.392 x) +
0.232695 E^(0.2 x) + 0.511794 E^(0.214 x) + 0.039419 E^(4.336 x) *)
and visualize:
Show[
ListPlot[fitdata, PlotStyle -> Black, PlotRange -> All],
Plot[qfunc, {x, -1, 1.5}, PlotStyle -> Red, PlotRange -> All]]
The found fitted function satisfies the condition to be less or equal of the data points, but it is made of too many Exp terms. So the next step is to reduce the number of Exp terms to two as required in the question.
We can visually evaluate the contribution of each of the terms in the found fit:
Plot[Evaluate[(List @@ qfunc)/qfunc], {x, -1, 1.5}, PlotRange -> All,
PlotLegends -> (List @@ qfunc)]
We pick two of the terms (plus the intercept) and call QuantileRegressionFit again:
qfunc2 =
First@QuantileRegressionFit[fitdata,
Prepend[(List @@ qfunc)[[{3, -1}]], 1], x, {0}]
(* 0.658637 + 0.105279 E^(-5.392 x) + 0.0414842 E^(4.336 x) *)
Show[ListPlot[fitdata, PlotStyle -> Black, PlotRange -> All],
Plot[qfunc2, {x, -1, 1.5}, PlotStyle -> Red, PlotRange -> All]]
2. NonlinearModelFit model followed by QuantileRegressionFit
First we find a model with the required functions:
nlm = NonlinearModelFit[fitdata,
a*Exp[b*x] + c*Exp[d*x] + o, {{a, 0.1}, {b, 3}, {c, 0.3}, {d, -4}, {o, 1}}, x]
nlm["BestFitParameters"]
(* {a -> 0.127629, b -> 3.38374, c -> 0.310767, d -> -4.07292,
o -> 1.02299} *)
Show[ListPlot[fitdata, PlotStyle -> Black],
Plot[nlm[x], {x, -1, 1.5}, PlotStyle -> Red]]
Using the model functions:
{Exp[b*x], Exp[d*x]} /.
Cases[nlm["BestFitParameters"], HoldPattern[(b | d) -> _]]
(* {E^(3.38374 x), E^(-4.07292 x)} *)
find the quantile regression curve that is below the data points (0. quantile):
qfunc =
First@QuantileRegressionFit[
fitdata, {1, Exp[b*x], Exp[d*x]} /.
Cases[nlm["BestFitParameters"], HoldPattern[(b | d) -> _]],
x, {0.0}]
(* 0. + 0.303621 E^(-4.07292 x) + 0.13403 E^(3.38374 x) *)
Plot the result:
Show[
ListPlot[fitdata, PlotStyle -> Black, PlotRange -> All],
Plot[qfunc, {x, -1, 1.5}, PlotStyle -> Red, PlotRange -> All]]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Waiting on Updater singleton
I'm looking for the best practise, for making background updater.
I have this sequence of activities
SplashScreen -> LoginScreen -> MainActivity
What i need is to perform update before MainActivity has started. I'm using volley lib for download. I want Activity/Singleton/Service/Something else, which starts simultaneously with SplashScreen. And start of MainActivity have to wait until the background Updater has finished. I want to
Updater object behavior:
Check version, if newer version exists, download archive with sources.
Try apply changes (parsing xml and lots of things that should crash).
Apply changes.
Start app.
My thoughts:
1) Make updater an Activity: But i want to download o lots of bits and 5 seconds of splashscreen wait should slow down this process. As i know, background activity doesn't exist. (Yeah, it does, and its called service...)
2) Make them an Service: I never used service, so i'm not sure it's the best way. After update there is 24 hours off timer. Is even possible to start Activity from service?
3) Singleton (static class, or something, what is not activity, nor service): As service, but there should be problem with acces options that needs context to it's running. If i get it, change context from Splashscreen to loginscreen shloud be the problem.
4) AsyncTaks: As previous, how to wait until asynctaks is done to start activity?
Did i miss something? Is some practise which fits my problem?
Can anyone give me some example of classes and their connection to each other, which would be the best solution of this problem?
A:
Option 4, AsyncTask, is a good candidate for what you want to do.
Option 1 (Activity) is not good because activities can be destroyed by the system for multiple reasons (e.g. screen rotation). Plus code invoked from activity lifecycle methods (onCreate, etc) execute on the UI thread. You do not want to perform network activity on this thread. It is a bad practice that leads to sluggish UIs. Newer versions of Android will throw exceptions if you attempt to do so (read up on Safe Mode).
Option 2 (Service) is not a bad one, but coding a service is not as simple as an AsncTask. Plus services tend to be used for longer running operations. Here is an SO post that explains this well: Android: AsyncTask vs Service.
Option 3 (Singleton) is not good as Android can kill your process at any time if memory is low. If your singleton has state, when the process is re-created, that state will be lost. There are ways to work around this, but they are difficult and error-prone.
So I suggest you read up on AsyncTasks. They are really quite useful in Android. They provide you with a thread from a pre-existing thread pool, and class methods that help you to ensure that your code is executing on the right type of thread (e.g. UI or background).
=========
So as this applies to your case:
Launch the AsyncTask at the appropriate time for your app. Most
likely in the LoginActivity.
In the "doInBackground" method, make your download call. Loop until the download is complete. When complete, let the method return.
Android will then call your task's onPostExecute method on the UI thread. Here you can end the current activity and start the new one.
Of course this is just one suggestion, and without knowing your app, I cannot say that it is optimal. Hopefully this gives you a taste of AsyncTask usage.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
GWT JSNI split method bug
I am developing a GWT application and I am obtaining a List containing the result of a select query. This select query has rows. Each row, has each element separated from the previous and the next by "::".
I am trying to split it using String.split, but it is taking ages to perform. I have read that currently (i am using GWT 2.5.1), the String.split method its quite bugged, sometimes almost taking x1000 times more than the JSNI method to perform; so i took that approach.
The JSNI method that i am using is the following (which i picked up from this same site):
public static final native String[] split(String string, String separator) /*-{
return string.split(separator);
}-*/;
But now, i am getting this error :
java.lang.ClassCastException: com.google.gwt.core.client.JavaScriptObject$ cannot be cast to [Ljava.lang.String;
And even if I write a .toString() at the end, the error becomes the following:
java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String;
I am calling this method like this :
String[] temp = split(str, "::");
In order to get the results from the split inside temp, for later usage.
str it is a String containing an iterator.next().
Could you please tell me what could i be missing or misunderstanding?.
Thank you in advance for your time,
Kind regards,
A:
A JavaScript list is not a Java array. While GWT uses JavaScript lists to emulate Java arrays, that doesn't mean that they are the same thing.
Instead you should return JsArrayString from your method, and use it that way, or just use the Java version of String.split which returns a real Java array.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reconnect to TCP/IP socket on NodeJS
I use "net" library to create TCP connection on my nodeJs.
root.socket = net.createConnection(root.config.port, root.config.server);
I'm trying to handle error when remote server is down and reconnect in Cycle.
root.socket.on('error', function(error) {
console.log('socket error ' + error);
root.reconnectId = setInterval(function () {
root.socket.destroy();
try {
console.log('trying to reconnect');
root.socket = net.createConnection(root.config.port, root.config.server);
} catch (err) {
console.log('ERROR trying to reconnect', err);
}
}, 200);
}
The trouble is that in case of remote server shutdown I still get en error and my nodeJS server stops.
events.js:72
throw er; // Unhandled 'error' event
^ Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
A:
You will need something like this:
var net = require('net');
var c = createConnection(/* port, server */);
function createConnection(port, server) {
c = net.createConnection(port, server);
console.log('new connection');
c.on('error', function (error) {
console.log('error, trying again');
c = createConnection(port, server);
});
return c;
}
In your case you are creating a new connection but you don't attach any error listener, the error is raised somewhere else in the execution loop and can not be caught by the "try / catch" statement.
P.S. try to avoid using "try / catch" statement, error handling in Node.JS is made using error listeners and domains, it can be useful only for JSON.parse() or other functions that are executed synchronously.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JQuery creating wrong URL in $.ajax method
I am wondering if there are any utility methods (perhaps similar to c# Path.Combine) to create URLs in jquery. I have a webapp. If I access it by typing http://mymachine/myapp/ in my web browser and then make $.ajax request with url='search', the request is made to http://mymachine/myapp/search. So far so good.
However, if I access my webapp by typing http://mymachine/myapp in my web browser, the app will load, but then if I make an $.ajax call with same url, jquery emits a request to http://mymachine/search - this is not what I want. How can I fix this problem?
A:
Use your server side language to set the application base url in js:
ex:
<script>
var baseUrl = '<%=Server.ApplicationPath%>';
</script>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create SVG object from string
How can I create new SVG object from a string in JavaScript?
Object to string
var str = new XMLSerializer().serializeToString(SvgDoc.getElementById(nameID));
String to object
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(str, "image/svg+xml");
But oDOM isn't an SVGGElement object.
A:
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(str, "image/svg+xml");
will give you a Document object. You can get the root element of a document via
var root = oDOM.documentElement;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
using request.user.is_authenticated() in Django project
When I try to do request.user.is_authenticated() I get a ValidationError: None is not a valid ObjectId
I'm trying to track down the problem but I do not what's causing it.I'm using MongoEngine (and MongoDB.)
I have the following in my settings.py:
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
'rs.claimutil.auth_backend.ClaimAuthBackend',
)
SESSION_ENGINE = 'mongoengine.django.sessions'
This is what I get:
Traceback: File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py"
in get_response
111. response = callback(request, *callback_args, **callback_kwargs) File "/Users/bastiano/Documents/ttsf/rsrv/views.py" in reserve
11. if not request.user.is_authenticated(): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py"
in inner
184. self._setup() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py"
in _setup
248. self._wrapped = self._setupfunc() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/middleware.py"
in
16. request.user = SimpleLazyObject(lambda: get_user(request)) File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/middleware.py"
in get_user
8. request._cached_user = auth.get_user(request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/init.py"
in get_user
101. user = backend.get_user(user_id) or AnonymousUser() File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/django/auth.py"
in get_user
149. return User.objects.with_id(user_id) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/queryset.py"
in with_id
923. return self.filter(pk=object_id).first() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/queryset.py"
in first
843. result = self[0] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/queryset.py"
in getitem
1136. return self._document._from_son(self._cursor[key]) File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/queryset.py"
in _cursor
579. self._cursor_obj = self._collection.find(self._query, File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/queryset.py"
in _query
375. self._mongo_query = self._query_obj.to_query(self._document) File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/queryset.py"
in to_query
202. query = query.accept(QueryCompilerVisitor(document)) File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/queryset.py"
in accept
267. return visitor.visit_query(self) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/queryset.py"
in visit_query
159. return QuerySet._transform_query(self.document, **query.query) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/queryset.py"
in _transform_query
720. value = field.prepare_query_value(op, value) File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/base.py"
in prepare_query_value
455. return self.to_mongo(value) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/base.py"
in to_mongo
451. self.error(unicode(e)) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mongoengine/base.py"
in error
203. raise ValidationError(message, errors=errors, field_name=field_name)
Exception Type: ValidationError at /rs/claim Exception Value: None is
not a valid ObjectId
Any ideas why this is happening? Is there an easier way to do user authentication in Django + MongoDB?
Views.py:
def claim(request):
if request.method == 'GET':
if not request.user.is_authenticated():
return shortcuts.redirect('rs/login')
all_b = dbutil.get_b(all=True)
return shortcuts.render_to_response('rs/index.html',
{'all_b':all_b},
context_instance=template.RequestContext(request))
elif request.method == 'POST':
The rest of the view is omitted for simplicity. I used ipdb to debug it and if not request.user.is_authenticated() is the problem. I tried using django.contrib.auth.decorators.login_required.decorator before, but it, too, failed.
A:
In one of my views I had the following:
r_v.obj.backend = 'mongoengine.django.auth.MongoEngineBackend', which is why Django was ignoring the AUTHENTICATION_BACKENDS in settings.py, and was never using my custom authentication backend.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does a mathematician choose on which problem to work?
Main question:
How does a mathematician choose on which problem to work?
An example approach to framing one's answer:
What is a mathematical problem - big or small - that you solved or are working on, how did you choose this problem, and why did/do you continue to work on it?
An earlier incarnation of this question asked also for problem sources, and about finding mathematics questions (and engaging in mathematical research) more generally; hopefully this revised version focuses it a bit more (though already posted answers should be understood as responses to the previous version).
As one example of what a retrospective look at a problem (problems) might look like, see the note (How the Upper Bound Conjecture Was Proved) provided by Richard Stanley in a comment below.
A:
I think that this question is somewhat similar to:
"How does a botanist decide which plants to look at?"
Well... a botanist always looks at lots of plants.
In the early phases of his/her career, a botanist will spend a lot a time studying well-known plants. Later on, a botanist will have learned to quickly recognise the commonly occurring plants so as to be able to quickly ignore them. He/she will then be able to focus their energy on rarer plants, or plants whose morphology is particularly interesting.
Even later, a botanist might have the opportunity to participate in expeditions to various remote parts of the planet, in order to search for plants that are new to science.
Now:
"How does a mathematician decide which problems to think about?"
Well... a mathematician thinks about a lot of stuff.
In the early phases of his/her career, a mathematician will spend a lot a time studying well-known constructions. Later on, a mathematician will have learned to recognise those problems that can be treated efficiently with well-known tools from those which are likely to be too hard. With the help of an adviser, he/she will then be able to focus their energy on problems that are at the right level of difficulty. Here, the meaning of "the right level of difficulty" always depends a lot on the expertise and background.
Experienced mathematicians have had the possibility to accumulate, throughout their interactions with colleagues, and by their own personal attempts at solving problems, a little collection of problems that are specialized enough so that no-one has really thought about them yet, and not too difficult for a graduate student. That's how graduate students often get their problems to work on.
The mathematicians who are no-longer graduate students have to constantly try to solve new problems. Their ability to find interesting problems (and to solve them) defines how good they are at their job.
A:
Here is one attempted answer (with the major caveat that I am not a professional mathematician). You actually have several questions, and so I will try to address the one in the title:
How does a mathematician choose on which problem[s] to work?
I emphasized the indefinite article (because different mathematicians, of course, have different approaches: an extreme example would be to compare Grothendieck and Erdos, with an interesting thought at MO 7155 in the third comment; more generally, see Freeman Dyson's Frogs and Birds) and pluralized the word 'problem' (because a mathematician may be working on several different problems, or parts of problems, at a time).
And so maybe I will comment briefly on one mathematician: Paul Cohen, who picked a rather tremendous problem (Hilbert's first problem, the Continuum Hypothesis) in 1962, and proved its independence in 1963. In MO 159935 I tried to hit the main points about how Cohen's thinking [may have] evolved, which benefited from the pair of answers to an earlier question I put up in MO 124011.
The key points, as I understand them, were:
A commanding interest in the problem, and, in taking on a big problem, a previously demonstrated mathematical aptitude (although in a different area, Cohen published On a conjecture of Littlewood and idempotent measures in 1960, which earned him the AMS Bôcher Prize in analysis when it was next given out);
A social network to support such work (consider, for example, Cohen's support in graduate school, his later interaction with Kleene, and his subsequent communication with Godel);
From (1) an eventual new idea (or new ideas); maybe these do not exist at the outset (cf. fedja's response to MO 124201) but something needs to convince you not only to pick up a problem, but also to stick with it - consider Cohen's combination of: thinking model-theoretically (I refer to his familiarity with Skolem's work, but this was not unique to set theorists at the time), thinking with "decision procedures" (I refer to his notion of building a model up slowly in a way that, I think, differed from the work of other set theorists at the time), and his familiarity with the Post Problem and its resolution via the priority method;
The space/time to think about the problems deeply: if you are worried about getting tenure, or keeping a job, then attacking a major problem -- as Cohen did -- may not be the best approach (consider also that Cohen has an important realization during his off-time, i.e., while driving around near the Grand Canyon; this seems to be a theme in mathematical insights, from Poincare to Hamilton).
I do not want this to grow too long, and I hope working mathematicians do not feel mis-represented by these few observations (and will correct them as necessary!). I think that if you re-summarize the four points above as some sort of themes, then you may find something like:
Interest in the problem (no surprise, I hope);
People to support you, work with you, advise you, etc (sometimes this social aspect seems to surprise non-mathematicians -- maybe it is less surprising in the context of this site, MO!);
New ideas and ways to approach the problem;
Other environmental resources (e.g., job stability, time to think).
There should be many examples for each theme (e.g., for 1: Pereleman's proof of the Soul Conjecture before the geometrization conjecture) and exceptions (e.g., for 2: Yitang Zhang, it seems) and other parts that were excluded (the interaction of working in different areas, on different problems, with different people) and even contemporary changes (the communication that occurs through MO or polymath projects may affect 1, 2, and 3 for the better; the "publish or perish" mindset of some institutions, or a reduction in funding, may affect 4 for the worse).
Still: I hope this "attempted answer" is helpful (even if only in a minor way).
A:
I think this is a difficult and significant question, and I have appreciated the answers to date. I am hoping to learn more about this topic from further answers, since I have struggled with this challenge all my career. I think it is widely felt that great problem finders are more rare than great problem solvers. Still I am motivated to try to answer it myself although I don’t feel well qualified to do so. And I hope I may learn something by thinking about it. I suggest a naive preliminary question: is one trying to solve the deepest possible problem, or to have as much fun as possible? Some of us are, to recall David Riesman, “inner directed”, and want to emerge from a private space with a solution of the Riemann hypothesis, and some of us are “other directed”, and just want to show up at a meeting with our advisor with a solution of his/her favorite problem.
Also, there is the question of how should a research problem be ideally chosen, say by a master, versus the question of how should the modestly gifted among us actually proceed, given our limitations. Thus even if one does hope to enter into research on a significant problem as soon as possible after tools begin to exist for its attack, only a select group of people may realize when this occurs.
So for this it is beneficial to maintain contact with the words and writings of those leaders who have command of the field one works in. It also helps if they are conversant with pregnant but little known literature, such as the papers of K. Petri, shown to me in the late 1960’s by my first advisor Alan Mayer, or the book of Wirtinger on Theta functions revealed to me by my second advisor C.H. Clemens.
After being launched by these generous gifts, an opportunity occurred again during a research postdoctorate at Harvard, privileged to be among the giants: Mumford, Griffiths, Hironaka, Mazur, Kazhdan, Bott, Zariski, a fabulous group of students: Bob Friedman, Joe Harris, Ron Donagi, Dave Morrison, Ziv Ran, Rick Miranda,.... and the many other stars who came there - Igusa, Fay, Teissier, Freitag, Tai, Siu, Ramanan, .....
To take advantage of this opportunity, I moved my family to Cambridge and lived on an NSF stipend so small I sold my car the first year for food, and had to decline the second year entirely. So you could say that to pursue excellent current problems from a privileged perspective as a young researcher, I embraced temporary poverty. The benefit was a seat at the theater to which the most active players in my field came to present their latest work. At this point it was very stimulating to try to answer any question whose answer was interesting to one of my mentors but unknown to them.
Those comments are from/for someone of average ability trying to compete for early progress on problems that are of wide spread interest and that may bring notoriety. Fortunately, as much or more satisfaction is found by working on problems that just appeal to our imagination, and that match our own expertise. At this later stage we are moving away from dependence on experts, to instruct us and supply us with topics and ideas, and are beginning to follow our own interests.
So here one begins to acquire some expertise oneself, from study and independent work. It then begins to be ones own responsibility to maintain up to date awareness of the progress of others and to try to apply it to questions that appear of interest. It seems crucial here to attend talks by the best workers and to read their works. At this point one reaches the mystical stage of being able to predict what the answer to a question will likely be, before one has solved it. One may even attempt to compete with recognized experts on the same problems. Success however will depend on more than good intuition, but also on mastery of technical tools to complete the work.
Some very strong individuals work more privately and still attack more public problems. I recall William Fulton saying he wanted to try to understand Schubert’s work on enumerative geometry, so he started reading it and filling details, but I don’t recall how much the fact it was a Hilbert problem influenced him, if at all. My colleague Bob Rumely was attracted to a Hilbert problem on finding procedures for solving integer equations, and tweaked it brilliantly to arithmetic integers. So another problem - finding technique is to take a well known one, solved or unsolved, and modify it intelligently.
The third stage it seems to me, is having such a wide awareness of the state and likely development of a field or area, that one sees likely problems on every hand and invites new talent to work on them. If one succeeds here, one may create a team and an environment of creative research that feeds on itself, and all the players may learn to add to the palette of interesting problems.
By the way, I would very much like to read accounts from some of the participants here of how they found a few of their favorite research problems. Going out on a limb here, I suspect a strong element of randomness will be noted.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change executable icon through ilasm
I have a installer app with a embedded .resx file with some information, like server name, port, password etc...
I have to generate this installer (this process is automated, and is done through our website) for each customer. This is working fine
I use ildasm for disassembler and replace the resx file, and then I use ilasm to make .exe again.
But after this process the .exe lost our icon, putting the default one in it's place.
I cannot find a way to change the default icon.
Thanks
A:
You are missing out on a fairly obscure detail in a C# program. The executable the compiler generates also contains unmanaged resources. Required because Windows doesn't know anything about managed resources. This is something you can see with Visual Studio. Use File + Open + File and select a .exe generated by the C# compiler. RTM edition required, it doesn't work for Express.
You'll see at least 3 nodes for your program:
RT_MANIFEST contains the manifest for the executable. Very important on later Windows versions, it declares the program compatible with UAC. It prevents Windows from treating your program like an earlier Windows program that needs to be lied to when it does UAC verboten things like trying to write files to protected directories and trying to create registry keys in HKLM. The content of the manifest is a default one in most programs, you can get a custom one with the "Application Manifest File" project item template.
"Version" contains the version resource for the executable. It contains the info you see when you look at the properties of the executable with Windows Explorer. Its content is auto-generated from the [assembly:] attributes in your AssemblyInfo.cs source code file.
"Icon" contains the icon resource for your program. The one you don't have anymore.
You'll need to use the /resource option for ilasm.exe to embed those unmanaged resources into the patched executable. That requires a .res file, the compiled version of the unmanaged resources, produced by the rc.exe Windows SDK tool. Note how this is also exposed in the Project + Properties, Application tab, Resource file radio button.
You cannot ignore this requirement, you can live without the Icon resource but not the manifest, especially not in an installer program. Getting the .res file out of the original executable is going to be difficult, fairly sure that ildasm.exe doesn't support decompiling it. If a tool like Resource Hacker doesn't do it then you'll need to create a .res file for your program. Or review the wisdom of using ildasm.exe to do what you wanted to do.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Maven: iterate a directory of files inside Maven's resource directory
I have a set of files in my Maven resource folder:
+ src
+ main
+ resources
+ mydir
+ myfile1.txt
+ myfile2.txt
How can I iterate mydir? Not only in Eclipse, but when running JUnit tests from the command line, and from a dependent jar.
File mydir = new File("mydir");
for (File f : dir.listFiles()) {
dosomething...
}
Thanks for a hint!
A:
Nutshell, roughly:
URL pathUrl = clazz.getClassLoader().getResource("mydir/");
if ((pathURL != null) && pathUrl.getProtocol().equals("file")) {
return new File(pathUrl.toURI()).list();
}
Tested; Groovy:
def resourcesInDir(String dir) {
def ret = []
pathUrl = this.class.getClassLoader().getResource(dir)
if ((pathUrl != null) && pathUrl.getProtocol().equals("file")) {
new File(pathUrl.toURI()).list().each {
ret << "${dir}/${it}"
}
}
ret
}
files = resourcesInDir("tmp/")
files.each {
s = this.class.getResourceAsStream(it)
println s.text
}
A:
In the end, this is what I came up with to handle accessing files within referenced jars:
public class ResourceHelper {
public static File getFile(String resourceOrFile)
throws FileNotFoundException {
try {
// jar:file:/home/.../blue.jar!/path/to/file.xml
URI uri = getURL(resourceOrFile).toURI();
String uriStr = uri.toString();
if (uriStr.startsWith("jar")) {
if (uriStr.endsWith("/")) {
throw new UnsupportedOperationException(
"cannot unjar directories, only files");
}
String jarPath = uriStr.substring(4, uriStr.indexOf("!"))
.replace("file:", "");
String filePath = uriStr.substring(uriStr.indexOf("!") + 2);
JarFile jarFile = new JarFile(jarPath);
assert (jarFile.size() > 0) : "no jarFile at " + jarPath;
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
if (jarEntry.toString().equals(filePath)) {
InputStream input = jarFile.getInputStream(jarEntry);
assert (input != null) : "empty is for " + jarEntry;
return tmpFileFromStream(input, filePath);
}
}
assert (false) : "file" + filePath + " not found in " + jarPath;
return null;
} else {
return new File(uri);
}
} catch (URISyntaxException e) {
throw new FileNotFoundException(resourceOrFile);
} catch (IOException e) {
throw new FileNotFoundException(resourceOrFile);
}
}
private static File tmpFileFromStream(InputStream is, String filePath)
throws IOException {
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1,
filePath.lastIndexOf("."));
assert (fileName != null) : "filename cannot be null for " + filePath;
String extension = filePath.substring(filePath.lastIndexOf("."));
assert (extension != null) : "extension cannot be null for " + filePath;
File tmpFile = File.createTempFile(fileName, extension);
// tempFile.deleteOnExit();
assert (tmpFile.exists()) : "could not create tempfile";
OutputStream out = new FileOutputStream(tmpFile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
is.close();
out.flush();
out.close();
assert (tmpFile.length() > 0) : "file empty "
+ tmpFile.getAbsolutePath();
return tmpFile;
}
public static File getTempFile(String resourceOrFile) throws IOException {
InputStream input = getInputStream(resourceOrFile);
File tempFile = IOUtils.createTempDir();
tempFile.deleteOnExit();
FileOutputStream output = new FileOutputStream(tempFile);
byte[] buffer = new byte[4096];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
output.close();
input.close();
return tempFile;
}
public static InputStream getInputStream(String resourceOrFile)
throws FileNotFoundException {
try {
return getURL(resourceOrFile).openStream();
} catch (Exception e) {
throw new FileNotFoundException(resourceOrFile);
}
}
public static URL getURL(String resourceOrFile)
throws FileNotFoundException {
File file = new File(resourceOrFile);
// System.out.println("checking file ");
// is file
if (file.exists()) {
// System.out.println("file exists");
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
throw new FileNotFoundException(resourceOrFile);
}
}
// is resource
if (!file.exists()) {
// System.out.println("file resource");
URL url = Thread.class.getResource(resourceOrFile);
if (url != null) {
return url;
}
url = Thread.class.getResource("/" + resourceOrFile);
if (url != null) {
return url;
}
}
throw new FileNotFoundException(resourceOrFile);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get innerHtml of elements ignoring a specific id
I'm trying to get the innerHTML from a div but I need to ignore the divs inside it that have a specific id.
In the bellow sample, I need to get all #data innerHtml but ignore div#ignoreme.
<div id="data">
<div id="ignoreme">ignore</div>
<p>line</p>
this is another line
</div>
I tried doc.DocumentNode.SelectSingleNode("//*[@id='data']").SelectNodes("//*[not(@id='ignoreme')]");
But it isn't working, this always returns the full html document (!?)
So, is this possible with html agility pack, XPath?
A:
Try this :
var sol = doc.DocumentNode.SelectSingleNode("//*[@id='data']")
.SelectNodes(".//*[not(@id='ignoreme')]").ToList();
Or you can do this instead:
var sol1 = doc.DocumentNode.SelectSingleNode("//*[@id='data']")
.Descendants()
.Where(p => p.Id != "ignoreme")
.ToList();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to compare two rows in pandas (across all columns), and sum the output?
I have data like this-
User1 User2 User3 User4 User5 User6 User7 User8
w1 1 1 1 1 0 1 1 1
w2 0 1 0 0 1 1 1 1
w3 0 0 1 1 1 1 1 1
w4 1 1 1 0 0 0 0 1
w5 1 0 1 0 1 1 1 0
w6 1 1 1 1 1 1 1 1
Now what I want to do is compare every two consecutive weeks, and find all cases where the change is 1->0 .
So output for the above data would be something like this-
Column
w1 n/a
w2 3
w3 1
w4 4
w5 2
w6 0
A:
could also do it like this:
(df > df.shift(-1)).sum(axis=1)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python Creating a nested list with random module
Let's say I want to create a nested list with number sequence, and I want no repeated list sequence.
i.e. I would like something like this: [[1,2,3,4],[2,1,3,4],[4,2,3,1]] ,where the len of list depend on how many non repeated number sequence I could generate in limited attempt (four attempts in below case)
So here my first attempt:
import random
rng = random.Random()
bd =list(range(4))
i = 0
result =[]
while i <4:
rng.shuffle(bd)
if bd not in result:
result.append(bd)
i +=1
print(result)
I created the a list bd = [0,1,2,3] first before entering the while loop.
While running the above code, I got surprisingly only one element in my nested list every time.
Result: [[1, 2, 0, 3]]
But if I modify the code a little bit, it works as I expected.
Here my modified code:
import random
rng = random.Random()
i = 0
result =[]
while i <4:
bd =list(range(4))
rng.shuffle(bd)
if bd not in result:
result.append(bd)
i +=1
print(result)
Result: [[3, 2, 0, 1], [1, 0, 3, 2], [0, 1, 3, 2]]
What I do is just reset the list bd in every loop over again.
As per my understanding the list bd would be shuffled in every loop, so resetting bd to [0,1,2,3] should be meaningless.
Could somebody explain to me why the modified code works? Thanks.
A:
Lists and similar objects in Python are referred to by reference. Consider the following simple example:
a_list = [1,2,3,4,5]
another_list = []
for i in range(5):
another_list.append(a_list)
a_list[0] = i + 10
print(another_list)
You would expect the output to be:
[[10, 2, 3, 4, 5], [11, 2, 3, 4, 5], [12, 2, 3, 4, 5], [13, 2, 3, 4, 5], [14, 2, 3, 4, 5]]
However, the output you see is:
[[14, 2, 3, 4, 5], [14, 2, 3, 4, 5], [14, 2, 3, 4, 5], [14, 2, 3, 4, 5], [14, 2, 3, 4, 5]]
Every time you call another_list.append(a_list), you append a reference to a_list. You then change a_list, and previously appended references point to the changed list.
At the end, a_list is equal to [14, 2, 3, 4, 5], and another_list contains five identical references to this list.
Back to your case. To prevent this from happening to you, you can create a copy of the list every time you append it, as documented here:
import random
rng = random.Random()
i = 0
result =[]
while i <4:
bd =list(range(4))
rng.shuffle(bd)
if bd not in result:
# Use [:] to create a slice of bd which actually contains the whole list
result.append(bd[:])
i +=1
print(result)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Obfuscate PHP code
I create software using PHP. I'm going to sell this software so I need to protect my source code so that nobody can view it. How can I protect my PHP code so that the software still functions the same?
I also need to bind the software to a particular, authorized PC. It should not run on any other PC. How can I do that? Should I encrypt using LAN MAC address? Does anyone have any other ideas?
A:
I put together the following list a ways back - don't know if they are all current, or how many are now free, but you should find something useful here:
About:
Wikipedia article: PHP Accelerator
Comparison of APC, Zend, xCache, & the Zend Framework
Software:
Safeyar (Best)
PHP's APC (PECL page)
RoadSend
Turck-mmcache
eAccelerator
PHP-Accelerator
SourceGuardian
NuSphere Nu-coder
Gridinsoft
IonCube SA-Encoder.php
Another thread on SO that adds a few more (check it out):
Can I encrypt PHP source or compile it so others can't see it? and how?
Zend Guard
BCompiler (PECL page)
PHC
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What could explain over 5,000,000 System.WeakReference instances on the managed heap?
I have been running load tests against a production ASP.NET web application and am seeing a huge number of System.WeakReferences created on the heap. Within about 15 minutes under load managed heap memory has shot up to about 3GB and I have approximately 5,000,000 references to System.WeakReference. Performing a forced garbage collection of all generations does not release these references.
I have seen posts about the __ENCLIST helper class which if assemblies are compiled in debug can create WeakReferences to all objects which are created, at first I thought this was the problem, but have verified all deployed assemblies are built in release.
I have been using WinDbg to debug the process, here's the final few lines of !dumpheap -stat
000007fef788e0c0 39253 18510000 System.Collections.Hashtable+bucket[]
00000000021bf120 94336 151023192 Free
000007fef7887e98 5959 189838752 System.Char[]
000007fef7874390 517429 589750224 System.Object[]
000007fef78865a0 1531190 1230824112 System.String
000007fef787dab8 51723338 1655146816 System.WeakReference
As you can see about 1.5GB of memory has been consumed by these System.WeakReferences.
Does anyone have any idea what could be creating all these WeakReferences?
A:
So it turns out I had a System.WeakReference leak due to dynamically creating large numbers of System.Diagnostics.TraceSwitch instances, internally TraceSource/TraceSwitch allocates a WeakReference to the new TraceSource/TraceSwitch and puts the WeakReference into a list. Although the WeakReference allows the TraceSource/TraceSwitch to be garbage collected, the WeakReference itself will never be freed resulting in a memory leak.
A little more info can be found here
http://msdn.microsoft.com/en-us/library/system.diagnostics.tracesource(VS.80).aspx
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to Return A File and a strongly Typed data at the same time?
I am using asp.net mvc 1.0 and I want to return a XML file but I also want to return a strongly typed data back so I can update some fields.
Like the XML file will contain users who failed to be inserted into the database. So I want that to appear as a dialog save box what asp.net mvc return file() would do.
However I also want to return on the page like values like how many users failed to be added, how many users where added, etc.
So I want to use scafolding with the class file I want to pass it along. If this was a view I could pass it along as an object model but I don't see a parameter for that in File().
I also don't want to save the xml file onto the harddrive I want to do it through memory. So have a link that would display on the page to download the file and show the the data I want would not be desired.
A:
I could be wrong, but I think you'll need to use JavaScript for this. What your're trying to do is a limitation of HTTP and from my understanding of HTTP, you can only return one file type per response since the protocol is a request->response.
You can have MVC return the strongly typed view in addition to the XML file name inside the ViewData. Then have a JavaScript function change the window.location property to the file's URL (or make a new window).
I'm not sure about the exact details on how to gracefully have the JavaScript spit the file out like alot of download websites have it.
Edit:
I found how to gracefully automate the download process, check this question out:
JavaScript automatic download of a file
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to solve x in y for both are vectors?
Solve $x$ in $y$ with the following equation $$-y+x^Tyx=0$$ where $x,y \in \mathbb{R}^n$. It could be verfied that the solution is $x=\frac{y}{||y||}$, could someone help explain how to achieve such a solution.
A:
If $y$ is the zero vector then this equation holds for all $x$ and we're done, so now let's only consider the case where $y$ is nonzero. We have
$$(x^\top y) x = y$$
Notice that $x^\top y$ is a scalar. So $x$ must be a scalar multiple of $y$ for this equation to have any chance of holding. Which? Set $x = \lambda y$; then the equation says
$$(\lambda y^\top y) \lambda y = y$$
Which means that
$$\lambda^2 (y^\top y) = 1$$
so
$$\lambda = \frac{1}{\sqrt{\big(y^\top y\big)}} = \frac{1}{||y||}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Extract number float in exponential format from a bunch of long paths
I have a lot of strings corresponding each one to the path of files.
I would like to extract number in exponential format in each string.
For example, I have :
../../Analysis_Pk_vs_Step_BEFORE_NEW_LAUNCH_13_DECEMBRE_22h57/Archive_WP_Pk_der_3_pts_step_7.27168772219203e-07/wm_up
and I would like to extrat the float number : 7.27168772219203e-07
I would like to avoid using the splitmethod (with _ separator).
So I tried with python regexp like but I can't find which method to use (findall, research or sub) ?
If someone could help me to achieve this in a simple or short way (independently from wm_up substring since it may be other substrings (like this wm_dw for example)).
UPDATE 1: Sorry, I didn't well explain all the issue :
I would like to extract number since I want to sort in ascending order all these long srings. I would like to use natsorted:
For example, I have initialy :
../../Analysis_Pk_vs_Step_BEFORE_NEW_LAUNCH_13_DECEMBRE_22h57/Archive_WP_Pk_der_3_pts_step_9.301510038746646e-06/wm_up
../../Analysis_Pk_vs_Step_BEFORE_NEW_LAUNCH_13_DECEMBRE_22h57/Archive_WP_Pk_der_3_pts_step_9.301510038746646e-06/wm_dw
../../Analysis_Pk_vs_Step_BEFORE_NEW_LAUNCH_13_DECEMBRE_22h57/Archive_WP_Pk_der_3_pts_step_9.437191487625705e-05/wm_up
../../Analysis_Pk_vs_Step_BEFORE_NEW_LAUNCH_13_DECEMBRE_22h57/Archive_WP_Pk_der_3_pts_step_9.437191487625705e-05/wm_dw
This is the result of natsortedof array of paths : as you can see, the ascending order takes into acccount the first digits and not the value of float exponential number (the real value) that I would like to extract. I would like to select by the ascending order of this value.
I hope you understand.
A:
Here is the code:
l = [
'../../Analysis_Pk_vs_Step_BEFORE_NEW_LAUNCH_13_DECEMBRE_22h57/Archive_WP_Pk_der_3_pts_step_9.301510038746646e-06/wm_up',
'../../Analysis_Pk_vs_Step_BEFORE_NEW_LAUNCH_13_DECEMBRE_22h57/Archive_WP_Pk_der_3_pts_step_9.301510038746646e-06/wm_dw',
'../../Analysis_Pk_vs_Step_BEFORE_NEW_LAUNCH_13_DECEMBRE_22h57/Archive_WP_Pk_der_3_pts_step_9.437191487625705e-05/wm_up',
'../../Analysis_Pk_vs_Step_BEFORE_NEW_LAUNCH_13_DECEMBRE_22h57/Archive_WP_Pk_der_3_pts_step_9.437191487625705e-05/wm_dw'
] # the input that we have
# regex from https://stackoverflow.com/a/4703508/7434857
numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?'
rx = re.compile(numeric_const_pattern, re.VERBOSE) # compile the regex
l.sort(key=lambda x: (float(rx.findall(x)[-1]),x))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Получение значений по заранее неизвестному ключу в JSON (Java Gson)
Занимаюсь поддержкой тестового кода Java по обработке запросов с сервера при помощи библиотеки Gson.
Все было хорошо, до недавнего времени.
Входные данные: есть массив из 28000+ строк, приведу часть JSON с интересующей частью:
{
"status": {
"code": code,
"message": "message"
},
"data": {
"datas": [
{
"id": idHere,
"date_gmt": "2020-08-04T07:01:47",
"title": "title1",
"status": "publish",
"data_category": [
263,
495,
492,
68
],
"is-bonus-data": false,
"data-poster": "link here",
"data-preview-sprite": "link here",
"sprite": "link here",
"data-links": {
"3D 180 01_trailer": "link here",
"3D 180 02_trailer": "link here",
"3D 180 03_trailer": "link here",
"3D 180 04_trailer": "link here",
"3D 180 05_trailer": "link here"
},
"data-positions": [
"data-positions1",
"data-positions2"
],
...
}
Данный JSON описан в классе, и при получении все нормально парситься, но...
В последнее время в поле "data-links" стали приходить объекты с ключами, отличающиеся от "стандартных" - "3D 180 01_trailer_001", "3D 360 03_trailer" и т.д. По началу было принято решение добавлять эти ключи как поле класса, и собственно парсить еще и по ним, но сам класс data-links уже раздулся до невероятных размеров.
Класс, который описывает
public class DataLinks {
@SerializedName("3D 180 01_trailer")
@Expose
private String _3D18001Trailer;
@SerializedName("3D 180 02_trailer")
@Expose
private String _3D18002Trailer;
@SerializedName("3D 180 03_trailer")
@Expose
private String _3D1803KTrailer;
@SerializedName("3D 180 04_trailer")
@Expose
private String _3D1804KTrailer;
@SerializedName("3D 180 05_trailer")
@Expose
private String _3D18005Trailer;
}
Вопрос: как обеспечить тестам "вытаскивать" значения по ключам, которые заранее неизвестны?
Смотрел ответы google, самые разные, где люди приводят примеры, самый подходящий был здесь: Как разобрать динамический ключ JSON во вложенном результате JSON, но код начинает плеваться эксепшенами при попытке адаптации.
A:
Можете использовать java.util.Map:
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
@Data
static class Test {
@SerializedName("data-links")
private Map<String, String> dataLinks;
}
public static void main(String[] args) {
String json =
"{" +
"\"data-links\": {" +
"\"3D 180 01_trailer\": \"link here\"," +
"\"3D 180 02_trailer\": \"link here\"," +
"\"3D 180 03_trailer\": \"link here\"," +
"\"3D 180 04_trailer\": \"link here\"," +
"\"3D 180 05_trailer\": \"link here\"" +
"}" +
"}";
Test test = new Gson().fromJson(json, Test.class);
System.out.println(
test.dataLinks.entrySet().stream()
.map(e -> e.getKey() + ": " + e.getValue())
.collect(Collectors.joining("\n")));
}
}
Результат:
3D 180 01_trailer: link here
3D 180 02_trailer: link here
3D 180 03_trailer: link here
3D 180 04_trailer: link here
3D 180 05_trailer: link here
|
{
"pile_set_name": "StackExchange"
}
|
Q:
fancy header/footer on pages with chapter beginning
I'd like to produce report class document with one style of page numbering.
I've declared:
\usepackage{fancyhdr}
\fancyfoot[R]{\thepage}
\pagestyle{fancy}
but on pages with new chapter the page numbers are centered.
How can I protect my fancy setting form overwriting by chapter settings or how can I define my own header and footer for those pages?
Thanks for any approach.
A:
Make known the plain page style to fancyhdr
\fancypagestyle{plain}{%
\fancyhf{}\fancyfoot[R]{\thepage}%
\renewcommand{\headrulewidth}{0pt}}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does Internet Explorer have certain JS you can’t use?
I have a loan repayment calculator that works fine in all other browsers, but not running in IE11.
I have looked if IE11 has certain JS you can’t use and changed some of my let’s to var, but no luck.
<script>
function loanRepay(){
//Present Value
var pv = (parseFloat((document.getElementById("AB").value).replace(/[&\/\\#,+()$~%'":*?<>{}]/g,''), 10));
//Interest Rate (Compounded Monthly)
var r = ((parseFloat((document.getElementById("IR").value).replace(/[&\/\\#,+()$~%'":*?<>{}]/g,''), 10)) / 100) / 12;
//Number of Compounds in a Period - Compounded monthly
var n = (parseFloat((document.getElementById("TL").value).replace(/[&\/\\#,+()$~%'":*?<>{}]/g,''), 10));
//Payments per Month
var pay = pv * (r / (1 - (1 + r)**-n));
document.getElementById("pay").innerHTML = "$" + pay.toFixed(2);
//Interest Paid
var interest = (pay * n) - pv;
document.getElementById("interest").innerHTML = "Interest Paid $" + interest.toFixed(2);
//Total Payment
var total = interest + pv;
document.getElementById("total").innerHTML = "Total Amount $" + total.toFixed(2);
//if form isn't filled out correctly
if (isNaN(total))
{ alert('Please fill all fields with numerical values before pressing calculate.');} else{};
}
</script>
IE isn’t throwing any errors, it just isn’t running. I am still learning JS and I think it is pretty simple JS, so I am not sure why it isn’t running.
A:
Exponentiation operator(**) is an ES2016+ feature and it is not supported in IE 11. Change this line to:
var pay = pv * (r / (1 - Math.pow(1 + r, -n)));
You can set up babel and its presets in your project to target specific browsers. If it is a small project or it gets too complicated, you can just paste your code in Babel REPL to get the transpiled code.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sort objects with duplicate keys
I need a long list of objects ordered by one of they're parameters. What is the fastest way to do this in C++? I need to be able to add and remove elements to this list and still be sorted by that specific parameter.
Class Foo {
private:
int rank;
}
I want all my Foo objects to be listed in ascending order and when a new one is added or deleted it should take the right spot in the order. There can also be more than one object with the same rank so key-value is not possible.
Any idea how I can do this in C++? I was looking at make_heap() but I'm not sure how to use it (or if it can be used) with objects.
A:
First you should probably define operator< for Foo (something like this)...
inline bool operator< (const Foo& lhs, const Foo& rhs) {
return lhs.rank < rhs.rank;
}
which will need to be declared as a friend of Foo's:
class Foo {
public:
explicit Foo(int rank_init) : rank(rank_init) {}
friend bool operator< (const Foo&, const Foo&);
private:
int rank;
};
Now you can create a std::multiset<Foo> which will keep the Foos sorted ascending by rank, e.g.
std::multiset<Foo> foo_multiset;
foo_multiset.insert(Foo(5)); // 5
foo_multiset.insert(Foo(3)); // 3, 5
foo_multiset.insert(Foo(1)); // 1, 3, 5
foo_multiset.insert(Foo(3)); // 1, 3, 3, 5
size_t erased_count(foo_multiset.erase(Foo(3))); // 1, 5 (erased_count == 2)
There are no guarantees however that this will be the "fastest" option in your particular case. You'll need to profile for that. Depending on the number of elements, the frequency of insert/erase operations, and the STL implementation, you could find that a sorted std::vector<Foo> better suits your needs.
Scott Meyers' Effective STL describes how this could be the case in Item 23.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.