Is using a thermal camera an effective method to locate mold & moisture behind finished walls in a basement?

Question: My basement is finished and there are signs that I have leaks or some mold.
The smell is not very strong but I can feel it for the first few seconds when I enter the basement, after that it instantly disappears in the sense that I can not smell it anymore.
I am planning to rent a infrared thermal camera to see if this can help with locating the problem.
Is such a camera effective in these situations ?
PS: I have also seen some DIY or consumer grade cameras which can be attached to an android phone in order to get the infrared picture. Has anyone tested these ? Any links to what you tested would be much appreciated
Here is one such a camera http://obtain.thermal.com/product-p/uw-aaa.htm
Comment: You usually smell mildew more than mold. What region are you in? Is it humid in the basement?
Comment: Ontario near the lakes but on higher lands. No it is not humid. Interesting fact, as the temperature dives under zero outside the smell is gone! completely gone! weird. Must be outside originated water, very close to ground level because it freezes
Comment: Have you checked the usual culprits outside? (Ground sloping towards foundation, missing gutters, plugged downspouts, no splashblocks, etc). I know that won't fix the current issue but might help with future problems.
Comment: I have tons of posts on this. I am waiting for the warmer weather to fix what I know that I have to fix or check. Disconnec the gutters from drain is one and the patio slope is the second. Epic threads posted around here :-)
Comment: Oh! This is related to the patio. Yea, it sounds like that's the ultimate culprit here. Fix that first! And good luck! What may be happening is water is hitting your foundation, running down to your footer, then coming under the wall at the footer. If that's the case, you may be able to just cut out the lower 1' or so of sheetrock and insulation and replace just that.
Answer: I doubt it. I'd assume that any water which has made its way far enough into your house, to wet the backside of drywall, would have already acclimated. It's hard enough to find gaping holes in the exterior of a building by scanning a panel of drywall.
Thermal cameras are used to find heat gain, standing inside, or heat loss, standing outside. Suggested reading: Where do I need to drain the footing drain when I waterproof a basement from the outside? You need to somehow drain or shed rain water away from the house. See any cracks in the foundation?
Comment: nope ..just being very detailed when I do something. I do it the best I can and since we are looking at a couple of good tens of thousands dollars to spend on a contractor I would rather do my homework and see what I can and what I can't do myself
My feeling is that people are paying big money because they are lazy and ignorants. Digging should not be a problem, you can rent a miniexcavator for around 250$/day with operator included. Two days (one to dig, one to fill back) and the difficult work is done. Insulating properly should be doable by a DIYer. Connecting to sewers ...hmm not really.
Comment: That is my own thread ...I posted that question. I am working on both fronts, inside and outside :-)
Search MoldDog in Toronto. The guy pretends to be able to use the dog to locate the problem and to use the thermal camera to show you where is problems with humidity and water
Comment: A little ambitious, are we? ;)
Comment: If the question is if *these guys could* then I'd say yes. Bunch of other nifty gadgets, know-how and the thermo cam tells them spots that are X temp for mold to grow. I don't think you or I could.
Comment: I might artificially aggravate the proble pouring cold or hot watter from outside in big volumes...then I am going to know for sure where and what.
I already ordered a HD inspection camera (USB one which I plan to attach to a fish tape) ..somehow I will find out what and where !


array of function declaration and assignment problem

Question: I am trying to create an array of pointers to functions, and trying to assign the function address to it. But i am getting errors which i dont know how to proceed with.
My code
void (*Event_Handlers)[3]();  //Line no 10

/* Queue, Drop and Send_back have been defined. for eg */
void Queue()
{
....
}

Event_Handlers[0]=Queue;  // Line 35
Event_Handlers[1]=Drop;   // Line 36
Event_Handlers[2]=Send_Back;   // Line 37

But i am getting the following error
 fsm.c:10: error: declaration of âEvent_Handlersâ as array of functions

 fsm.c:35: warning: data definition has no type or storage class

 fsm.c:35: error: invalid initializer

 fsm.c:36: warning: data definition has no type or storage class

 fsm.c:36: error: invalid initializer

 fsm.c:37: warning: data definition has no type or storage class

 fsm.c:37: error: invalid initializer

Where am in going wrong
Answer: You are very close...
Try:
void (*Event_Handlers[3])();

Comment: thank you Nemo.. But still the warning persists.. wat may be the reason?
Comment: Seriously?  What compiler?  I tried your version (and got the warning) then mine (and it went away).  I just tried it again to make sure...  Try @Mihran's approach; it is clearer anyway.
Comment: My version is gcc. I tried Mihrans approach. Still i am getting that error
Comment: I assume the warning on line 10 is gone?  Are you trying to put these assignments at the top level?  You cannot have code outside of a function in C...  You have to put them into a function (say, main())
Comment: @CHID: Have you tried using proper prototypes? `void Queue(void)` and `void (*Event_Handlers[3])(void)`? Your compiler could be slipping into K&R mode and getting confused. And yeah, Mihran's typedef (an awesome band name BTW) approach will be less confusing in the long run.
Answer: For first time to be sure that you declared array of pointers to function use the following syntax:
typedef void (*func_t)();
func_t EventHandlers[3];

Comment: thankk you Mihran. I tried ur code. But still my compiler complains.. Now i get a new error. "Conflictng types of EventHandlers followed by invalid initialiser". My code contains only the above mentioned lines. I have made sure that ther is no otherp ointer by the name EventHandlers
Comment: What compiler do you use? Are you sure there is no `EventHandlers` variable in other place in your code (try `grep -r 'EventHandlers' ./` through all source files). Try to initialize EventHandlers after declaration (`func_t EventHandlers[3] = {NULL}`).
Comment: Thank you Mihran. The problem was solved. #Nemo's second comment
Answer: the array element type could be function pointer, but can not be function.
void (* Event_Handlers[3])()
will be the right answer


Optimisation of the modulus of a function over an interval

Question: I have a well-behaved complex-valued function $f(x)$ (well-behaved in the sense that it can be represented by a Taylor series). Through the addition of a constant, I would like to be able to minimise the modulus of the function over an interval $(x_{1},x_{2})$ in the sense that I want to calculate:
$\min_{C}\left({\max_{x\in(x_{1},x_{2})}\left|C+f(x)\right|}\right)$
The interval itself is small in the sense that $f(x)$ is slowly varying across the interval, but not necessarily so small that I can simply ditch all quadratically small terms in a Taylor expansion about a point within the interval.
Thus, in the first instance one might consider choosing $C=-f\left(\frac{x_{1}+x_{2}}{2}\right)=C_0$, which, to linear order terms in the Taylor expansion of $f(x)$ about $\frac{x_{1}+x_{2}}{2}$, would be the optimal solution (I believe).
However, I would like to know if there is a better solution if the quadratic (or higher order) terms are significant. My attempt so far has been to work in terms of the Taylor expansion of $f(x)$ about $\frac{x_{1}+x_{2}}{2}$ to quadratic order, and I've managed to get out a solution that's rather clunky in the sense that it depends on the quadrant of the complex plane occupied by the ratio of the first two terms in the Taylor expansion.
I would like to know if there's a more elegant way to solve this, perhaps by considering a perturbation about the optimal solution up to linear order, $C=-f\left(\frac{x_{1}+x_{2}}{2}\right)$. Thanks in advance for any help.
Answer: EDIT: Still uncertain how to analytically obtain a solution for complex-functions
When $f(x)$ is complex-valued
I believe $(x_1,x_2)$ should map to a curve in the complex plane. Determine the circum-circle for this mapping; i.e. the smallest circle that contains the mapping. Then the minimizing $C$ is the negative of the centre of this circle, and $\min_C \max_{x\in(x_{1},x_{2})} |C + f(x)|$ is the radius of the circle. The logic is that $\max _x|f(x)|$ is the radius of the circumcircle over $f(x)$ and centred at origin. So to minimize this, shift the mapping (by $C$) to be around the origin.
When $f(x)$ is real-valued
$-C$ marks the new '$0$' value for the expression $|C + f(x)|$. The maximum of this expression then is the largest distance from this zero. To minimize this distance, then put the new zero baseline halfway between the min and max of the function,
$$
C = -\frac{f^{\max} + f^{\min}}{2} \rightarrow \min_C \max_{x\in(x_{1},x_{2})} |C + f(x)| = \frac{f^{\max} - f^{\min}}{2} \\
f^{\min} \equiv \min_{x\in(x_{1},x_{2})} f(x), \; f^{\max} \equiv \max_{x\in(x_{1},x_{2})} f(x)
$$
The following is the algebraic derivation,
$$
C + f^{\min} \leq C + f(x) \leq C + f^{\max} \\
|C + f(x)| \leq \max \left( |C + f^{\min}|, |C + f^{\max}|\right) \\
\implies \max_{x\in(x_{1},x_{2})} |C + f(x)| = \max \left( |C + f^{\min}|, |C + f^{\max}|\right) \\
$$
$$
C \geq - f^{\min} \rightarrow \max_{x\in(x_{1},x_{2})} |C + f(x)| = |C + f^{\max}| \geq f^{\max} - f^{\min}\\
C \leq - f^{\max} \rightarrow \max_{x\in(x_{1},x_{2})} |C + f(x)| = |C + f^{\min}| \geq f^{\max} - f^{\min} \\
-f^{\max}\leq C \leq - f^{\min} \rightarrow \max_{x\in(x_{1},x_{2})} |C + f(x)| = \max \left( - C - f^{\min}, C + f^{\max}\right) \leq f^{\max} - f^{\min} \\
\therefore \min_C \max_{x\in(x_{1},x_{2})} |C + f(x)| \implies -f^{\max}\leq C \leq - f^{\min}\\
$$
$$
a(C) \equiv - C - f^{\min},\; b(C) \equiv C + f^{\max} \\
\rightarrow \min_C \max_{x\in(x_{1},x_{2})} |C + f(x)| = \min_C \max(a(C),b(C)) \\
\text{where} \; a + b = f^{\max} - f^{\min}, \; 0 \leq a,b \leq f^{\max} - f^{\min} \\
\therefore C = -\frac{f^{\max} + f^{\min}}{2} \rightarrow \min_C \max_{x\in(x_{1},x_{2})} |C + f(x)| = \frac{f^{\max} - f^{\min}}{2}
$$
Comment: Thanks, Tony. I like your geometrical interpretation. A very small bandwidth would then map out a straight line in the complex f(x) plane, which would be a diameter of the circumcircle.
Comment: Thanks for your answer, Tony. My function, f(x), is complex-valued. Are your definitions for fmin and fmax meant to contain the modulus of f(x)? If so, I'm not quite sure how the first line of the derivation works.
Comment: Oh, I see, I was thinking real-value function . I believe the same logic of midway between min and Max should work, but I'll have to think about how the derivation should be changed


Determinant of the "bordered" Hessian of a composition

Question: Write $H_{f}$ for the Hessian of a real function $f:\mathbb{R}^n\mapsto \mathbb{R}$, and define the bordered Hessian as
$$ H_{f} =
\left(\begin{matrix}0 & \nabla f' \\
\nabla f & H  \end{matrix}\right),\quad

H := \left[ \frac{\partial f}{\partial x_ix_j}\right]_{i,j} \quad i,j=\overline{1,n}$$
and consider the composition $g = h \circ f$. What is the best way to show the relationship of $H_g$ and $H_f$?
Comment: I didn't change the title, but why does it contain the word "determinant"?
Comment: Oh, some authors refer to the determinant of the $H_f$ matrix as the bordered Hessian. I find that a lot. It's a good point though.
Answer: We have $\frac{\partial g}{\partial x_i}=h'(f)\cdot\frac{\partial f}{\partial x_i}$ so $\nabla g=h'(f)\nabla f$ and
$$\frac{\partial^2g}{\partial x_i\partial x_j}=h''(f)\cdot \frac{\partial f}{\partial x_i}\cdot \frac{\partial f}{\partial x_j}+h'(f)\frac{\partial ^2f}{\partial x_i\partial x_j},$$
hence
$$H_g=h'(f)H_f+h''(f)\pmatrix{0\\\ \nabla F}\pmatrix{0\\\ \nabla F}^T.$$
Comment: The two matrices are not conformal. $H_f$ is $n\times n$, whereas
$$ \left(\begin{matrix} 0 \\ \nabla f \end{matrix}\right)\left(\begin{matrix} 0 \\ \nabla f \end{matrix}\right)'
$$
is $n+1\times n+1$.
Comment: In the definition $H_f$ seems to be $(n+1)\times (n+1)$ since $H$ is $n\times n$.
Comment: Right, sorry, my notation is confusing even to me. Thank you!


How to add traces for AppDynamics

Question: I have a Python agent for AppDynamics and I would like to have a feature to send specific logs that I could read afterwards directly in AppDynamics.
That is, just some logs sent to AppDynamics that I would use to troubleshoot any issue.
How could I do that, and where would I read them within AppDynamics?
Answer: The Python Agent does not have this specific ability, but there are a few options which may aid in your use case.

Use Log Analytics - requires an Analytics Agent (or a Machine Agent with the Analytics extension). Set config / log line format to parse log data into a usable format in AppD. Docs: https://docs.appdynamics.com/appd/22.x/latest/en/analytics
Use Custom Events - through hitting the Analytics Events API to store records in a custom schema. Could be used to store log lines. Docs: https://docs.appdynamics.com/appd/22.x/latest/en/analytics/adql-reference/adql-data/analytics-custom-events-data
Use Custom Extensions - custom scripting for the Machine Agent allows for arbitrary reporting of metrics under a host as "Custom Metrics". Not for logs specifically, meant for additional metrics. Docs: https://docs.appdynamics.com/appd/22.x/latest/en/infrastructure-visibility/machine-agent/extensions-and-custom-metrics

It is also worth noting that by default, stack trace / call stack information can be found within sampled snapshots - see https://docs.appdynamics.com/appd/22.x/latest/en/application-monitoring/business-transactions/troubleshoot-business-transaction-performance-with-transaction-snapshots

How to add traces for AppDynamics


Difficulty proving $x_n$ satisfaction in the inequality

Question: I am trying to prove that $$x_n = \int_{0}^{1}\left(\frac {n}{x}\right)^n \,dx$$ satisfies the inequalities
$$\frac {n}{n+1}\left(\frac {\pi^2}{6}-\sum_{k=1}^{n}\frac {1}{k^2}\right)<x_n<\frac {n}{n+1}\left(\frac {\pi^2}{6}-\sum_{k=1}^{n-1}\frac {1}{k^2}\right)$$
$$\frac {n^2}{n+1}\left(\frac {\pi^2}{6}-\sum_{k=1}^{n}\frac {1}{k^2}\right)<x_n<\frac {n^2}{n+1}\left(\frac {\pi^2}{6}-\sum_{k=1}^{n-1}\frac {1}{k^2}\right)$$

I tried to make the substitution $\frac {n}{x} =t$ but I couldn't get the desired result.
Comment: Let $t=\dfrac1x$ and then rewrite the new integral on $(1,\infty)$ as an infinite series of smaller integrals, each on an interval of the form $(k,k+1)$. I assume you are already aware that $\dfrac{\pi^2}6=\zeta(2)=\displaystyle\sum_{j=1}^\infty\frac1{j^2}$
Answer: $$x_n = n \int_{n}^{\infty} \frac {t^n}{t^2}\,dt = n \sum_{k=n}^{\infty}\int_{k}^{k+1} \frac {t^n}{t^2} \,dt = n \sum_{k=n}^{\infty}\int_{k}^{k+1} \frac {(t-k)^n}{t^2} \,dy =  n \sum_{k=n}^{\infty} \int_{0}^{1} \frac {y^n}{(k+y)^2}\,dy = n \int_{0}^{1} y^n \left(\sum_{k=n}^{\infty} \frac {1}{(k+y)^2}\right) \,dy $$
Since $\frac {1}{(k+1)^2} < \frac {1}{(k+y)^2} < \frac {1}{k^2}$, for positive integers $k$, and $y \in (0,1)$, it follows that
$$n \int_{0}^{1} y^n \left(\sum_{k=n}^{\infty} \frac {1}{(k+1)^2}\right) \,dy < x_n < n \int_{0}^{1} y^n \left(\sum_{k=n}^{\infty} \frac {1}{k^2}\right) \,dy$$
Thus,
$$\frac {n}{n+1}\left(\frac {\pi^2}{6}-\sum_{k=1}^{n}\frac {1}{k^2}\right)<x_n<\frac {n}{n+1}\left(\frac {\pi^2}{6}-\sum_{k=1}^{n-1}\frac {1}{k^2}\right)$$
Which implies that $\lim\limits_{n\to \infty} x_n = 0$.
The second limit equals $1$. We have, based on the preceding inequalities, that
$$\frac {n^2}{n+1}\left(\frac {\pi^2}{6}-\sum_{k=1}^{n}\frac {1}{k^2}\right)<x_n<\frac {n^2}{n+1}\left(\frac {\pi^2}{6}-\sum_{k=1}^{n-1}\frac {1}{k^2}\right)$$
and the result follows since $\displaystyle\lim\limits_{n \to \infty} n\left(\frac {\pi^2}{6}-\sum_{k=1}^{n} \frac {1}{k^2}\right) = 1$
Comment: Wow! thanks for the comprehensive answer!


Convert a Pandas dataframe with a date column to a Vaex dataframe

Question: I am trying to do the following

load some data with string columns

measurement_df = pd.read_csv('data/tag_measurements/all_measurements.csv')
measurement_df.head(3)
measurement_df
>> prints
.  timestamp               tag_1      tag_2        tag_3
0   2018-01-01 11:09:00 0.729193    -0.236627   -1.968651
1   2018-01-02 05:56:00 -2.812988   0.394632    -1.151147
2   2018-01-03 00:37:00 0.363185    -0.089076   -1.509133

at this point the timestamp column is of type str:
type(measurement_df.iloc[0]['timestamp'])
>> prints
str

convert it to Vaex

vdf = vx.from_pandas(measurement_df)
vdf.head(3)
>> prints
#           tag_1          tag_2                  tag_3           index
0   0.7291933972260769  -0.2366268009370677  -1.9686509728501898    0
1   -2.8129876800434737 0.3946317890604529   -1.1511473058592252    1
2   0.3631852302577519  -0.08907562484360453 -1.5091330993605443    2

somehow I lose the timestamp column. Any ideas what could be going wrong?
Comment: what is the dtype of  'timestamp'? (did you make sure it's 'datetime64'?)
Comment: It is ```str``` (see edit to the post). I converted it to ```np.datetime64```: ```measurement_df['timestamp'] = [np.datetime64(i) for i in measurement_df['timestamp'].values]```. after the conversion it still does not work, i.e. the timestamp column disappears.
Answer: If you would like to preserve the date/time format, especially while reading CSVs, i suggest you do :
df = pd.read_csv('myfile.csv', parse_dates=['datetime_col_1', 'datetime_col_2'])
you can also do:
df = vaex.read_csv('myfile.csv', parse_dates=['datetime_col_1', 'datetime_col_2'])
it is the same since it is using the pandas method in the background.
Comment: I just check, and I was using an old version of vaex. Update to 3.0.0 (`conda install -c conda-forge vaex=3.0.0 `) and your proposed solution works! Thank you @Joco.
Comment: looking at [Vaex APIs](https://vaex.readthedocs.io/en/latest/api.html), I think the closest thing they have is `from_csv`. I tried calling `vx.from_csv('my_files.csv', parse_dates=['timestamp'])`, it leads to the following error and the `timestamp` is dropped: `could not convert column timestamp, error: AssertionError("dtype not supported: dtype('",), will try to convert it to string`
Comment: FYI for anyone reading this one.. vaex is currently at version v4.5.x. Dunno why but sometimes pip/conda do not install the latest version


Karate : Select 'n' number of random values from an Array

Question: To get 'n' number of random values from the below array whenever i execute the test script. How i can i achieve this into Karate in a feature file.
[
"2972029540",
"2972033041",
"2972030914",
"2972028446",
"2972030851",
"2972026534",
"2972029484"
]
Answer: Here you go:
<code>* def random = function(max){ return Math.floor(Math.random() * max) + 1 }
* def data = [ "2972029540", "2972033041", "2972030914", "2972028446", "2972030851", "2972026534", "2972029484" ]
* def count = random(data.length)
* print 'random count is', count
* def temp = data.slice(0, count)
* print temp
</code>
Read this for more info: https://stackoverflow.com/a/53975071/143475


Default variable that is passed to views

Question: Very simple CakePHP question.
I know you can pass data with $this->set() in controller, and I know data exists in $this->request->data.
Does CakePHP pass the request->data to a named variable that can be called in the view automatically? Or, do I always have to do $this->set('variable', 'data') ?
Answer: Request data is accessible automatically in the view without the need to set it as a variable:
$this->request->data(...

Fore example (accessing POST data):
$this->request->data['MyModel']['title'];

You can just debug($this->request->data()); in your View to see what's available to you.
Comment: Is accessing the request data directly considered good practice?
Comment: I don't see why it wouldn't be.  Someone feel free to correct me if I'm wrong.  Seems better practice than adding variables for no other reason that adding variables.


Why am i getting NullPointerException when i try to save image?

Question: I am trying to save image in my app. But i am getting null pointer exception when i try to persist image object. Here is my Image class:
 @PersistenceCapable
 public class ImageObject {

     @PrimaryKey
     @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
     private Key key;

     @Persistent
     private String title;

     @Persistent
     private Blob image;

     public ImageObject(){}

 //     all getters and setters
 }

Following is my servlet code which is giving exception:
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
    List<BlobKey> blobKeyList = blobs.get("upload_img_form_input");
    BlobKey blobKey = blobKeyList.get(0);
    String keyString = req.getParameter("upload_img_form_key");

    Key key = KeyFactory.createKey(ImageObject.class.getSimpleName(), keyString);
    Image img = ImagesServiceFactory.makeImageFromBlob(blobKey);
    ImageObject imgObj = new ImageObject();
    imgObj.setKey(key);
    imgObj.setTitle(keyString);
    imgObj.setImage(img.getImageData());
// i am getting exception at this line where i am trying to persist
    pm.makePersistent(imgObj);

Can anybody please tell me why am i getting this NullPointerException? Thanks in advance.
Comment: Well `imgObj` isn't null and you've said below that `pm` isn't null, so you're best bet is to step through `pm.makePersistent()` and see which field in `imgObj` is causing the problem.  Adding the relevant parts of the stack trace might be useful here too.
Comment: img.getImageData() is null. This is the blobkey i am getting . why is img.getImageData() null? Am i not fetcing img in right way?
Answer: the only way you could have a Npe on this line :
pm.makePersistent(imgObj);

is when pm is null
you should check that part :
PersistenceManager pm = PMF.get().getPersistenceManager();

is your persistence.xml in classpath ?
Comment: i printed pm and this is shown "org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManager@1367f48c". which means atleast its not null
Comment: i am persisting a lot of object in other servlets using same line of code. and its working fine. I think its something else.
Comment: could you add your stacktrace  ? :D
Comment: this is what i am getting in my console: Exception error: java.lang.NullPointerException   nothing else
Answer: In my experience, img.getImageData() returns null when you get the image from ImagesServiceFactory.makeImageFromBlob without applying any transformation to it. If you want to get the bytes from the blob without doing any image transformation, you don't actually need the image service and you will just have to fetch the data from the blob store. I tried this code from a blog post and it works well.
public static byte[] readBlobFully(BlobKey blobKey) {

    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);

    if (blobInfo == null)
        return null;

    if (blobInfo.getSize() > Integer.MAX_VALUE)
        throw new RuntimeException("This method can only process blobs up to " + Integer.MAX_VALUE + " bytes");

    int blobSize = (int) blobInfo.getSize();
    int chunks = (int) Math.ceil(((double) blobSize / BlobstoreService.MAX_BLOB_FETCH_SIZE));
    int totalBytesRead = 0;
    int startPointer = 0;
    int endPointer;
    byte[] blobBytes = new byte[blobSize];

    for (int i = 0; i < chunks; i++) {

        endPointer = Math.min(blobSize - 1, startPointer + BlobstoreService.MAX_BLOB_FETCH_SIZE - 1);

        byte[] bytes = blobstoreService.fetchData(blobKey, startPointer, endPointer);

        for (int j = 0; j < bytes.length; j++)
            blobBytes[j + totalBytesRead] = bytes[j];

        startPointer = endPointer + 1;
        totalBytesRead += bytes.length;
    }

    return blobBytes;
}


Is it safe to connect two extension cords to reach 75 feet to a generator?

Question: For my generator? It's a duromax xp4850eh with one of those 240v L14-30 outlets. The inlet is about 75 feet away from where I want the generator to sit outside. Because of voltage drop concerns, I thought maybe I could connect a 8/4 extension cord to the generator first, then connect my 25 feet 10/4 cord to the end of that. I really don't want to deal with a full on 8 gauge 75 foot cord.
Answer: Yes, you can run extension cords in series.  The wires have to be sufficient size for the ampacity from end to end.  The cords and in particular the junction between the cords would have to be rated for the environment, they'd have to be weather proof if they are outdoors.
The voltage drop would be additive, you'd calculate voltage drop from the source voltage on the first cord, then calculate the drop of that adjusted voltage on the second cord.
There is no issue with a 10-4 cord at 30 amps for 75' - that would be less than 2% at 240V and less than 4% at 120V, which should be no problem at all.


Steam Trading Error - "This trading session has expired."

Question: How can I fix this issue? Sometimes I find that when I try to trade with anyone, before the screen loads, this error message pops up.
I'm not using Steam Beta.
Comment: This is similar to uploading screanshots on Steam. It sometimes simply don't work.
Answer: This means that - for whatever reason - the built-in browser handling these pages somehow lost the data identifying the current session (which is essentially just some semi-random value to identify the computers allowed to actually see the data and modify it; i.e. those that are allowed to complete the trade).
There are several reasons why this could happen:

The whole trade session might have been open simply too long. For example, you might have opened the trade and then didn't try to complete it "in time". I don't know how long that time is, but I'd assume at least a few minutes (unlikely more than an hour).
Some server handling the request(s) dropped that Information. This could be a local proxy or just some server at Valve acting up.
Your Internet connection dropped for a few seconds while you tried to perform the trade. In this case you might have been assigned a new IP by your ISP, which most likely would invalidate the current session for security purposes.
If you're using some kind of firewall or filter software modifying the content of web pages (to "protect" you or remove ads), this might be the reason as well (filtering this legitimate data intentionally or by accident). Try to add the Steam client to its exception list.
Answer: I believe that what is occurring is similar to an expired browser session. The server is taking too long to respond and Steam automatically times it out. Just try again.


Installing Quojs

Question: I'm trying to install Quojs, a gestures library but I got the following error :
TypeError: $$(...).tap is not a function

Any idea what I should do to get it work ?
<!DOCTYPE html>

    <title>The Touc Project</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

TOUC !

Comment: Seem to be specific to 3.X.X version, the 2.3.6 quo.js works fine
Answer: Check the source url of Quojs and try  this instead
$$('h1').tap(function(){
    console.log('tap');
});

Comment: Still have the same error, you can try to see why there : https://jsfiddle.net/9qn0jegr/1/

Installing Quojs


In F#, what is the correct way to store temporary results?

Question: I have to write an Excel addin in F#, it does some pretty heavy computations in order to calibrate some curves as a first step in some User Defined Functions.
As a second step, I need re-use the representation of the universe (the curves calibrated in the first step) as an argument for other functions.
When I was doing this in a procedural language with states, I would just return a string handle on the universe which would be an object that I would store in memory. If I am doing this in F#, am I breaking the functional language paradigm ?
Is there an elegant way to do a similar thing without having to do the recalibration in the first step ? Here I am using Excel, but this is a more general question.
Answer: Do you mean that if you have user-defined function A and UDF B both of them require calling another function to calibrate?  If that's the case, then it sounds like you should memoize the calibration function and have A and B use the memoized function.
As a side note, you should consider disregarding typical academic implementations of memoization and consider one with limits on the upper bound of inputs.
As a side, side note - Excel is one of the most widely used function programming paradigms.
Comment: In my C# implementation, I have a set of functions returning strings like "CURVE1.1" "SPLINE2.1" and then I would have a way to organise them in a representation of the universe via another function which would for example return a handle "UNIVERSE1.2". Then I would pass around only this Universe handle around in the second part. I am trying to understand what is the correct way to do something similar in a functional language.


Proof: $ \lfloor \sqrt{ \lfloor x\rfloor } \rfloor = \lfloor\sqrt{x}\rfloor $.

Question: I need some help with the following proof:
$ \lfloor \sqrt{ \lfloor x\rfloor } \rfloor = \lfloor\sqrt{x}\rfloor $.
I got:
(1) $[ \sqrt{x} ] \le \sqrt{x} < [\sqrt{x}] + 1 $ (by definition?).
(2) $[ \sqrt{x} ]^2 \le x < ([\sqrt{x}] + 1)^2 $.
(3) $[ \sqrt{x} ]^2 \le [x] \le x < ([\sqrt{x}] + 1)^2$
??
Answer: Note that every nonnegative number $x$ is between the squares of two consecutive nonnegative integers. Say $n^2 \leq x < (n+1)^2$. Then $n \leq \sqrt{x} < n + 1$, so $\lfloor \sqrt{x} \rfloor = n$ in this situation.
So you just have to make sure the left hand side is also $n$. Since $n^2$ is an integer, one has
$n^2 \leq \lfloor x \rfloor \leq x$, so $n^2 \leq \lfloor x \rfloor < (n+1)^2$. So exactly as above one has $\lfloor \sqrt{\lfloor x \rfloor} \rfloor = n$ as well.
Answer: Hint: for any positive integer $n$, $\sqrt{n+1}-\sqrt n=\frac 1{\sqrt{n+1}+\sqrt n}\lt 1$, hence
$$\sqrt{x}\leqslant \sqrt{[x]+1}\lt 1+\sqrt{[x]},$$
hence $[\sqrt x]\leqslant \sqrt{[x]}$.
Since $[\sqrt x]$ is an integer, we actually have
$$[\sqrt x]\leqslant [\sqrt{[x]}].$$
The opposite inequality is a consequence of increasingness of $t\mapsto \sqrt t$ and $[s]\leqslant s$ for any real number $s$.
Comment: Is it always true that: $\quad$$\sqrt{x}<1+\sqrt{\lfloor{x}\rfloor}\Rightarrow\lfloor{\sqrt{x}} \rfloor\le\sqrt{\lfloor{x}\rfloor}$
Answer: First, you need that $x \geq 0$. Write $x=a+ \alpha$ where $\left\lfloor \sqrt x \right \rfloor=a$ and $\alpha <1$. Take $n^2 \leq a < (n+1)^{2}$ . Now, you need to prove that $n= \left \lfloor \sqrt a \right \rfloor = \left \lfloor \sqrt {a+ \alpha} \right \rfloor$. $\left \lfloor \sqrt {a+ \alpha} \right \rfloor \leq \left \lfloor \sqrt {(n+1)^2 -1 + \alpha} \right \rfloor <\left \lfloor \sqrt {(n+1)^2} \right \rfloor =n+1$. This implies $\left \lfloor \sqrt {a+ \alpha} \right \rfloor=n $ what you needed


Device to "freshen" an unventilated bathroom?

Question: Is there a device that ozone-ises or ionises the air to reduce the odour that builds up in an unventilated bathroom?
I'm not talking about reducing smells created by - eh - "toilet deposits", more the smell that builds up because there is exposed water in an unventilated room.
Update
This is indeed an infrequently used bathroom, in my inlaws basement. I need to do some wiring work down there and thought if there was a device I could wire in to help I'd do so.
I thought I'd seen things in bathrooms in Pubs & Restraunts that does this, possibly not.
Comment: I'm going to guess this is in a second/third/guest bathroom, since it sounds like the water must be sitting for quite some time undisturbed.  You might want to get in the habit of occasionally flushing the toilet and running water down the drains (sink,tub,etc).  If a drain is left too long unused the water in the trap can evaporate, allowing sewer gases to escape into the room.
Comment: my favorite device for this is a flame powered wax vaporizer... aka a candle.
Comment: I wouldn't be surprised if the commercial air fresheners are battery operated.  You can get something that looks much better and works just fine for home use (e.g. reed diffusers).
Answer: Try putting a small dehumidifier in the room, which will cut down on musty smells.
Also if this bathroom is used infrequently, be sure the flush the toilet periodically, and run the faucet.  Stagnant water in the toilet will stink, and the drain trap will dry out, leading to sewer gas smells.  This will be especially true with a dehumidifier, which will dry things out.


How do you view enemy unit attack ranges?

Question: In most, if not all, SRPG or turn-based strategy games you can put your cursor over an enemy unit, and press a button to view their attack range.  I know you can view their movement range, which helps for direct attack units, but I have to manually calculate ranged units.
So, how do you view an enemy unit's attack range?  Assuming it's possible, but I can't imagine that probably the most comprehensive SRPG of all time doesn't have that feature.
Answer: You can't.  Because here's a fun fact: Ranged attacks can hit WELL beyond their listed ranges.  It's based on the relative height differences between the unit and their target.  The higher the unit is, the farther they can reach.  Archers on walls (because they have Warp Rings or Winged Boots), can sometimes target the entire map.  Obstacles will also play a part for Gunners; they need a direct line to their target, whereas Archers will just shoot over them.
The only limitation for ranged attacks are spells; those, the range isn't extendable, but is still subject to obstacles.
Melee is the only one you can figure out; it's the unit's movement range, and then add one for all melee weapons, and add an extra one for whips and spears.


Overriding an UpdateView's get_form_kwargs() method

Question: I'd like to override an UpdateView's get_form_kwargs() method, and have something similar to the following:
class GroupRatingView(UpdateView):
    model = Group
    fields = ['rating']

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super(GroupRatingView, self).get_form_kwargs(*args, **kwargs)
        import ipdb; ipdb.set_trace()

However, if I try this out, I get the following error:
File "/venv/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  181.         form = self.get_form()

File "/venv/lib/python2.7/site-packages/django/views/generic/edit.py" in get_form
  45.         return form_class(**self.get_form_kwargs())

Exception Type: TypeError at /groups/5/rate
Exception Value: ModelFormMetaclass object argument after ** must be a mapping, not NoneType

It seems that self.get_form_kwargs() is returning None, whereas I would expect to drop into the debugger. Why am I getting an error instead of hitting the debugger trace?
Answer: You forgot to return the kwargs at the end of the method; this causes the method to return None, which is not a mapping and causes the error.
Add a return statement to your method:
class GroupRatingView(UpdateView):
    ...

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super(GroupRatingView, self).get_form_kwargs(*args, **kwargs)
        ...
        return kwargs


How can I tell dart that it should use the latest version of the packages when using "dart pub global activate"?

Question: I'm trying to install the package spec_cli. For this, I'm using the dart pub global activate spec_cli command.
However, there is an issue in the package spec_cli in version 0.1.2+2 or lower. To fix this, the author released 0.1.3. Unfortunately, dart pub global actiavte spec_cli still uses 0.1.2+2:
dart pub global activate spec_cli
+ _fe_analyzer_shared 220.127.116.11s)
+ analyzer 5.1.0
+ ansi_styles 0.3.2+1
+ args 2.3.1
+ async 2.9.0
+ boolean_selector 2.1.0
+ charcode 1.3.1
+ cli_util 0.3.5
+ collection 1.16.0
+ conventional_commit 0.4.3+1 (0.5.0 available)
+ convert 3.0.2
+ coverage 1.6.1
+ crypto 3.0.2
+ dart_test_adapter 0.2.0
+ duration 3.0.12
+ file 6.1.4
+ freezed_annotation 1.1.0 (2.1.0 available)
+ frontend_server_client 3.0.0
+ glob 2.1.0
+ graphs 2.1.0
+ http 0.13.5
+ http_multi_server 3.2.1
+ http_parser 4.0.1
+ io 1.0.3
+ js 0.6.4
+ json_annotation 4.7.0
+ logging 1.0.2
+ matcher 0.12.12
+ melos 1.5.2 (2.7.1 available)
+ meta 1.8.0
+ mime 1.0.2
+ mustache_template 2.0.0
+ node_preamble 2.0.1
+ package_config 2.1.0
+ path 1.8.2
+ platform 3.1.0
+ pool 1.5.1
+ pub_semver 2.1.1
+ pubspec 2.3.0
+ quiver 3.1.0
+ riverpod 2.0.2
+ shelf 1.4.0
+ shelf_packages_handler 3.0.1
+ shelf_static 1.1.1
+ shelf_web_socket 1.0.2
+ source_map_stack_trace 2.1.0
+ source_maps 0.10.10
+ source_span 1.9.1
+ spec_cli 0.1.2+2 (0.1.3 available)
+ stack_trace 1.10.0
+ state_notifier 0.7.2+1
+ stream_channel 2.1.1
+ string_scanner 1.1.1
+ term_glyph 1.2.1
+ test 1.21.6
+ test_api 0.4.14
+ test_core 0.4.18
+ typed_data 1.3.1
+ uri 1.0.0
+ vm_service 9.4.0
+ watcher 1.0.1
+ web_socket_channel 2.2.0
+ webkit_inspection_protocol 1.2.0
+ yaml 3.1.1

You can see that the dart tool knows that there is a new version of spec_cli ("spec_cli 0.1.2+2 (0.1.3 available)").
But how can I use this update?
Comment: Makes sense, @RandalSchwartz. I'm going to file an issue at GitHub
Comment: It has been fixed :) Indeed, it was an issue with the dependency of spec_cli. If you want, you can write an answer and I'm going to accept it
Answer: [moved from a comment]
It looks like spec_cli depends on some other packages that also need updating to talk to freezed_annotation 2 instead of 1. You should file an issue with spec_cli with your output from trying to activate it.


knockout: data binding to individual text box in a foreach binding

Question: Here's the relevant code:

 0">
    <input data-bind='value: $parent.newCommentText' />
    Add comment

ViewModel:
self.newCommentText = ko.observable()
self.addComment = function(chat) {
            var newComment = { CourseItemDescription: self.newCommentText(), };
            chat.CommentList.push(newComment);
            self.newCommentText("");
            $.ajax({
                url: "@Url.Action("AddComment")",
                data: ko.toJSON(newComment),
                type: "post",
                contentType: "application/json"
            });
        };

The problem is that this will put whatever I type in one text box in all the other text boxes. How can I make it so that it only binds to the textbox that the user is typing in and have that data available to the addComment function?
Answer: If you want each chat to be able to have their own comment field to add, then you would want to add your newCommentText field to the chat object rather than the parent.  Then you can read it and clear it out off of the chat object that is passed to addComment.
Answer: I needed to put the newCommentText inside the chats array.
so the code would become
self.addComment = function(chat) {
            var newComment = { CourseItemDescription: chat.newCommentText(), };
            chat.CommentList.push(newComment);
            chat.newCommentText("");
           ...
        };


Meta Tag in HTML Mail is partly shown

Question: We have vom .txt dokuments with our email content as HTML code.
Problem is, that we had to add some blank lines so the meta tag is not shown in the mails.
Until now, we had 5 blank lines, but with the Greek mails we need around 20 blank lines for this.
Is there a less ugly solution for this problem?
The affected meta tag:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

The Code in the Document:
Subject:

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0," />

//followed by body

Example in Mail:
-equiv="Content-Type" content="text/html; charset=utf-8">

The Mail is displayed as coded after this line.
Can someone please help?
Thank you!
Comment: This is not how it is supposed to work.  My guess is that something else entirely is wrong, and that the empty lines somehow mask the real problem.  Perhaps you could show the full source of a representative email message?  (This doesn't really seem like a programming question, though.)
Comment: I added the whole header.
Comment: You have a single `Subject:` header and no MIME headers at all?  Then it should be displayed as just text, not HTML.  Which client are you seeing this under?
Comment: you mean mail client?
Web.de and gmail
I didn't write the code für the mails, my work was just changing the translations, so I don't really know, what they thought, when they wrote this...
Answer: Your message should not display as HTML at all.  We can only surmise that adding empty lines somehow exposes a bug in some webmail clients.  You should not be relying on this; you should send valid messages.  Here is a simple minimal example of a valid HTML email message.
From: you <email@example.com>
To: recipient <email@example.com>
Subject: whatever you like
Mime-Version: 1.0
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0," />

//followed by body

I don't think the http-equiv is even necessary any longer, given that the MIME content declaration already sets things up for properly displaying it, but YMMV.
The Content-Transfer-Encoding: 8bit means lines have to be shorter than some 1,000 characters.  If that's a problem, maybe employ a different content-transfer-encoding (quoted-printable, perhaps; but then you have to program that, too).
Comment: From and To is set at another point.
I added the other two parts. Sadly, this destroyed the whole email.
I think I have to look at the notification system.

Meta Tag in HTML Mail is partly shown


Cannot change brightness of my laptop

Question: My laptop is a DELL 3521 with dual graphic cards, which usually cause some problems, and I have switched off the AMD Radeon card.
Now, when I want to turn the brightness down by dragging the brightness bar in the "Brightness and lock settings" and I close the window, nothing changes, and when I open "Brightness and Lock Settings" again, the brightness bar turn back to its previous state!
So, is it something is the system or I did some kind of mistake?
Answer: Try it once.. It has solved all problems about brightness! Including mine!!

Open terminal ( Ctrl+Alt+T ) and type:
sudo gedit /etc/default/grub

You will find this line in the new opened window: GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
Change it to:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=vendor"

Save and close the window and type this in the terminal:
sudo update-grub

Restart your system..

Cannot change brightness of my laptop


Is there a Powerpoint (PPT) to text/html converter?

Question: Is there a ppt to text/html converter for Ubuntu/*nix?
Answer: Just found a python based command line converter called unoconv (install from Software Center or with apt-get)
 which will allow you to convert from and to anything openoffice can deal with including ppt, txt and html plus as it is cli based so you can batch process nicely :)

Homepage of unoconv
Answer: I'm pretty sure that OpenOffice.org/LibreOffice allows you to export presentations in html or plain text, doesn't it?
Answer: Try catppt from the catdoc  package.


Listview remove particular file name

Question: I'm stuck on this part of my project
I have a listview filled up with files from a specific folder, it get all files from a folder but I need to make a filter only for
"zw1(random numbers and letters)".txt, what am I doing wrong?
here's the code
   public void DataFromFolders1(string fileName = "*")
    {

        string zw1 = "zw1";
        LV1.Items.Remove($"{zw1}*.txt");

        LV1.Items.Clear();

        //zet files van een folder in de listbox als de path correct is
        //de paths kan je boven aan vinden boven InitializeComponent();

        if (dinfo.Exists)
        {
            //FileInfo[] Files = dinfo.GetFiles("*.txt");
            FileInfo[] Files = dinfo.GetFiles($"{fileName}*.txt");

            foreach (FileInfo file in Files)

            {
                LV1.Items.Add(file.Name);
            }
        }
        else
        {
            MessageBox.Show("Pad van niet gedaan folder niet gevonden!");
        }
    }

I have this method in a timer
also the parameter {fileName} is from a date picker ignore that.
Thanks in advance (;
Comment: You need to use Regex here. `Items.Remove` will remove exact match
Answer: Regex regex = new Regex(@"^zw1\.txt$"); //This regex looks for the file name,
   foreach (var item in LV1) //Check every item
      if (regex.Match(item).Success) //If item matches the regex
         LV1.Remove(item); // remove item

Implimentation.
public partial class MainWindow : Window, INotifyPropertyChanged
{
  private List<string> aListOfItems;

  public event PropertyChangedEventHandler PropertyChanged;

  public List<string> AListOfItems
  {
     get { return aListOfItems; }
     set { aListOfItems = value; OnPropertyChanged("AListOfItems"); }
  }
  public MainWindow()
  {
     InitializeComponent();
     DataContext = this;
     AListOfItems = new List<string> { "item1", "item2", "item3", "zw1.txt","hey"};
     ThisIsTheRemoveCode();
  }

  protected void OnPropertyChanged(string name)
  {
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
  }

  private void ThisIsTheRemoveCode()
  {
     Regex regex = new Regex(@"^zw1\.txt$");
     for (int i = 0; i < AListOfItems.Count; i++)
        if (regex.Match(AListOfItems[i]).Success)
           AListOfItems.Remove(AListOfItems[i]);
  }
}

Comment: i tried the code and var item in LV1 has an error.

Severity Code Description Project File Line Suppression State
Error CS1579 foreach statement cannot operate on variables of type 'ListView' because 'ListView' does not contain a public instance definition for 'GetEnumerator
Comment: I have updated my code, this should do as youve asked.

Listview remove particular file name


Retrieving specific elements from XML string using java

Question: Below is my code. I am able to parse xml, I am getting all the values if it in xml - For eg:- Part No i am getting all the values since it is in xml. While i am accessing MODEL, application terminates. How to check whether model tag is there or not and i want to check whether if tag is there value is empty or not.
PartNo[i].setText(el.getElementsByTagName("PART_NO").item(0).getTextContent());

if(el.getNodeName().contains("MODEL"))
{
    Model[i].setText(el.getElementsByTagName("MODEL").item(0).getTextContent());
}

The XML document looks like this:
<root>
  <DataSet>
    <PartNo>aaa</PartNo>
    <Model>bbbb</Model>
  </DataSet>
  <DataSet>
    <PartNo>aaa</PartNo>
  </DataSet>
</root>

Answer: Your call el.getNodeName().contains("MODEL")) is checking whether the String node name of el contains "MODEL", which is obviously wrong.
Reading between the lines, I think you want to check is there is a corresponding Model element for each PartNo element, which can be done like this with a DOM parser:
NodeList partNoElements = document.getElementsByTagName("PartNo");
for (int i = 0; i < partNoElements.getLength(); i++)
{
  Element partNoElement = partNoElements.item(i);

  PartNo[i].setText(partNoElement.getTextContent());

  Element modelElement = (Element)partNoElement.getNextSibling();
  if (modelElement != null && modelElement.getNodeName().equals("Model"))
  {
    Model[i].setText(modelElement.getTextContent());
  }
}

NOTE: this relies on the order of the elements always being as you've listed, which should be enforced by a schema if you're going to use this code.
Comment: Hi nick. Your code not working man. It is going into Dataset and printing all the values, but when i am getting nextsibling individually it is not working. and the getnodename().equals("Model") also not working.
Comment: Please someone answer quickly, i wanna finish the project.
Comment: The code I've listed isn't using the `DataSet` element, it's using the `PartNo` element then getting its *sibling*.  It's fragile, as I indicated in the answer, but it works
Comment: PS: requests to 'Please someone answer quickly' are unlikely to be well received on SO
Comment: how to check sibling is there of not.
Comment: if u can work with the particular xml and get the solution it would be fr8
Comment: The line `if (modelElement != null && modelElement.getNodeName().equals("Model"))` is checking the sibling is there and that it's a `Model` element
Comment: but if i give that na, application is stopped


Unable to add object fetched from mongoDB to normal javascript array

Question: I am trying to create an add to cart button which fetches the data from product database using the id of specific product which I selected. I am trying to push the object found using the same Id into a normal javascript array and then to display it using ejs methods. While I was tring I found I am unable to push the data in object form.
Summary:
On 7th line I have declared an array and in that array I want to store some objects which I have fetched frome a db model.
On 15th line I am trying to push the object form into my array so that I could iterate through the objects to display them on my page using ejs. But I am unable to do that.
screenshots:

Here's the final result I'm getting even after trying to push objects in array:

empty array logged

Here are the objects I'm trying to push:

Objects
Code:

app.get("/cart", (req, res) => {
    if (req.isAuthenticated()) {
        const findcartdata = req.user.username;
        userData.findOne({email: findcartdata}, (err, BookId) => {
            // console.log(BookId.cartItemId);
            const idArray = BookId.cartItemId;
            var bookArray = [];
            idArray.forEach((data) => {
                productData.findOne({_id: data}, (err, foundBookData) =>{
                    // console.log(foundBookData);
                    if(err){
                        console.log(err);
                    }
                    else{
                        bookArray.push(foundBookData);
                    }
                })
            });
            console.log(bookArray);
            // res.render("cart", {
            //     cartBookArray: BookId.cartItemId
            // })
        });
    } else {
        res.redirect("/login");
    }
})

In above code i found the user's email using passport authentication user method and using that email I wanted to add the products in a different javascript array (which I am goint to  pass to my ejs file of cart and then iterate it on list) using those array of Id which I got from another model called userData. The problem is I am able to find userData of each Id but  unable to store them as an array of objects.
Comment: you are not waiting for the Your second promise/callback. ` console.log(bookArray);` this should be run only after you got the results of second array., do it using async await or promiseAll
Comment: Hey Sojin, I tried using async-await but it's not working. Here's the error I got:

nhandledPromiseRejectionWarning: MongooseError: Query was already executed: productData.findOne({ _id: new ObjectId("6177e7b5aaa6cae0d4c...
    at model.Query._wrappedThunk [as _findOne] (D:\Mohit\Web\INT 220 - final project\BookStore\node_modules\mongoose\lib\helpers\query\wrapThunk.js:21:19)
Answer: Looks like a timing issue, your code completes before the database downloads the objects and pushes them to your array.
This should fix your issue:
// ...
const idArray = BookId.cartItemId;
var bookArray = [];
for (const data of idArray) {
    const foundBookData = await productData.findOne({_id: data}).catch(console.error);
    if (!foundBookData) continue;
    bookArray.push(foundBookData);
}

console.log(bookArray);
// ...

By the way, make sure to make the whole function asynchronous as well, which would be done by changing this line:
userData.findOne({email: findcartdata}, async (err, BookId) => { // ...

Comment: Thanks man, I guess I need to learn the concepts of javascript promises again. Well done.
Comment: Hey, The method you mentioned is throwing an error:

UnhandledPromiseRejectionWarning: MongooseError: Query was already executed: productData.findOne({ _id: new ObjectId("6177e7b5aaa6cae0d4c...
    at model.Query._wrappedThunk [as _findOne] (D:\Mohit\Web\INT 220 - final project\BookStore\node_modules\mongoose\lib\helpers\query\wrapThunk.js:21:19)
Comment: I edited my answer, can you take a look at the new version ?


How to queue something in a Cypress test

Question: I have the following test for a custom Cypress command of mine:
it('can navigate to a url', () => {
  const history = createHistory();
  cy.window().then(win => ((win as any).__chh__history__ = history));

  cy.spy(history, 'push');
  history.listen((location, action) => {
    expect(action).to.equal('PUSH');
    expect(location.pathname).to.equal(PATH);
    expect(location.state).to.equal('foobar');
  });

  cy.navigate(PATH, 'foobar');

  cy.wait(0).then(() => {
    expect(history.push).to.have.been.called;
  });
});

The command works fine, but if I remove the cy.wait(0), only doing the expect, then the test fails.
I assume it's because the cy.navigate command (added via Cypress.Commands.add) is queued, like other Cypress commands, meaning the expect actually runs before any of the Cypress commands have even started?
If so, that's fine and as expected of course, but is there a way in Cypress tests to queue things, without using cy.wait(0)?
For example when I'm checking elements, I can use cy.get(something).should($el => expect(...)), but in this case, there's nothing to "should on"... I could of course cy.get('body') or whatever, but I don't really want to get anything in this case.
Comment: I think the trick is to do anything that involves a `cy.window().then` is to put it in the `beforEach()` block, so that it completes before your proper test starts
Comment: In this case, that `cy.navigate` call is specifically what I'm trying to test. So doing it _before_ the test wouldn't really make sense.
Answer: The docs show use of a naked expect() after the spy has been established,
cy.spy(util, 'addListeners')
App.start()
expect(util.addListeners).to.be.called

but I think this is misleading, since expect() runs immediately but intervening Cypress commands may have inherent delays or reties, and can't be guaranteed to complete before the expect is executed.
Two other ways to test this are:
Ensure the expect is only run after your custom command
cy.navigate(PATH, 'foobar').then(() => {
  expect(history.push).to.have.been.called;
})

Put the expectation into the Cypress command queue
cy.navigate(PATH, 'foobar');
cy.wrap(history).its('push').should('have.been.called')


Powering up Video Intercom and magnetic lock with single POE cable

Question: I have the following setup, Video Intercom powered by POE. I need to power my magnetic lock with 12V.
I have a "solution" but don't really want to use it which is Split the cable since POE and 100Mbit use 2 pairs out of 4. And then I could use one of the remaining pairs to provide power to the magnetic lock.
I've been searching for a POE splitter that would provide power on both outputs. On the RJ45 to for data and power for the intercom, and just power for the magnetic lock. So far I have not been able to find a poe adapter/splitter that would do this. The reason I'm looking at an adapter is the installation would be cleaner and more organized avoiding the installation of added devices (power adapter for the magnetic lock).
As someone came across an adapter that provides power output in both RJ45 and DC Jack ?
Comment: POE negotiates the voltage transmitted over the wire, so putting 2 devices on the same wire requires that the splitter is an active device is capable of changing the voltage on at least one part
Comment: Does the intercom use PoE power directly?
Comment: @ratchetfreak, I see thanks.
Comment: @ThreePhaseEel, exactly. Right now the videointercom is powered by POE.
Answer: Can the video intercom be powered by DC voltage on a separate cable as an alternative to PoE? Is there a DC supply voltage that both the lock and the video intercom will accept? (12v is likely.)
Get a passive PoE injector and PoE splitter. Rather than 802.3af/at standard negotiated PoE, this kind puts the DC voltage on the wires without any active negotiation. At the load end you can then wire the DC output to both devices and pass the Ethernet signals through to the video intercom. (photo credit: ebay seller restsale89)

If you prefer 802.3af/at PoE, perhaps so that the devices can be powered by an existing PoE switch which happens to give you remote power-cycle capability, then consider an active PoE splitter. It costs more than the passive kind, but this type will negotiate with the Ethernet switch and will step the nominal 48 V down to your choice of voltage (5v, 12v, etc).
Comment: I ended up with going with this approach since it was the cheaper option. The suggested approach from @jay613 would end up a bit more expensive.
Answer: You need two widgets:

A PoE extender/repeater.   You can get a 1-to-2 port device.   This will allow connection of two PoE devices to one PoE cable.
A PoE splitter for the lock.  This allows use of PoE as a dumb DC power source.  Normally the PoE device negotiates voltage.  The splitter requires you to set the voltage manually, and provides separate ethernet and DC power cables.

It's a bit of a hack, it may not work.  The repeater may have a DC power input plug.   IF the PoE source is capable of powering the repeater, splitter, and both of your devices you may not need to provide external power to the repeater.    You'll need to test it and may need to babysit it over time.
It may be easier and more reliable to power the lock separately, from a nearby AC outlet with a wall wart.


SSH access even if your CMD is closed

Question: Please I want some help
My work manager gives me SSH access to a local server using the command : shh user@local_ip to work on a data sciences project
The running time is so long and if I close my CMD, the running process will be stopped
And while the code running, if I tried to open another CMD or Powershell window to connect to the server, then using the command : screen -list, the output is 0 sockets
I want a way to keep my code running on the server even if I close the CMD window
Note: There's no public hosting, No RDP access
Is there a way to do that?
Thank's for listening.
Answer: You need to run your script with screen in the first place, this is not done automatically. Otherwise there won't be anything in screen -list.

Run screen
Start your script
Press Ctrl - A, then D to detach from your screen.
You can exit the session

To reattach, run screen -r or if there are multiple screens running screen -r <ID>. Check the IDs with screen -ls.
You can also give a session name with screen -S <NAME>, then you can run screen -r <NAME>.

SSH access even if your CMD is closed


PDFBox blurry image when inserted on pdf in Java

Question: I'm trying to insert images inside a PDF but the quality makes the images unreadable. How can improve the quality of final PDF document ?
I have tried other free non GPL license libraries and I think pdfbox is the best, so I would like to be able to use pdfbox.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;

public class pdfBoxTest {

    public static void WritteBufferedImageToPDF(BufferedImage buff)
    {

        PDDocument doc = null;
        PDPage page = null;
        PDXObjectImage ximage = null;
        try {
            doc = new PDDocument();
            page = new PDPage();
            doc.addPage(page);

            ximage = new PDJpeg(doc, buff, 1.0f);

            PDPageContentStream content = new PDPageContentStream(doc, page);

            content.drawImage(ximage, 0, 0);
            content.close();
            doc.save("C:/Users/crusader/Desktop/Hello World.pdf");
            doc.close();

        }
        catch (IOException ie){
            ie.printStackTrace();
            //handle exception
        }
        //save and close
 catch (COSVisitorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public static void main(String []args)
    {
        BufferedImage buff= null;

        try{

            buff = ImageIO.read(new File("C:/Users/crusader/Desktop","tests.jpg"));

        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }

        System.out.println(buff.getWidth());
        System.out.println(buff.getHeight());
        pdfBoxTest.WritteBufferedImageToPDF(buff);
    }
}

Comment: @iddo: try PDPixelMap in the latest version
Comment: The problem stems from PDFBox only being able to use JPEG as the image format for images in the document, which is a lossy format.
I have not found a proper solution yet.
Comment: @Crusader:I have tried your code and its working good,but i am only getting half of the page content(width wise) in the pdf document.Can u please help me with that
Answer: I know a trick that can help you increase the quality in some scenarios with PDFBOX, which is to scale the image (I know it's not a very smart solution, increases the CPU use, file size... but it does work).
public class PdfBoxTest {

    public static void WritteBufferedImageToPDF(BufferedImage buff, int width, int height)
    {

        PDDocument doc = null;
        PDPage page = null;
        PDXObjectImage ximage = null;
        try {
            doc = new PDDocument();
            page = new PDPage();
            doc.addPage(page);

            ximage = new PDJpeg(doc, buff, 1.0f);

            PDPageContentStream content = new PDPageContentStream(doc, page);

            content.drawXObject(ximage, 0, 0, width, height);
            content.close();
            doc.save("C:/Users/crusader/DesktopHello World.pdf");
            doc.close();

        }
        catch (IOException ie){
            ie.printStackTrace();
            //handle exception
        }
        //save and close
        catch (COSVisitorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static final int SCALE_FACTOR = 3;//increases file size and quality

    public static void main(String []args)
    {
        BufferedImage buff= null;
        BufferedImage resized = null;
        try{
            buff = ImageIO.read(new File("C:/Users/crusader/Desktop","tests.jpg"));
            resized = new BufferedImage(buff.getWidth()*SCALE_FACTOR, buff.getHeight()*SCALE_FACTOR, buff.getType());
            Graphics2D g = resized.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(buff, 0, 0, resized.getWidth(), resized.getHeight(), 0, 0, buff.getWidth(), buff.getHeight(), null);
            g.dispose();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }

        System.out.println(buff.getWidth());
        System.out.println(buff.getHeight());

        PdfBoxTest.WritteBufferedImageToPDF(resized, buff.getWidth(), buff.getHeight());
    }
}

*Please, let me know if this has been somehow helpful
Comment: I have tried your code and its working good,but i am only getting half of the page content(width wise) in the pdf document.Can u please help me with that
Comment: Multiply width and height with 0.5f in the content.drawXObject() call.


My GTA 5 just stopped working

Question: My GTA 5 just stopped working. I'm already halfway finished with the game, and now all of a sudden, it just stops working. I tried reinstalling it, but that didn't work. It keeps coming up as an unrecognized disc. Plus, it's a brand new game so I don't get why this is happening in the first place.
Comment: Does the drive play other discs ok?
Comment: try washing the disk with warm water and liquid soap. Make sure you rinse it well and try it off before trying again
Comment: PS3 or 360? Do other games work? I would not recommend washing the disc with warm water and soap, until you have determined that the disc is the issue.
Answer: What console are you playing on? If it is a PS3, just clean your Blueray lens or wash your disc. If it is an xbox360, try washing it. If you are playing on PC, maybe your PC has a virus.
Comment: GTA5 on PC. Sounds like you put a lot of thought into this one.
Comment: [GTA 5 will be released on PC in June of 2014.](http://crossmap.christianpost.com/news/gta-5-pc-release-date-in-june-amazon-reveals-version-excludes-windows-8-gta-san-andreas-mobile-release-is-rockstars-biggest-release-yet-9018)

My GTA 5 just stopped working


Express4.10 bodyParser req.body undefined

Question: I'm trying to build the login of a node application trying to access the route / login get: req.body undefined
Error:
TypeError: Cannot read property 'usuario' of undefined
   at login (/home/makros/workspace/ntalk/controllers/home.js:8:24)
   at Layer.handle [as handle_request] (/home/makros/workspace/ntalk/node_modules/express/lib/router/layer.js:82:5)
   at next (/home/makros/workspace/ntalk/node_modules/express/lib/router/route.js:100:13)
   at Route.dispatch (/home/makros/workspace/ntalk/node_modules/express/lib/router/route.js:81:3)
   at Layer.handle [as handle_request] (/home/makros/workspace/ntalk/node_modules/express/lib/router/layer.js:82:5)
   at /home/makros/workspace/ntalk/node_modules/express/lib/router/index.js:235:24
   at Function.proto.process_params (/home/makros/workspace/ntalk/node_modules/express/lib/router/index.js:313:12)
   at /home/makros/workspace/ntalk/node_modules/express/lib/router/index.js:229:12
   at Function.match_layer (/home/makros/workspace/ntalk/node_modules/express/lib/router/index.js:296:3)
   at next (/home/makros/workspace/ntalk/node_modules/express/lib/router/index.js:190:10)

app.js
var express = require('express'),
load = require('express-load'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
bodyParser = require('body-parser'),
app = express();

load('models')
    .then('controllers')
    .then('routes')
    .into(app);

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.use(cookieParser('secret'));
app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
}));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.static(__dirname + '/public'));

app.listen(3000,function(){
    console.log('Started!');
});

package.json
{
  "name": "ntalk",
  "version": "1.0.0",
  "private": true,
  "scripts": {
  "start": "node ./bin/www"
  },
  "dependencies": {
  "body-parser": "^1.9.0",
  "cookie-parser": "^1.3.3",
  "ejs": "~0.8.5",
  "express": ">= 0.0.0",
  "express-load": "^1.1.14",
  "express-session": "^1.8.2"
  }
}

controllers/home.js
module.exports = function(app) {
    return {
        index: function(req, res) {
            res.render('home/index');
        },
        login: function(req, res){
            console.log(req.params);
            var email = req.body.usuario.email,
                nome = req.body.usuario.nome;
            if(email && nome) {
                var usuario = req.body.usuario;
                usuario['contatos'] = [];
                req.session.usuario = usuario;
                res.redirect('/contatos');
            } else {
                res.redirect('/');
            }
        },
        logout: function(req, res){
            req.session.destroy();
            res.redirect('/');
        }
    };
};

routes/home.js
module.exports = function(app) {
    var home = app.controllers.home;
    app.get('/', home.index);
    app.get ('/entrar', home.login);
    app.get('/sair', home.logout);
};

views/home/index.ejs
<% include ../header %>

Ntalk

Bem-vindo!

            <form action="/entrar" method="post">
                <input type="text" name="usuario[nome]" placeholder="Seu nome">

                <input type="text" name="usuario[email]" placeholder="Seu e-mail">

                <button type="submit">Entrar</button>
            </form>

<% include ../footer %>

Please help me!
Comment: Is this happening on page load, or when you submit the form? You have your handlers registered for `GET` requests, but a `GET` has no body.
Comment: When submit the form, and with method="POST" the problem persists
Answer: You're adding your route handlers to app before your body parsing middleware. All routes/middleware/etc. added to app are executed in order in Express 4.
So move this:
load('models')
    .then('controllers')
    .then('routes')
    .into(app);

after this line:
app.use(express.static(__dirname + '/public'));

On an unrelated note, you typically should place your express.static() usage near the top of your route/middleware list for efficiency. This prevents automatic session creation and unnecessary cookie parsing for static asset requests for example.
Comment: I did as suggested, but the error persists. I suspect that has something to do with express-load, this is the direction they are investigating now.
Answer: try move
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

before
load('models')
    .then('controllers')
    .then('routes')
    .into(app);

Answer: In fact the problem was in my implementation of express-load, it injects dependencies but does not configure the app, so I decided not to use it:
app.js
var express = require('express'),
    path = require('path'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    bodyParser = require('body-parser');

var routes = require('./routes/home'),
    contacts = require('./routes/contacts');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/contatos', contacts);

app.listen(3000,function(){
    console.log('Started!');
});

routes/home.js
var router = require('express').Router();
var home = require('../controllers/home');

router.get('/', home.index);
router.post('/entrar', home.login);
router.get('/sair', home.logout);
module.exports = router;

controllers/home.js
module.exports = {
    index: function(req, res) {
        /*do somethings*/
    },
    login: function(req, res){
        /*do somethings*/
    },
    logout: function(req, res){
        /*do somethings*/
    }
};

There must be a better way to implement using express-load with express4, but not yet found.


Why does rerolling two dice change probability over setting a randomly selected die value?

Question: I stumbled on a youtube video that defined the following problem:

2 dice are rolled.

A 3 appears on at least one of the dice.

Find the probability that the sum of the upper-most faces is greater than 7.

We assume that the 3 appears on the upper-most face of the die.
My initial thought was that the result would be 2/6, but the video explained that it's 4/11.
I wanted to roughly confirm that (and I did, that's not the issue), so I wrote a JS function to test it over a milion/bilion/x samples.
At first I was getting a slightly higher result though, and only upon fixing a logical "error" I was able to get the correct 4/11 result.
The error was that instead of rerolling both dices until one of them is 3, I was setting a randomly selected dice to 3 if neither of them was a 3.
Code before the change:
function testTheory(samples = 10000000) {
    function roll() {
        return Math.floor(Math.random() * 6) + 1;
    }

    let positive = 0;
    for (let i = 0; i < samples; i++) {
        let rollA = roll();
        let rollB = roll();

        // Substitution
        if (rollA !== 3 && rollB !== 3) {
            const rollC = roll();
            if (rollC > 3) {
                rollA = 3;
            } else {
                rollB = 3;
            }
        }

        if ((rollA + rollB) > 7) {
            positive++;
        }
    }
    console.log(`Positive: ${positive}, probability: ${positive/samples}`);
}

Prints: Positive: 3887204, probability: 0.3887204 when called (numbers might differ slightly).
Code after the change (it's pretty much the same, only the lines next to the comment change):
function testTheory(samples = 10000000) {
    function roll() {
        return Math.floor(Math.random() * 6) + 1;
    }

    let positive = 0;
    for (let i = 0; i < samples; i++) {
        let rollA = roll();
        let rollB = roll();

        // Rerolling
        while (rollA !== 3 && rollB !== 3) {
            rollA = roll();
            rollB = roll();
        }

        if ((rollA + rollB) > 7) {
            positive++;
        }
    }
    console.log(`Positive: ${positive}, probability: ${positive/samples}`);
}

Prints Positive: 3638915, probability: 0.3638915 when called (numbers might differ slightly).
I do not understand however why is that changing the probability, in my head that's pretty much the same operation. I'd really appreciate an explanation.
Comment: In the first code, if both dice are different than $3$, then you randomly substitute _one_ of the values with $3$, which excludes the possibility of obtaining $(3,3)$. Hence, if you had to re-roll, you could only get _exactly_ one $3$, as opposed to _at least_ one 3.
Comment: @Bergson I see it now, upon fake-rerolling I was getting 1 less possible "negative" outcome, which was influencing the probability. Thank you!
Comment: Knowing that a $3$ appears rules out many outcomes. This need not change the probability for some event , but usually this is the case.
Comment: Conditional probability that you get $5$ or $6$ on the other die given you got $3$ on one die is indeed $4/11$, as can be easily shown. You find it counterintuitive? Intuition can mislead.
Answer: In your first code, you are calculating
$$\frac{11}{36}\frac{4}{11}+\frac{25}{36}\frac{2}{5}$$
$$=\frac{1}{9}+\frac{5}{18}$$
$$=\frac{7}{18}$$
which is the probability the event happens (at least one three and then no threes), times the probability the sum is greater than seven ($35,36,53,63$ from $11$ and then $5$ or $6$ from a sample space of $\{1,2,4,5,6\}$), summed together.


jQuery validation, append an addition field to validate on div click

Question: I want to add an additional field to validate when user click on a specific div or text. Here is the scenario, I have a form that is validated using jQuery validation, there are two fields that I did not include for validation, for the purpose of I want this two field to be validated when the user click on "Change Password?" text. How could I add and additional field to validate during runtime?
Change Password

$(document).ready(function() {
 $("#update_user").validate({

        rules: {
          "admin_account[name]": {
            required: true
          },
          "admin_account[email]": {
            required: true
          },
          "admin_account[gender]":{
            required: true
          },
          "admin_account[nationality]":{
            required: true
          },
          "admin_account[photo]":{
            accept: false
          },
          "admin_account[date_of_birth(1i)]":{
            required: true
          },
          "admin_account[date_of_birth(2i)]":{
            required: true
          },
          "admin_account[date_of_birth(3i)]":{
            required: true
          }
        },
        errorPlacement: function(){
            return false;  // suppresses error message text
        }

      });

//I want to trigger here an additional validation for the password field
$(".change-password").on("click", function(){
    $("#update_user").validate({

        rules: {
          "admin_account[name]": {
            required: true
          },
          "admin_account[email]": {
            required: true
          },
          "admin_account[password]":{
            required: true
          },
          "admin_account[password_confirmation]":{
            required: true,
            equalTo:"#edit_registerPassword"
          },
          "admin_account[gender]":{
            required: true
          },
          "admin_account[nationality]":{
            required: true
          },
          "admin_account[photo]":{
            accept: false
          },
          "admin_account[date_of_birth(1i)]":{
            required: true
          },
          "admin_account[date_of_birth(2i)]":{
            required: true
          },
          "admin_account[date_of_birth(3i)]":{
            required: true
          }
        },
        errorPlacement: function(){
            return false;  // suppresses error message text
        }

      });
});

Comment: What exactly happens when user clicks on `.change-password` element?
Comment: it show two field, for the password field and confirm password. I want this two field will also get validated. and when the user click the "cancel" the two field will get hide and no longer get validated
Answer: jQuery validation has an ignore property which excludes the specified elements from validation process. By default it's value is set to :hidden and it exactly does what you want, i.e. it excludes the hidden elements. Just define the rules in the first validate call and remove the second validate function.


Why are there no Pokémon near me?

Question: I see pictures online of everyone having all these Pokémon to catch being everywhere around them, but it seems like I can only ever see one or two. I live in a rural area, but even walking miles through the farmland, it's rare to find any Pokémon.
Why is this? How can I find more Pokémon?
Answer: Pokémon spawns in Pokémon Go are random, so it could just be bad luck if you don't have any near you, and you might want to try again later. However, the spawn locations are also weighted based on population density. Much like in Niantic's other game Ingress, Pokémon Go uses Google Traffic to get the traffic density in each area by tracking the GPS locations of Android phones. The more people that frequent an area, the more Pokémon there will be there.
Ironically, the best way to find wild Pokémon is to go to the city, not the wild.
I believe that PokéStops are also weighted a bit more heavily, because I saw many Pokémon spawn directly on top of my church in the country, but I suppose that could just be because a few hundred people spend a few hours there every week. Regardless, this could be a useful plan if just because many people go to those locations.
If you are really in the middle of nowhere though and unable to find fellow humans, the best plan would be to wait. Even if there are no Pokémon near you when you start the app, just having the app open will cause at least some Pokémon to spawn near you. I don't think I've waited long without having any Pokémon near me, so I would just go look for the one or two that are nearby, because more should spawn while you catch those.
And then if you don't want to move or wait, you can always just pay money. Using Incense will make more Pokémon spawn near you for 30 minutes, so that's a pretty good solution for the rich farmer. If you are at a PokéStop and you want more Pokémon, you can also use a Lure on one and it will cause more Pokémon to spawn by that PokéStop. If you're lucky, someone else may have already used one on a local PokéStop and you can benefit for free.
Comment: The article which claims "just having the app open will cause at least some Pokemon to spawn near you" has numerous factual errors. Pokemon spawns are reportedly on a timer, something like randomly once an hour at each spawn point, and the Pokemon de-spawns after 15 minutes. The number of spawn points in an area is based on the Android GPS location data.
Comment: "Even if there are no Pokémon near you when you start the app, just having the app open will cause at least some Pokémon to spawn near you."
I beg to differ, I have had the app for 5 days now and I have not seen a SINGLE pokemon nearby since the starters, checking it regularly for the first 2 days, not so much anymore. I live really out in the boonies. Even took a few 1-3 km walks and still nothing. Have to go to the village nearby for anything to spawn
Comment: @h0ch5tr4355 Boston has more then 600000 People living there.if only 1% of them is using Android that will be enough.i live in a very small town and even here i can find some.only when i go in the wood or field where no houses or streets are,i find no pokemon at all
Comment: I wonder if more people go to church now...
Comment: Is it really based on Android Smartphones? I heard of regions like Boston where iOS has user rates of about 90 percent. Would that mean that there are nearly no Pokemon in Boston? :D
Comment: Well, gotta go buy 100 smartphones, be right back.
Comment: More seriously, in rural areas, running Ingress can help as there might be a correlation between Ingress XM spawns and Pokemon GO. At home, whenever I have pokemon in the nearby list, I know most of them spawn at the neighbour's home. I tested this in another rural area: one unknwon pokemon nearby; checked Ingress for xm, went to the nearest xm spot, and sure enough the pokemon was there.
Answer: I work on a military air base with a nice cushy desk job. I've spent an entire day refreshing and keeping the app running without finding a single pokemon. It helps to have multiple people with their apps open all together. Increase appearances. Density is everything
Comment: Millitary/Government areas are given a 0% spawn rate.
Answer: Ullallulloo is right. It's kind of random. I have even used an incense and had none spawn in the 30 minute duration. High traffic areas are better. Our shopping center has 4 gyms and 2 pokestops in the same area. The entire thing can't be more than a km across...

Why are there no Pokémon near me?


Open a new ViewController on Button Click if text entered matches Parse string

Question: So I'm trying to create a registration page with availability by Zip Code. For instance, a user can only register if the service is available in their area (zip code).
So far I have a Text field for Zip Code and a button labeled "Check Availability".
I have a Parse Backend and I tested a connection to it using their setup guide and it works.
How can I go about checking the text that was inputted to see if it matches a zip code in my parse database? So if a the zip code the user entered matches one in the parse database I need a new ViewController called "Register" to open and the user can begin their singup/registration.
Current Code:
<code>class checkAvailability: UIViewController {

@IBOutlet weak var zipCode: UITextField!
@IBAction func checkAvailBtn(sender: AnyObject) {
    performSegueWithIdentifier("beginSignUp", sender: self)
}

func checkZip() {
    var usersZipCode = zipCode.text
    var queryZip = PFQuery(className: "zipCode")
    queryZip.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
        if error == nil {
            // The find succeeded.
            println("Successfully retrieved \(objects!.count) zip codes.")
            // Do something with the found objects
            if let zipCodes = objects as? [PFObject] {
                if zipCodes.contains({ $0["zipCodes"] == usersZipCode) {
                print("your in!") // transition to the new screen
                }
                else {
                print("your out.") // do whatever
                }
                }
            } else {
                // Log details of the failure
                println("Error: \(error!) \(error!.userInfo!)")
            }
        }

override func viewDidLoad() {
    super.viewDidLoad()

    //Code
}
</code>
Thank you
Answer: Create a PFQuery to pull down the list of zip codes into the app, then simply check to see if the string the user entered is in the list.
-- EDIT --
<code>    let query = PFQuery(className:"ZipCode")
    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) -> Void in

        if error == nil {
            // The find succeeded.
            print("Successfully retrieved \(objects!.count) zip codes.")
            // Do something with the found objects
            if let zipCodes = objects as? [PFObject] {
                if zipCodes.contains({ $0["zip_code"] as! String == usersZipCode }) {
                    print("your in!") // transition to the new screen
                }
                else {
                    print("your out.") // do whatever
                }
            }
        } else {
            // Log details of the failure
            print("Error: \(error!) \(error!.userInfo)")
        }
    }
</code>
Comment: I found and fixed an error in the `zipCodes.contains` line. Warning, the above is written in Swift 2.0. If you are using 1.0, you will have to change the prints to printlns. *That said* there are some huge issues with the code in your question that have nothing to do with my code. If you continue having problems with it, I think you should start a new question with your code and what the compiler is complaining about.
Comment: Could you provide some code I can use as reference?
Comment: Generally, it works best here if you include the code you are having trouble with in your question and we can help you make it work. That said, I posted something in my answer, maybe it will help.
Comment: What happened when you ran the app and entered a bad zip code? Did it do what you wanted it to?
Comment: The app was not able to build properly
Comment: It throws a lot of wrong syntax errors with that code. Check out my updated code.
Comment: I suggest you look up the documentation for `performSegueWithIdentifier` and then read the comments I put in the code. Hopefully, a light bulb will go off over your head.
Comment: I've got the idea behind performSegueWithIdentifier and I have it working correctly. The thing is I get a lot of errors using the code your provided, the errors are syntax and have to do with the brackets. I just can't figure out how to resolve it.


GPU Monitor is missing on android studio 3.0

Question: In android studio 2.3 the GPU Monitor is located in motions tab.

In android studio 3.0 it has been replaced with Android profiler and it contains every thing in the old monitor tab except the GPU Monitor.

is there a way to enable GPU Monitor or a replacement in the android studio 3.0
Comment: Is that a programming question ?
Comment: yes, asking question android studio is very common on StackOverflow as it is directly linked with the development process.
Comment: Did you research ? Read [this](https://developer.android.com/studio/profile/am-gpu.html)
Comment: of course, I did, this only available in version prior to AS 3.0. I mention this in my question.
Comment: Where did you see it's only for prior  A.S 3.0 ?  (don't make me fire up my AS and shame you lol - just joking)
Comment: I have both android studio 2.3 and 3.0. and I simply can't find it in 3.0. If you have AS 3.0 please do
Comment: awww sorry. I have 2.3.2 ... So no can't you. Good luck... Read carefully the documentation, you may even have to [perform dependencies check](https://developer.android.com/studio/profile/am-basics.html#byb)
Comment: And also AWWW bro... I just googled. Version 3.0 is not even stable yet. Don't wait you time please.
Comment: I know it is in beta. but as the AS team said they will not add new features. only bug fixes till the release.
Comment: Im not sure what was in https://developer.android.com/studio/profile/am-gpu.html a few weeks earlier, but it says that the GPU profiler tool has been removed from AS 3.0 as of today :'(
Answer:
https://developer.android.com/studio/profile/am-gpu.html
:'( this seems to be removed from Android Studio 3.0 . Not quite sure why


(xRDP) Desktop looks different when connecting remotely

Question: I've looked around online about this issue and haven't really found anything that helps me. I'm relatively new to Ubuntu and recently set up a tower so that I could connect to it over the internet via xRDP. That aspect of it works fine, but, for some reason, the desktop looks different on the remote login.
The GNOME dock isn't present on the home screen and looks different when I open the activities thing. Plus I'm missing the dock's customization section in the Settings application. That's really all I've immediately noticed, but I also don't have the experience with Ubuntu to really know what else might be missing.
Is there some way to fix this? I only have one user set up on the computer and use it to log in when connecting remotely, I don't know if that's of any importance or not.
Answer: We are assuming that you are running Ubuntu 18.04 or later, as you are connecting to the GNOME Desktop.  The problem you are describing is expected when you perform a manual installation (with no further actions).
To solve your issue, you have multiple options:
1. Manually change the look and feel within your remote session
This post from my personal blog provides a step by step explanation on what you need to do.  In a nutshell:

Install Tweak tool:
sudo apt-get install gnome-tweak-tool
sudo apt install gnome-tweaks  # for Ubuntu 22.04 ref. https://askubuntu.com/questions/1233088/xrdp-desktop-looks-different-when-connecting-remotely#comment2580018_1407324

Open the tool, go to the Extensions node, and enable the Dock bar.

Go to the Appearance node and select the Theme to be used (often it's Yaru).

2. Create a login script file
Copy the code below into your Terminal console and let it execute.  This will create a file called .xsessionrc. This file is kind of a login script that will load your desktop configuration into the remote session. After the file is created, login back to the xRDP session and see if the desktop looks like the one you have when logged on locally.
cat <<EOF > ~/.xsessionrc
export GNOME_SHELL_SESSION_MODE=ubuntu
export XDG_CURRENT_DESKTOP=ubuntu:GNOME
export XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/etc/xdg
EOF

3. Use scripted installation
Next time, you perform a xRDP installation, you could use the script that can be found in my personal blog to automate the installation and let it perform for you the post-configuration actions that make the desktop interface look similar when connected locally or remotely through xRDP. There is also a how-to guide provided as well with the script (see the above link).
Please note that the script is updated on a regular base, so please be sure to check if a new version of the script is available.
Comment: I tried Option 2 and it did not work for me.
Comment: Hello, Ok sorry to here that.... are you using Ubuntu 18.04 and gnome desktop ?  The command above in option 2 would only work for Ubuntu running the gnome desktop interfaces....
Comment: Thanks. I am using Ubuntu 20.04 with gnome desktop.
Comment: The reason it didn't worked for you @SaTa is because of the `echo` at the beginning of the second line. Try it like this: cat < ~/.xsessionrc export GNOME_SHELL_SESSION_MODE=ubuntu export XDG_CURRENT_DESKTOP=ubuntu:GNOME export XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/etc/xdg EOF
Comment: For some reason , the version 1.4.7 from your blog is not working for me. Client window automatically closes after trying to connect. Can you please let me know what I am doing wrong?
Comment: ok.. do not know yet... check that the file ~/.xsessionrc is indeed created with the correct content.   You can also try this piece of code and see if this is better   DesktopVer="$XDG_CURRENT_DESKTOP"
SessionVer="$GNOME_SHELL_SESSION_MODE"
ConfDir="$XDG_DATA_DIRS"
sudo sed -i "4 a #Improved Look n Feel Method\ncat < ~/.xsessionrc\nexport GNOME_SHELL_SESSION_MODE=$SessionVer\nexport XDG_CURRENT_DESKTOP=$DesktopVer\nexport XDG_DATA_DIRS=$ConfDir\nEOF\n" /etc/xrdp/startwm.sh
Comment: On Ubuntu 23.10 I found that to enable the dock I had to enter
`gnome-extensions enable firstname.lastname@example.com` from this answer https://askubuntu.com/questions/1403431/update-to-22-04-problem-with-dock
Answer: The answer above is great, but note that in Ubuntu 22.04 step 1 has changed to:
sudo apt install -y gnome-tweaks
There you just enable the 3 built-in options (Especially the Ubuntu Dock), and you should be good to go.
Comment: Worth noting that `gnome-shell-extension-prefs` is in fact deprecated, the only supported version is now `gnome-tweaks`.
Comment: @Pilot6 Incorrect, this absolutely helped with the problem, I'm having exactly the same issue as OP and this helped. I had to combine this solution with the above xsessionrc script to get everything working in xRDP.
Comment: @Pilot6 what's up with the flagging? This is the second post I've seen you report answers as non-answers that are, in fact, answers.
Comment: Please describe in detail what " 3 built-in options" you are referring to.