Searching MongoDB with Rails

Question: I am using ruby 1.9.3p194 and rails 3.2.5
when i do
<code>@authors = Author.all
</code>
it works fine by outputing all name from my database.
But
<code>@authors = Author.where("name like ?", "%#{params[:q]}%")
</code>
is not working. I am using Mongodb. I want to output the name(Ram) when i input R.
What could be the solution?

By this method i can search params[:q] through my field :name only. How can i add other field name also such i want to seach this params[:q] in text field :role , :email also at once? I used || but it gives error.
I have to write this in comment but since my comment list is long . I ask this question here.
Sorry for that.
Answer: MongoDB doesn't use "LIKE" queries as in SQL.
You (can) use regular expressions:
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions
To solve your specific problem, you could use
<code>@authors = Author.where(name: /#{params[:q]}/)</code>, but I'm not entirely sure if this can be a security issue or not.
Comment: `/#{Regexp.escape(params[:q])}/` might server you better. And it is worth noting that you'll be limited to the regexes that MongoDB supports rather than Ruby's.
Comment: DO u have any idea that search condition works for capital letter also. I mean to say( if a then it displays all associated data including capital letter also) for ex a->apple,Aeroplane
Comment: To make it case insensitive, add a "i" to the end, like this: `/#{Regexp.escape(params[:q])}/i`
Comment: can we code it such that if one data is choosen then it will not display second time. for example i choose m(results mongo monkey) and mongo is chhosen there. and in second time also if i choose m then only monkey should be displayed . I am using jquery token. might i have to change in js or here i am confused.
Comment: @regmiprem probably, but that should be another question
Comment: ya it should be another question but do you have any idea about this. Since u are giving awesome answers so i think that by posting this question here, i can connect u directly.  http://stackoverflow.com/questions/12154136/any-idea-not-to-select-the-name-that-is-already-choosen-in-token-input
Comment: By this method i can search params[:q] through my field :name only. How can i add other field name also such i want to seach this params[:q] in text field :role , :email also at once? I used || but it gives error. I have to write this in comment but since my comment list is long . I ask this question here. Sorry for that.

Searching MongoDB with Rails


Definition of configuration tag

Question: I just tagged a question with configuration, referring to Configuration. However, the tag is probably otherwise used for any general configuration problem.
What definition of the the tag do we want?
Comment: [tag:libraries] has the same issue.
Answer: Using the tag for the module is much better, IMO. It would be too broad, if it is used for any configuration question.
The tag is actually used from the following questions, which have very few in common:

How to choose between Bean, Boxes and Fieldable Panels Panes?
Parsing a multi-valued theme-setting into to two defaults results in theme-settings not saving
Cannot access configuration pages
Configure Modules from a Script

Considering there is also settings, I would keep configuration for the module. Instead of configuration, we could use configuration.module, if the risk of misusing the tag is high.
What I would do is:

Use configuration.module for the question about the module
Merge configuration with settings (without to make them synonyms)
(Eventually) Rename configuration.module as configuration
Comment: I've retagged my question with configuration.module. I suggest we consider the above answer official policy for now :)

Definition of configuration tag


How do I limit string length using Javascript .replace() with a regex pattern?

Question: I am trying to limit a zip code to 5 and digits with a replace()
I have googled many variations of the expression.
$('#ZIP').on('keyup', function () {
    $(this).val($(this).val().replace(/[\D]{5}$/g, ''));
});

I have tried these and many more:
/\D{5}/g
/[\D]{5}/g
/([\D]){5}/g
/[^0-9]{5}/g
Then all of the above with {0,5}
I've tried them with $
Also, the normal pattern.test() seems to work differently than replace.
What am I missing?
Here is a snippet to play with:

$('#ZIP').keyup(function() {
 $(this).val($(this).val().replace(/(\D){0,5}/,""));
});

<input type="text" id="ZIP"/>

After playing with the code for a while, I noticed that /\D{5}/g will allow only 5 letters. So I'm sure my lack of expression know-how is preventing me from getting this
Answer: You may simply do:
$('#ZIP').keyup(function(){
    $(this).val($(this).val().replace(/\D/g,"").slice(0,5));
});

Check out the demo below

$('#ZIP').keyup(function(){
 $(this).val($(this).val().replace(/\D/g,"").slice(0,5));
});

<input type="text" id="ZIP"/>
Comment: @Jeremy: if your interest is purely academic, I can understand that, but from practice standpoint it doesn't make sense to stack up some messy regex to catch all the possible tricky inputs where simple string slicing works perfectly fine. Moreover, regex solution will get you those *bouncing back and forth* characters which doesn't seem aesthetic to you ;)
Comment: Then, right off the top of my head, catch this one: `s.replace(/(\D)|(?<=.{5})./g,'')`, hopefully it gets me accept ;)
Comment: Nice! I can set the maxlength attribute on the  element also. But I would like to figure out how to do this with the expression. I'm sure it can be done.
Comment: I agree. And, yes it is purely to see if it can be done, lol. I was just curious!
Comment: @YevgenGorbunkov I can right-click and paste a non-zipcode into the text
Comment: Yeah bro, you totally got it! Excellent!
Comment: @symlink, your answer is more robust and I like it, but like Yevgen point out, I simply wanted to know how to do it in the regular expression.
Comment: @symlink, dude no need to delete your post, your answer is awesome and could help others out.
Comment: @symlink: just like there's no need to downvote mine due to getting upset ;) , however, I agree with Jeremy it is really nice how it silently ignores invalid input. Undelete and I will gladly upvote. And please remove copy-paste disabling thing ;)
Comment: @YevgenGorbunkov your code is flawed, I won't delete the comment.
Comment: @symlink: can you be more specific what's wrong with it in your opinion? Would you give some test string that passes through?
Answer: Here's how I might do this:

function extract5digitZip(str)
{
 // Create a regular expression that can
  // be used to remove all non-digits:
 let rxMatchNonDigits = /[^\d]+/g;

 // Remove all non-digits
 str = str.replace(rxMatchNonDigits,"");

 if (str.length >= 5)
 {
  return str.substr(0,5);
 }
  // If 5 digits can't be extracted
  // return an empty string
 return "";
}
console.log(extract5digitZip("abc75926xyz"));
console.log(extract5digitZip("77036-1234"));
console.log(extract5digitZip("a1b2c3d4e5f6"));


Making a Python unit test that never runs in parallel

Question: tl;dr - I want to write a Python unittest function that deletes a file, runs a test, and the restores the file. This causes race conditions because unittest runs multiple tests in parallel, and deleting and creating the file for one test messes up other tests that happen at the same time.
Long Specific Example:
I have a Python module named converter.py and it has associated tests in test_converter.py. If there is a file named config_custom.csv in the same directory as converter.py, then the custom configuration will be used. If there is no custom CSV config file, then there is a default configuration built into converter.py.
I wrote a unit test using unittest from the Python 2.7 standard library to validate this behavior. The unit test in setUp() would rename config_custom.csv to wrong_name.csv, then it would run the tests (hopefully using the default config), then in tearDown() it would rename the file back the way it should be.
Problem: Python unit tests run in parallel, and I got terrible race conditions. The file config_custom.csv would get renamed in the middle of other unit tests in a non-deterministic way. It would cause at least one error or failure about 90% of the time that I ran the entire test suite.
The ideal solution would be to tell unittest: Do NOT run this test in parallel with other tests, this test is special and needs complete isolation.
My work-around is to add an optional argument to the function that searches for config files. The argument is only passed by the test suite. It ignores the config file without deleting it. Actually deleting the test file is more graceful, that is what I actually want to test.
Answer: I frequently need to run tests with complete isolation. The only way I've found that works consistently is to put those tests in separate classes. Agreed that handling config files inside tests is still kind of a pain.
For something I'm doing right now, I may also try something like pytest-ordering for running tests in a more deterministic fashion.
Answer: The Django 3.2 documentation contains an official solution to this problem using the django.test.testcases.SerializeMixin. This will force certain tests to run in series and prevent errors arising when they try to access the same resource.
As per  the Documentation, you would do something like this:
import os

from django.test import TestCase
from django.test.testcases import SerializeMixin

class ImageTestCaseMixin(SerializeMixin):
    lockfile = __file__

    def setUp(self):
        self.filename = os.path.join(temp_storage_dir, 'my_file.png')
        self.file = create_file(self.filename)

class RemoveImageTests(ImageTestCaseMixin, TestCase):
    def test_remove_image(self):
        os.remove(self.filename)
        self.assertFalse(os.path.exists(self.filename))

class ResizeImageTests(ImageTestCaseMixin, TestCase):
    def test_resize_image(self):
        resize_image(self.file, (48, 48))
        self.assertEqual(get_image_size(self.file), (48, 48))

Answer: Firstly most testing framework that support parallelism also support methods to serial certain important tests. For instance Python Fabric support a serial annotation (when you launch your test as a parallel suite with command line flag -P):
from fabric.api import *

def runs_in_parallel():
    pass

@serial
def runs_serially():
    pass

However, I don't think you should do that, I think you should stop and contempt for a moment. Following the Single Responsibility Principal this is what I would say is going on.
You are in a situation where a test has essentially identified a condition of your code, it's highlight a little spot of cohesion for you.
What you should do now is realise that "converter.py" has too many responsibilities, not only does it perform some complex operation under the hood it is also responsibility for managing it's own creation and set-up in a way that is probably too much for it.
Perhaps if you had an object that can management reading in that file, you could then easily mock/stub it out and produce the condition you are describing that you want to test.
Comment: I am aware of Fabric, but I didn't know the `@serial` decorator, so thank you. Regarding the Single Responsibility Principle: I feel that I already adhere to it well. `converter.py` is just one file, but it has multiple functions (not too many). One of the functions is `load_config()`, and it has just one responsibility. Iff it finds a config file, it loads it, otherwise it uses the defaults. It actually doesn't need any arguments, but I added `load_config(use_defaults=False)` and pass in `True` ONLY during unit tests, which is what you suggested. This is suboptimal.
Comment: (Part 2 of 2) Using a kwarg like this has two problems: First, the source code of `converter.py` just became more complex. I just added a feature to `converter.py` that nobody should ever use, only unit tests should use it. That is the definition of something that belongs with the tests, not the code itself. Second: What if all the tests pass using this fake-out, but *actually* not finding a file causes a hard crash? The unit tests cannot see this problem anymore. The unit tests will pass. If `os.listdir()` changes and there is a regression, I will not see it.
Comment: Yup, I would concur with you points there. Answered this question a long old time ago and would have different ideas about things at this point.
Answer: The best testing strategy would be to make sure your testing on disjoint data sets. This will bypass any race conditions and make the code simpler. I would also mock out open or __enter__ / __exit__ if your using the context manager. This will allow you to fake the event that a file doesn't exist.
Answer: The problem is that the name of config_custom.csv should itself be a configurable parameter. Then each test can simply look for config_custom_<nonce>.csv, and any number of tests may be run in parallel.
Cleanup of the overall suite can just clear out config_custom_*.csv, since we won't be needing any of them at that point.
Comment: The file name actually is configurable. I really want to test the behavior if nothing is found. My work-around, mentioned in my original question, is fundamentally similar to this suggestion, and it doesn't actually test the behavior I want. My work around is to tell the config-file-finder "do not look for any config files". You suggestion is basically "only look for specific config files". I want to test the behavior if it looks normally and finds nothing. I do not want to turn off or limit the search itself.
Comment: @SerMetAla Using distinct files is a good way to do it without introducing locking. If you can't use distinct sets of files then you should just use locks.


Find $P$ such that $P' | P$

Question: I want to know how to answer this question:

Find all polynomial in $\mathbb{R}[X]$ such that the derivative $P' \ | \ P$.

My effort:
We know that

An $n$ degree polynomial has $n$ roots in $\mathbb{C}$.
$P(x) = P'(x) \cdot (ax+b).$

Thus we can suppose that
$$P' = b(x-a_1)(x-a_2)\dots(x-a_{n-1}),$$
and
$$P = c(x-a_1)(x-a_2)\dots(x-a_{n-1}) (x-a_{n})$$
where $b, c\in \mathbb{R}$ and $a_1,\dots,a_n \in \mathbb{C}$.
Take the derivative we have
$$P' = c(x-a_2)(x-a_3)\dots(x-a_n)+c(x-a_1)(x-a_2)\dots(x-a_n)+ \dots + c(x-a_2)(x-a_3)\dots(x-a_{n-1}).$$
Since $P'(a_1) = 0$, we then have $c(a_1-a_2)\dots(a_1-a_n) = 0$, thus $x\in \{{a_2,\dots, a_n}\}$. Suppose that $a_1=a_2$.
Then $$P = c(x-a_1)^2(x-a_3)\dots(x-a_{n-1}) (x-a_{n}).$$
Hopefully at some point, I can get $P = c(x-a_1)^n$.
Comment: Note first that a linear factor $x - a$ divides both $P$ and $P'$ iff $(x - a)^2$ divides $P$.
Answer: Let $$P(x) = a_nx^n+....+a_1x+a_0,$$ then we have $$ a_nx^n + ...+a_1x+a_0 = (a_n\cdot n\cdot a) x^n+...+(aa_1+2a_2b)x+a_1b$$ Since $a_n\neq 0$ we get $an=1$, so $a=1/n$

Write $$ {P'(x) \over P(x)} = {1\over ax+b}$$
Then $$a(\ln P(x))' = (\ln(ax+b))'$$ and thus $$a\ln(P(x) = \ln(ax+b) + c$$
So $$P(x) = (ax+b)^{1\over a} e^c = (ax+b)^ne^c$$
Answer: For a polynomial $P$ of degree $n$, we always have
$${P'(x)\over P(x)}={1\over x-r_1}+{1\over x-r_2}+\cdots+{1\over x-r_n}$$
where $r_1,r_2,\ldots,r_n$ are the roots of $P$.  If, at the same time, we have $P'\mid P$, then $P(x)={1\over n}(x-r)P'(x)$ for some $r$ (since $P'$ is of degree $n-1$ with lead coefficient that is $n$ times the lead coefficient of $P$).  This gives us
$${n\over x-r}={1\over x-r_1}+{1\over x-r_2}+\cdots+{1\over x-r_n}$$
If we do not have $r_1=r_2=\cdots=r_n=r$, then the right hand side has a singularity where the left hand side does not. Thus if $P'\mid P$, we must have $r_1=r_2=\cdots=r_n=r$, and so $P$ must have the form $P(x)=a(x-r)^n$. We also need $a,r\in\mathbb{R}$ in order for $P$ to have real coefficients.
Remark: The key equality can be proved by induction: If $P(x)=(x-r_n)Q(x)$ with
$${Q'(x)\over Q(x))}={1\over x-r_1}+{1\over x-r_2}+\cdots+{1\over x-r_{n-1}}$$
then
$$\begin{align}
{P'(x)\over P(x)}
&={((x-r_n)Q(x))'\over(x-r_n)Q(x)}\\
&={(x-r_n)Q'(x)+Q(x)\over(x-r_n)Q(x)}\\
&={Q'(x)\over Q(x)}+{1\over x-r_n}\\
&={1\over x-r_1}+{1\over x-r_2}+\cdots+{1\over x-r_{n-1}}+{1\over x-r_n}
\end{align}$$
(with the base case, $P(x)=a(x-r_1)$, being straightforward to check).
Answer: Write $P(x) = P'(x) L(x)$, where $L$ has degree $1$.
Write $P(x) = L(x)^m Q(x)$, where $Q$ is coprime with $L$.
Then $P' = m L^{m-1} L' Q + L^m Q'$ and so $L^m Q = P = P'L = m L^{m} L' Q + L^{m+1} Q'$.
Therefore, $Q$ divides $ L^{m+1} Q'$. Since, $Q$ is coprime with $L$, $Q$ must divide $Q'$, and this happens iff $Q$ is constant.
Thus, $P=q L^m$.
Answer: Assume $P$ is of degree $n$. Then $P'$ is of degree $n-1$. Then of course, $P'| P$, means that there is a polinomial $Q$ of degree 1 such that $P'Q = P$. (Otherwise the degree of $QP'$ would not be the same as the one of $P$)
Let's write $P = a_n x^n + ... + a_1x + a_0$. Then $P' = n a_n x^{n-1} + (n-1)a_{n-1}x^{n-2}+... + a_1$
We can write $Q$ as $bx + c$, so $Q P' = (bx+c)(n a_n x^{n-1} + (n-1)a_{n-1}x^{n-2}+... + a_1) = $ $= a_n n b  x^n + (a_{n-1}(n-1)b + na_n c)x^{n-1}+... + (a_{i-1} (i-1)b+a_i ic)x^{i-1} +  (a_1 b + a_2 2 c )x+a_1 c $
Then, since $QP' = P$, we must have
\begin{cases} a_n = a_n n b \\ ...   \\ a_{i-1} = a_{i-1} (i-1) b + a_i i c \\ ...  \\ a_0 = a_1c \end{cases}
For the first equation we know we must have $b = \frac{1}{n}$ and from the last $c = \frac{a_0}{a_1}$
Then, if all the other $a_{i-1} = a_{i-1} (i-1) b + a_i i c$ for $i = 1... n-1$ are good with that, we reach our goal. That means they have to solve $a_{i-1} = a_{i-1} (i-1) \frac{1}{n} + a_i i \frac{a_0}{a_1}$
That is $a_{i-1} (1 - \frac{i-1}{n}) = a_i i \frac{a_0}{a_1}$, which is $a_{i-1} = a_i i \frac{a_0}{a_1}\frac{n}{n-i+1}= a_i \frac{a_0}{a_1}\frac{in}{n-i+1}$
That gives us a way to find, with free $a_0, a_1, a_n$ all the others $a_i$. However, if we apply that to $a_1$, it gives us $a_1=a_2 \frac{a_0}{a_1}\frac{n}{n} $, which means $a_1 ^2 = a_2 a_0$
Answer: $P$ is a solution to the differential equation
$$\frac{P}{P'} = Ax + B $$
for some $A$ and $B$ in $\mathbb R$.
This is true because
1)   $\operatorname{deg} (P') = \operatorname{deg}(P) - 1$,
2)   $P/P'$ happens to be a polynomial because $P' \mid P$
3)    $P/P'$ has degree $1$ by my first point, and therefore has the general form $Ax+B$
Taking the reciprocal gives
$$\frac{P'}{P} = \frac 1 {Ax + B}$$
This is a separable differential equation. So we can write the above as
$$\frac{d}{dx}\log(P(x)) = \frac1A\frac{d}{dx}\log(Ax+ B)$$
And you can solve it, but it would be slightly non-rigorous because if either $P(x)$ or $Ax + B$ are not positive then it's not legal to take the $\log$.
So we do it rigorously: There is a non-empty open interval $I$ in which $Ax + B$ is positive. Over $I$, it's OK to take $\log(Ax+B)$. But then even over $I$, $f(x)$ can still be negative. To make $f(x)$ "loggable", multiply it by an appropriate power of $-1$ to make it positive. All of this gets us:
$$\frac{d}{dx}\log((-1)^CP(x)) = \frac 1 A \frac{d}{dx}\log(Ax + B), x \in I$$
Taking anti-derivatives and re-arranging gets us $$P(x) = (-1)^Ce^D(Ax+B)^{1/A}$$
This can be written as $$P(x) = \alpha (\beta x + \gamma)^n $$
for arbitrary $\alpha, \beta, \gamma \in\mathbb R$, where $\alpha, \beta \neq 0$.
A polynomial over $I$ generalises uniquely over $\mathbb R$, and has the above form.

Find $P$ such that $P' | P$


Panzer Corps, Stalingrad - a loss with victory conditions satisfied

Question: I'm playing Panzer Corps campaign. For Stalingrad, "marginal victory" condition is to capture all objectives except three cities in Caucasus. I captured all objectives except Baku (furthest to the south) and got loss. This seems to be a bug.
Maybe it has something to do with capturing some cities with Romanian units, but on strategic map they still show as mine (grey).
So, why?
Answer: This is a known bug in this scenario. However, in this case it does not matter. Whatever the result you always get send to Kursk after the battle, and you will always get 2880 prestige.
Source: Matrix games forums


Nuxt js - window or document is not defined

Question: I have seen many questions related to this topic. But none of them solved my problem.
I have a situation, where I've to check the innerWidth of the window, to check if the device is mobile or not using the isMobile variable.

      ...

Below is my script code. I'm checking process.client but it is coming as false. I don't know if I've missed something which I need to add somewhere (maybe nuxt.config.js).
    data() {
      return {
        isMobile: false,
      };
    },
    mounted() {
      if (process.client) {
        console.log("Hello from the client!");
        this.isMobile = window.innerWidth < 768;
      }
      console.log('process', process.client); // Logs as false
    },

Answer: There's nothing wrong with your code. It works as it should. Let me explain.
Do you see that text in the console Nuxt SSR? It means that the output below is the result of console.log executed on the server side, not in your client. If you look in your console a little bit below this Nuxt SSR block you should see another output - either process false or process true depending on your current width of the window.
Not convinced? Try to replace that code with this and I think you'll believe me.
created() {
  if (process.client) {
    console.log("Hello from the client!")
  }
  console.log("Hello from the server... and also the client!")
}

It should output this.

Maybe you'd like to replace the created() function with mounted() because created() is called on both the server side and client side. And mounted() is called only on the client side when that component/page gets mounted. So that you don't have to check if process.client is true on the server side. Which will always be false so it's unnecessary to do that check.
Comment: I have changed and checked under `mounted` as well, but I can't see any log from `Hello from client`


Cannot source .nanorc correctly: command "include" not found

Question: I'm trying to customize nano to my needs, I copied nanorc from the /etc directory in my home directory and haven't edited anything so far.
My goal is to enable syntax highlighting for config files such as .bashrc. Syntax highlighting already works when I assign an extension to files such as file.py but it doesn't work for config files which are usually full of comments and options unless I explicitly type nano configfile --syntax=sh. I would like this flag to be enabled by default.
When looking into the nanorc file I noticed the statement include /usr/share/nano/*.nanorc. When sourcing the file with source .nanorc I get the following error:
.nanorc:236: command not found: include

Why is this happening and how can I fix it? Thanks!
Comment: Because `.nanorc` files aren't shell scripts? they are meant to be read and parsed internally by `nano` itself - not by your shell
Comment: OK sounds like you should write an answer based on your findings!
Comment: @steeldriver they're simply text files. Anyway I fixed it! Your comment helped me understanding that since they're not shell scripts, nano uses the default syntax settings! So I edited /usr/share/nano/default.nanorc including the desired default syntax! Thanks! I don't know why, but I was assuming they were all shell scripts by default..
Comment: I did not know that.. but then how can I solve the problem I have?
Comment: Can you be more specific than "config files"? what kind of files are these? do they really have a Bourne shell-like syntax?
Comment: @steeldriver done!
Answer: I found a solution to the problem!
In order to perform syntax highlighting, nano uses a set of configuration files which located (in Ubuntu 16.04) in the directory /usr/share/nano. For example, you have a file related to syntax highlighting of shell scripts (sh.nanorc), Python scripts (python.nanorc), etc...
The syntax highlighting rules to be used is determined based on some pattern matching criteria specified in each file. Python files are matched based on the .py extension for instance.
When there is no match between the file characteristics (extension, interpreter line, etc...) nano uses the default file "default.nanorc".
This means that when you are opening a generic text file such as ~/.bashrc (for example) syntax highlighting is going to be performed using the regex rules contained in the file "default.nanorc". Just edit this file according to your required rules and then save it. Next time you open nano the changes are already stored and effective.
By the way, you can edit syntax highlighting for all other kind of files or the matching criteria between files and syntax highlighting rules by simply editing the corresponding *.nanorc file.
Comment: @wjandrea not really - they look like regular expression matches on the shebang and the ASCII string representation of the file magic respectively, but I'm just basing that on the contents of the /usr/share/nano/*.nanorc files. For example the `sh.nanorc` file has `header "^#!.*((ba|da|k|pdk)?sh[-0-9_]*|openrc-run|runscript)"` and `magic "(POSIX|Bourne.*) shell script text"`
Comment: It can use the file's header (such as `#!/bin/sh`) and *magic pattern* (as used by the `file` utility) as well as just the extension, I think
Comment: @steeldriver Do you know how to do that?
Comment: @steeldriver I added a shebang to my bashrc, now it's highlighted automatically!


Cannot boot into Linux, low graphics error, cannot boot into terminal

Question: The title is a little confusing but this is the problem. I deleted my Ubuntu partition and didn't bother to fix the bootloader so I enter the grub console when ever is boot my laptop up. I reinstall Ubuntu and it was successful. When I rebooted it, it goes into low graphics. I followed the directions on the low graphics but terminal would load. Right now I'm reinstalling Ubuntu but putting the bootloader (or whatever it's called) on the same partition as the OS. If this still doesn't work, can someone help me solve my boot into terminal problem?
Answer: Steps to install Ubuntu is really simple.
After you run the ubuntu installer:
Create a partition in the installation process and make it mount to /boot size maybe 1GB Another partition for the root / or as you like your schema to be.
If you have more than one hard drive (actual hard drive not partition) then you need to make sure that it is on the top of boot order from the BIOS setup, and make sure that it is the hard drive you chose to install the boot loader.
Another important point is: remove the CD/USB that you used to install ubuntu after the installation.
Comment: Uh, ive got installed fine but also I got the problem fixed too. Now my problem is that I cant boot into windows (I dual booted... obviously). Instead of the Ubuntu windows boot manger and all the other options, I get a black windows with the usual ubuntu purple as a border. I dont know if this is a graphics issue or what though. Any comments on this?
Comment: No this is not a graphic problem. You can not boot into windows is a different matter. Do you have UEFI boot or legacy?
Comment: UEFI boot I believe
Comment: If you have installed Ubuntu on legacy boot, then the only way to boot Windows is to switch back to UEFI. Ok try this: go to bios setup and switch to UEFI. and see if windows starts (if windows asks for recovery there will be a chance that windows will overwrite the boot sector which causes ubuntu to be not bootable). There are 2 ways to install ubuntu, the easy way in my opinion is to install ubuntu in legacy mode, and whenever you want to start windows you will have to switch back to UEFI. The other way is a long process of installing ubuntu in UEFI boot.


Installing a GFCI with wires from "line" to "line" instead of "line" to "load."

Question: I don't know the proper terms so please bear with me. But here's the scenario.
We have a second refrigerator in our garage. It plugs into a standard looking outlet. But it is wired from another outlet on the other side of the room that is a GFCI. So when that GFCI gets tripped (rarely happens) it cuts power to the fridge.
We had some work done by professional licensed electricians who had to turn off the main power to the circuit panel. This tripped our GFCI's and we had to reset them.
But before I assumed that this was the case I thought something more insidious happened. Not to get into a long story but we are having nightmare after nightmare scenarios with wires failing in the walls, etc. in our new home we recently moved to. That's why they were here, to address an entire second floor where we lost all power. We called them back thinking what they might have done caused the issue but on their way back I remembered to try hitting the GFCI in the garage and the power went back on to the fridge. The licensed electrician has seen me do some work around the house and trusts that I have an idea of what I can do.
When I told him that it was the GFCI he said that the fridge should not be connected in anyway to a GFCI because if we, for example, went on a long vacation and somehow the GFCI tripped we could come home to a very horrible rotting situation.
He told me to wire the GFCI in a "line to line" manner. In other words, I'm supposed to avoid carrying the romex to the fridge by using the "load" connections on the back of the GFCI outlet. At first I couldn't picture what he was saying because I didn't have an outlet in front me. But now that I bought a new one I can see that I can insert one set of Romex wires to the "line" on top and then insert another pair of wires on top just a quarter of an inch below or above the top connections.
So in other words, I leave the yellow tape over the connections that say "load" and just do what I explained above? I have never done this before so I thought I would ask for clarification. Also, I can't seem to find any info on this while doing internet searches.
I trust our electricians. They have been here at least three times fixing really horrible scenarios that are out of my league. And apparently, he trusts me to wire this GFCI but did I understand him correctly? I just wire the two wires and do a "line" to "line" connection and avoid the "load" connection?
Comment: Use caution with internet advice as it is commonly wrong. I agree that it is not a good idea to have a fridge on a GFCI but in a garage unless your state has an exception it is a code violation to remove the GFCI protection. We go to add them if not required as they cost more.
Comment: With the down votes and being the only licensed electrician I can tell you violating code because someone told you will do as much good in court as telling a police officer a friend that is a officer said that they wont pull you over for 8 over the posted limit.
Answer: Yes!  That's exactly what you do.

he said that the fridge should not be connected in anyway to a GFCI because if we, for example, went on a long vacation and somehow the GFCI tripped we could come home to a very horrible rotting situation.

Yes, or even worse, the GFCI trips, the temperature rises, bacteria run amok... and then someone resets the GFCI for some other reason and it never occurs to them that the fridge lost power.  So they do not warn the chef.  The chef finds cold food as expected.  No warning of failure.
They do make refrigerator alarms for that purpose. They monitor the fridge for loss of cold.

I can see that I can insert one set of Romex wires to the "line" on top and then insert another pair of wires on top just a quarter of an inch below or above the top connections.

Yes, the 2 little slots or holes that are directly under each screw.

I trust our electricians. They have been here at least three times fixing really horrible scenarios that are out of my league.

I rely on your claim there.  Your local people know your local Codes, amendments, AHJ practices and whether the circuit is grandfathered based on your facts.
I will say that GFCI protection is generally required in garages.  Local authorities (or local amendments) very commonly grant exceptions for refrigerators and freezers, but they want to see a receptacle set up that can only be used by the fridge, and is labeled as such.  E.G.
Comment: @EdBeal  It is not for me to second-guess a REAL electrician who **actually has boots on ground in the physical site, and is intimately familiar** with local adopted NEC version, local amendments, AHJ practices and grandfathering.  If *THAT* electrician says it's A-OK, I must rely on that.   How do you hold  yourself above that person?
Comment: Guess you don't follow the national electric code! NEC 120.8.A.2 "garages " require GFCI protection for all receptacles. So it would be a code violation even ceiling mounted receptacles are required to be GFCI protected.
Comment: @ Harper. Thanks for your very detailed answer. We had them install a separate outlet in the garage to power an in-wall air conditioner we also just recently installed which is now on it's own individual circuit at the electric panel. Before we did this we  had it plugged into the same outlet that the fridge was powered from and the GFCI kept tripping when it got really hot out. We strive to keep the garage at 90 degrees because higher ambient temperatures can significantly shorten the life of a fridge. It can reach as high as 122 in our area in the summer.
Answer: He may have had you wire it line -line because it would be something he could loose his license over if he did it.
Line to line is bypassing the GFCI for all the receptacles protected by this GFCI.
Garage receptacles require GFCI protection if under the NEC current code.
Some states have exemptions for dedicated circuits like one that only goes to the fridge or freezer.
Wiring the GFCI line to line in your case has the problem that the other receptacles on this circuit are not protected (if there is only the receptacle to the fridge it may be ok depending on jurisdiction)
It sounds like you are using back stabs, 15 amp circuit push in connectors. I don't like these and especially not on a Refridgeration circuit.
If back and side that uses a screw to secure the wires that would be better. Might try a line to line then a fridge if this was the only receptacle or if the others could be protected by another GFCI wired line load to protect the remaining receptacles.
Comment: I can't believe you got 2 DVs on this!  I thought it was code legal to replace GFCI breakers/outlets with ones that didn't have GFCI protection in situations where you got nuisance trips, esp. when on fridges and freezers.
Comment: Adrien, All receptacles outside require GFCI protection there are NO exceptions in a wet area. pools haves required GFCI protection prior to my apprenticeship in the 70's and yes if some e is injured because you removed a GFCI even if not required when built but installed later, replacement receptacles are required by code to meet code. I can not remove or bypass a GFCI because of legal lability, it sounds like you now have multiple code violations that could end in injury or death and believe me there are lawyers that will clean you out even from in-laws injuries I have seen it in the past.
Comment: @george Anderson in our jurisdictions it is legal in some inside cases but the Pacific Northwest has multiple exceptions to the NEC even though we are on the 2020 code version. There are many states there are no exceptions and the outside water timer not being protected is similar to a case I know of where a family took another family member to court and the home owner lost a sizable judgement I remember him being more upset because the insurance company lawyer stated it was a good thing the person died if disabled the judgment would have been 10x
Comment: *He wired a separate outlet that is no longer GFCI for the irrigation so I won't ever have this problem again.*  That is **DANGEROUS**. It is not only outside, so required by code to have GFCI, but it is a **WATER**-related receptacle. Water and electricity don't mix - at least not safely. The very fact that it used to trip is an indication that there was a danger that it was protecting you from - possibly saving your life.
Comment: I don't think it's something he's telling me to do because if he did it he would lose his license. We had him also do some rewiring for outdoor outlets near our pool equipment and outdoor kitchen area. Before he came along we had a GFCI outlet that I was using to plug an irrigation timer into. The GFCI was tripping now and then which resulted in me not knowing that the trees I planted this past winter weren't getting any water. Well, $500 of a waste later all of my trees are dead. He wired a separate outlet that is no longer GFCI for the irrigation so I won't ever have this problem again.
Comment: The outlet I was talking about for my irrigation is located inside a pool shed that is protected by the elements and is at least ten feet away from the pool. Again, I worked with a licensed electrician in my area. There were other things we talked about him doing that he would not do because they were not legally up to code. So I don't see how he would not know this.
Comment: All receptacles in out buildings are required to be GFCI protected there are no code exceptions unless your local AHJ has eliminated this section of code. I doubt it was exempted.  You made the statement that he told you to do it ,,, not that he did it , as all these comments show it is not legal for a receptacle in your pool house , garage, garden shed, barn or any other out building to not have GFCI protection.


Tools to profile performance of .NET Compact Framework applications

Question: The only thing I've found is EQATEC Profiler. Are there any other profilers out there that can be used to profile .NET CF apps?
Comment: It's the only CF profiler I'm aware of.
Answer: There's the built-in CLRProfiler: The CLRProfiler for the .NET Compact Framework (Version 3.5 of the .NET Framework): your question doesn't state which version you are targeting. It's part of the Power Toys for .NET Compact Framework 3.5.
There is also the .NET Compact Framework Remote Performance Monitor:

How to: Monitor Performance at Run Time

The .NET Compact Framework Remote
  Performance Monitor is an analysis
  tool that is included with the .NET
  Compact Framework version 2.0 Service
  Pack 1. This tool provides a user
  interface that lets you view
  performance data on the fly. When you
  start your application from Remote
  Performance Monitor, the tool will
  read statistical data for the .NET
  Compact Framework performance counters
  directly from the common language
  runtime (CLR).
You can also view .NET Compact
  Framework performance data by using
  the Windows desktop tool, PerfMon.exe.
  You can use these tools together for a
  live, graphical view of the
  performance counter data generated by
  the CLR.
Remote Performance Monitor enables you
  to do the following:

View performance counter data while an application is running.
View performance counter data in a graphical format in PerfMon.exe while
  an application is running.
Enable the generation of .stat files to duplicate behavior supported in
  earlier versions of the .NET Compact
  Framework. When you use this feature,
  any .stat file is written to disk when
  the application exits. For more
  information, see How to: Generate
  Performance Statistics.
View previously generated .stat files that were created in the .NET
  Compact Framework version 2.0.
Enable and disable logging.
Comment: CLRProfiler is focused more on memory issues then application performance.
Comment: There is a blog post series on using it here: http://blogs.msdn.com/stevenpr/archive/2008/05/08/the-clr-profiler-for-the-net-compact-framework-series-index.aspx
Comment: @Fredrik Mörk: that's what I linked to in my post, but thanks.
Comment: @Vadmyst: that's true. Memory bottlenecks are often a bigger concern on mobile devices.
Comment: @Mitch: my bad; I pointed at your link but misread it as pointing somewhere else. Should have clicked on it, I guess (being lazy is not a good thing, right?).
Answer: From my experiences of looking a while back the EQATEC profiler was the only "minimum effort" profiling option kicking around. It becomes more suitable for proper performance testing if you use the "clear snapshot" command after the code you're interested in has been JITed and if you use the mechanism of producing files you can parse them yourself to gain a: Min, Max, Average output.
Obviously that then becomes more effort than "minimum effort" though! :D
Comment: I just checked your page. I think you meant "gouge"? Here I thought everybody in the UK could spell better than everybody in the US :)
Comment: Oh my word, how terribly embarrassing. Thank you for the catch! :)
Answer: Try dotTrace from JetBrains. Here is the howto for CF applications profiling http://confluence.jetbrains.net/display/NetProf/How+to+profile+.NET+Compact+Framework+applications
Answer: Can you run it under a debugger? Can you manually interrupt (pause) it? If so, then this works.
ADDED: It works on multi-threaded apps if you can take stackshots of threads, and it works no matter how large the application is. (It appears to work better on larger apps because they tend to have more problems to find.)
Comment: Did you try that technique on large multi-threaded applications?
Comment: @Vadmyst: Yeah, that's answered above.
Comment: ... BTW, I tried to surf to your blog, and IE froze. I trust there's nothing mean on there?
Comment: @Mike Dunlavey: Nope, blog is just fine. My IE opens it without problems.
Comment: @Vadmyst: I guess my machine's getting old (like me).


Ubuntu 14.04 Stuck after login

Question: I installed Ubuntu 14.04 last night on my Lenovo X200, Dual Core 2.4GHz 3GB RAM and 250GB HDD. Everything was working fine, and this morning when I powered it up to double check everything, it was all good.
I came into work and all booted up fine.
However, when I tried to login (password protected user); only user on the computer - It logged in fine but was stuck straight away, with the blank screen (the background of the login screen) and just my cursor. Nothing else.
I left it for a few minutes thinking it was just being a little slow, but to no avail nothing happened. I have tried a reboot and nothing happened.
Comment: Providing more information will be helpful. Like the screen color you see and what did you last dp to the system during the previous boot. Your Graphics card. What graphics software did you install on your system. Using Xorg?
I believe I have experienced this before. What I did, if I didn't forget is to boot on Ubuntu safe mode and reconfigure some graphics settings or installed something.
Answer: Okay, I've managed to fix this myself. What I have done is to reinstall the ubuntu desktop.
sudo apt-get install --reinstall ubuntu-desktop

Then I rebooted the machine using sudo shutdown -r now. This worked perfectly.

Ubuntu 14.04 Stuck after login


clipping to bounds with UIViewContentModeScaleAspectFill

Question: is there any way of controlling where UIViewContentModeScaleAspectFill clips an image? In my case, images are always clipped around the center of the image. Is it possible to make it clip around the top?
Thanks!
Antonio
Answer: The current implementation of UIViewContentModeScaleAspectFill is indeed to center the image as you pointed out, to my knowledge there's no way of altering this behavior.


How to optimize multivariate functions in Python

Question: I have this dataframe:

where:
x: independent variable
y: independent variable
z: dependent variable

How do I find in Python the optimal "a" and "b" parameters , so that I optimize this function:
z = a*sin(x) + b*sin(y)

I know that the optimal solution is:
a = 0
b = 1

But what Python code should I use? I guess I should use scipy optimize, but I am only able to use it with one independent variable.
Comment: Could you share your dataframe? (e.g. by providing the output of `df.to_records()`)
Answer: You might want to consider sklearn:
Assuming your dataframe is called df, first thing you might want to do is create a variable X containing the sin-transform of x,y, e.g.
from math import sin

X = [[sin(x), sin(y)] for x, y in zip(df.x, df.y)]

and then a variable Z which is df.z.
Finally, you can just do a linear regression fit usingsklearn, e.g.
from sklearn.linear_model import LinearRegression

reg = LinearRegression().fit(X, Z)

Comment: aahh that's the bit I was missing ! thanks !


Tetris Rotation Issue

Question: I am making Tetris, and I'm having issues getting the rotations working for a group of blocks. My groups of blocks consist of 4 block sprites that are children to an empty gameobject.

I move/rotate the blocks by updating the position/rotation of the parent object's transform, validating that the new position is within the grid, and then updating the individual child blocks.
this.transform.position += new Vector3(1, 0);
if (IsValidGridPos())
    UpdateGrid();

this.transform.Rotate(0, 0, -90);
if (IsValidGridPos())
    UpdateGrid();

For each group, I have a center point where I want the group to move/rotate around. The image below shows where my center points are for each group.

This works as intended for most of the groups, except for the straight-line and square group. Because both groups center points are not in the middle of a child block, it throws off the blocks position inside the 2D array I use to hold all blocks positions.
Is there a better way to handle a group's movement/rotation?
Comment: You could/should just make the groups for the line and box smaller to fit their actual size? Or move them to center of the group?
Comment: Just as a side note. I could be wrong but the way I remember it is that cyan(line), green and red (s/z) shapes have only 2 positions/orientations. They didn't have 2 horizontal/vertical positions offset by 1.
Comment: your approach is correct and should work. Are you sure that you dont use a cast to int at the wrong place of something like that?. Note that the center position might not be on the grid, so its position cannot be cast to int
Comment: @Nikaas I believe you are right.
Comment: I'm going to debug the 2D array once I get out of work. I'll post another comment with what I find.
Answer: For Group I and O, their center points are located either in between it's child blocks or on the side of the blocks. This led to my spawning script to place the group's center point in the correct position but not their child blocks.
The positions for Group_I and it's children's positions.

To fix this issue, I created a new script that will move the Group's transform position 0.5 in the x and y axis as soon as the Group is created.
const float DISTANCE = 0.5f;
void Awake()
{
    // Moves the center point of a Group over so it's
    // child blocks can align correctly with the game grid.
    this.transform.position += new Vector3(DISTANCE, DISTANCE);
}

If anyone has a better solution, please feel free to let me know. Thanks to everyone who commented on my question.

Tetris Rotation Issue


errors because of int conversion placement

Question: i have narrowed it down so that the int conversion from jtextfield to int is the errors but am unsure where to put them
   package demooo;

/*
 * GridBagLayoutDemo.java requires no other files.
 */
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.text.DefaultCaret;

public class Demooo implements ActionListener {

    final static boolean shouldFill = true;
    final static boolean shouldWeightX = true;
    final static boolean RIGHT_TO_LEFT = false;
    private final static String newline = "\n";
    protected JTextField textField;
    protected JTextArea textArea;

    public static void addComponentsToPane(Container pane) {

        if (RIGHT_TO_LEFT) {

pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }

        /*test for team names */
        //String[] teamString = {};
        String[] reffString = {"bob", "fred", "jon", "ed", "killa"};
         JLabel label;
        JLabel labelA;
        JLabel labelH;
        JLabel labelA2;
        JLabel labelH2;
        JTextField text;
        int g = 0 ;
        JButton next;
        JButton button1;
        JButton button2;
        JLabel blank;
        JLabel Head;
        JComboBox comboH;
        JComboBox comboA;
        JComboBox comboReff;
        String winner;
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
       /* int h = Integer.parseInt(homegoal.getText());
        int a = Integer.parseInt(awaygoal.getText());
        int h2 = Integer.parseInt(homegoal2.getText());
        int a2 = Integer.parseInt(awaygoal2.getText());*/

        pane.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        if (shouldFill) {
            //natural height, maximum width
            c.fill = GridBagConstraints.HORIZONTAL;
        }
        /*select home team*/

        labelH = new JLabel("Home Team");
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        pane.add(labelH, c);

        comboH = new JComboBox(/*teamString*/);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1;
        c.gridx = 0;
        c.gridy = 1;
        pane.add(comboH, c);
        /* to add blank space between teams*/

 /*cant get right yet but will try */
 /*select away team*/
        labelA = new JLabel("Away Team");
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 7;
        c.gridy = 0;
        pane.add(labelA, c);

        comboA = new JComboBox(/*teamString*/);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1;
        c.gridx = 7;
        c.gridy = 1;
        pane.add(comboA, c);

        /*Team 1 home*/
        Head = new JLabel("Home Game Score", SwingConstants.CENTER);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 20;      //make this component tall
        c.weightx = 0.0;
        c.gridwidth = 3;
        c.gridx = 0;
        c.gridy = 3;
        pane.add(Head, c);
        Head.setFont(new Font("Serif", Font.BOLD, 18));

        /*enter score for home game*/
        labelH2 = new JLabel("Home Team Goals");
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 4;
        pane.add(labelH2, c);

        JTextField homegoal = new JTextField(2);
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 5;
        pane.add(homegoal, c);
int h = Integer.parseInt(homegoal.getText());
        /*ref section*/
        label = new JLabel("Referee");
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 4;
        pane.add(label, c);

        comboReff = new JComboBox(reffString);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1;
        c.gridx = 3;
        c.gridy = 5;
        pane.add(comboReff, c);

        /*other teams goals*/
        label = new JLabel("Away Team Goals");
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 7;
        c.gridy = 4;
        pane.add(label, c);

        JTextField awaygoal = new JTextField(2);
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 7;
        c.gridy = 5;
        pane.add(awaygoal, c);
        int a = Integer.parseInt(awaygoal.getText());

        /*team 2 is home team*/
        Head = new JLabel("Away Game Score", SwingConstants.CENTER);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 20;      //make this component tall
        c.weightx = 0.0;
        c.gridwidth = 3;
        c.gridx = 0;
        c.gridy = 6;
        pane.add(Head, c);
        Head.setFont(new Font("Serif", Font.BOLD, 18));

        label = new JLabel("Home Team Goals");
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 8;
        pane.add(label, c);

        JTextField homegoal2 = new JTextField(2);
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 9;
        pane.add(homegoal2, c);
        int h2 = Integer.parseInt(homegoal2.getText());
        /*reff */
        label = new JLabel("Referee");
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 8;
        pane.add(label, c);

        comboReff = new JComboBox(reffString);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1;
        c.gridx = 3;
        c.gridy = 9;
        pane.add(comboReff, c);

        /*next teams goals*/
        label = new JLabel("Away Team Goals");
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 7;
        c.gridy = 8;
        pane.add(label, c);

        JTextField awaygoal2 = new JTextField(2);
        if (shouldWeightX) {
            c.weightx = 0.5;
        }
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 7;
        c.gridy = 9;
        pane.add(awaygoal2, c);

        int a2 = Integer.parseInt(awaygoal2.getText());

        /*match set complete*/
         button1 = new JButton("The winner of this set of matches was");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 20;      //make this component tall
        c.weightx = 2;
        c.gridwidth = 8;
        c.gridx = 0;
        c.gridy = 10;
        pane.add(button1, c);
        button1.addActionListener(new ActionListener() {

                        public void actionPerformed(int g) {
                        if (h>a){
                        g =+1;
                        }else if (a>h){
                        g =-1;}
                        else{
                        g = g;}
                        }

            @Override
            public void actionPerformed(ActionEvent ae) {
                throw new UnsupportedOperationException("Not supported
yet."); //To change body of generated methods, choose Tools | Templates.
            }
        });

        if (g > 0){
        winner = "home";
        }
        else if (g < 0){
        winner = "away";}
        else {
        winner = "Draw";}

        label = new JLabel (winner);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 20;      //make this component tall
        c.weightx = 2;
        c.gridwidth = 8;
        c.gridx = 0;
        c.gridy = 11;
        pane.add(label, c);

        button2 = new JButton ("Next Match");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 20;      //make this component tall
        c.weightx = 2;
        c.gridwidth = 8;
        c.gridx = 0;
        c.gridy = 12;
        pane.add(button2, c);

        try {
            con = DriverManager.getConnection("jdbc:derby://localhost:1527/"
+ "jfl", "jfl", "jfl");
            st = con.createStatement();
            String s = "SELECT Teamname,ID from JFL.TEAMS";

            rs = st.executeQuery(s);
            while (rs.next()) {
                comboH.addItem(rs.getString(1) + "  " + rs.getString(2));
                comboA.addItem(rs.getString(1) + "  " + rs.getString(2));
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "ERROR");
        } finally {
            try {
                st.close();
                rs.close();
                con.close();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "ERROR CLOSE");
            }
        }
    }

    /**
     * Create the GUI and show it.
     *
     * @param evt
     */
    public void actionPerformedd(ActionEvent evt) {

        String text = textField.getText();
        textArea.append(text + newline);
        textField.selectAll();

        //Make sure the new text is visible, even if there
        //was a selection in the text area.
        textArea.setCaretPosition(textArea.getDocument().getLength());
    }

    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Junior Football League");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JMenuBar menubar = new JMenuBar();
        frame.setJMenuBar(menubar);

        //file menu
        JMenu fileMenu = new JMenu("File");
        menubar.add(fileMenu);

        JMenuItem quitItem = new JMenuItem("Quit");
        fileMenu.add(quitItem);
        quitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //call another method to close window
                System.exit(0);
            }
        });
        JMenu helpItem = new JMenu("Teams");
        menubar.add(helpItem);

        JMenuItem subMenu = new JMenuItem("Create New Team");

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

the error message given is
run:

Exception in thread "AWT-EventQueue-0"
  java.lang.NumberFormatException: For input string: ""     at
  java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)     at
  java.lang.Integer.parseInt(Integer.java:615)  at
  demooo.Demooo.addComponentsToPane(Demooo.java:127)    at
  demooo.Demooo.createAndShowGUI(Demooo.java:918)   at
  demooo.Demooo.access$000(Demooo.java:12)  at
  demooo.Demooo$6.run(Demooo.java:936)  at
  java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)     at
  java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)    at
  java.awt.EventQueue.access$500(EventQueue.java:97)    at
  java.awt.EventQueue$3.run(EventQueue.java:709)    at
  java.awt.EventQueue$3.run(EventQueue.java:703)    at
  java.security.AccessController.doPrivileged(Native Method)    at
  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)   at
  java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at
  java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at
  java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at
  java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at
  java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
  BUILD SUCCESSFUL (total time: 1 second)
Comment: You say you narrowed it down, but that looks like you just dumped your entire code in here. Please create a proper [mcve] or at least reduce it to only the code where the error occurs, this is way too much
Comment: You can't parse the integer if there's nothing to parse... Looks like you need to check if the String is empty before attempting to parse it (based off the error message).
Comment: What is on line # **127** in your `Demooo.java`?
Comment: c.gridx = 0; so nothing to to with anything, just a placement for a label
Answer: You have this at line 127.
int h = Integer.parseInt(homegoal.getText());

The following lines from the exception tell me that the error is at that line and it is regarding conversion form String to Int.
java.lang.Integer.parseInt(Integer.java:592) at
java.lang.Integer.parseInt(Integer.java:615) at
demooo.Demooo.addComponentsToPane(Demooo.java:127) at

I would take a look at what value is coming through for homegoal.getText(). If it is null then put 0 in the int variable.
Edit: From the looks of it, you are just creating the text field so it will be empty. That's why the error. Check to see if empty and assign 0 on empty.
int h = (homegoal == null || homegoal.getText().isEmpty()? 0:Integer.parseInt(homegoal.getText());


how to automaticly validate a web form?

Question: I found this code on stackoverflow, code of https://stackoverflow.com/users/370876/peter-anselmo
<code>$url = 'http://www.targeturl.com';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );
</code>
I want to fill two fields, one line is ok or two are needed (with curl)
and how can I make like an "if" to test if the url returned is what I want or no and re-try again (like a loop).
I know I ask
Answer: Not really sure what you mean by your question, I'm sort of confused, but are you asking for something like this?
<code>$foundURL = FALSE;
while(!$foundURL)
{
     // Make CURL request
     $response = curl_exec($ch);
     if ($respons == "the url I want") $foundURL = TRUE;
     // Load next http/url for curl request...
}
</code>
This loop will continue to execute and make CURL requests until the response matches some URL that you're searching for ...

how to automaticly validate a web form?


How to listen the page beforeunload or unload event in android webview by JavaScript

Question: I use a WebView to load my page below:

first page

this page has worked well in Chrome or other PC-browser。
Here is the code in activity:
public class MainActivity extends AppCompatActivity {
    WebView web;
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        web = findViewById(R.id.web);
        web.setWebContentsDebuggingEnabled(true);
        WebSettings webSettings = web.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);

        web.loadUrl("http://192.168.0.103:5000/WebContent/");

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        Log.i("SSSS","acitvity destroyed");
        super.onDestroy();
        ConstraintLayout layout = this.findViewById(R.id.rootView);
        layout.removeView(web);
        web.destroy();
        web = null;
    }

}

when leave the activity that contains WebView ,I cannot catch any logs about page unload event,is anything wrong?
Answer: I didn't test this but based on the documentation you need to override WebChromeClient::onConsoleMessage and use WebView::setWebChromeClient.
Comment: It doesn't matter. Overriding WebChromeClient::onConsoleMessage  just makes the console log look like the app native log
Answer: This is because you are removing view and Webview in onDestroy
@Override
    protected void onDestroy() {
        Log.i("SSSS","acitvity destroyed");
        super.onDestroy();
        ConstraintLayout layout = this.findViewById(R.id.rootView);
        layout.removeView(web);   <----- This linse
        web.destroy(); <------ Forcing webview to destroy and next explicitly set null
        web = null;
    }

Comment: I tried what you said,still couldn't catch the page unload event. I remove and destroy the Webview because of the Webview still running in the background even though the activity already has been destroyed.
I cannot wait for GC.


Unintended Recursivity - How do I stop or reset a function on click?

Question: I tried making a jsFiddle for this, but it's not working right (I think because of the alerts I have set up to test my code), so hopefully someone can simply look at my JS and see the problem.
The issue is that when you close the div with the form (#verizoni516) and then re-open it, you get as many alerts as times you have closed the div and re-opened it, instead of the ONE alert I'm intending. Does that make any sense?
Here's the JS:
/*--------------Validation Functions-------------------*/
    function chkradio() {
        var elem = document.forms['vzi5'].elements['element_0'];
            len = elem.length - 1;
            chkvalue = '';
            sevenPlus = false;
            fourToSix = false;
            threeMin = false;
        for (i = 0; i <= len; i++) {
            if(elem[i].checked) chkvalue = elem[i].value;
        }
        if (chkvalue == '') {
            $('#radio-error').fadeIn('fast').effect("bounce", {times:3}, 'fast', function(){
                setTimeout(function(){
                    $('#radio-error').fadeOut('slow');}, 2000);
            });
        }
        if (chkvalue >= 7) {
            sevenPlus = true;
        } else if (chkvalue >= 4 && chkvalue <= 6) {
            fourToSix = true;
        } else {
            threeMin = true;
        }
    };
    function chkselect() {
        var elem = document.forms['vzi5'].elements['element_1'];
            len = elem.length - 1;
            chkvalue = '';
            likeNew = false;
            minProb = false;
            nonFunc = false;
        for (i = 0; i <= len; i++) {
            if (elem[i].selected) chkvalue = elem[i].value;
        }
        if (chkvalue == '') {
            elem.focus();
            $('#select-error').fadeIn('fast').effect("bounce", {times:3}, 'fast', function(){
                setTimeout(function(){
                    $('#select-error').fadeOut('slow');}, 2000);
            });
        } else if (chkvalue === 'Like New - No Functional Problems') {
            likeNew = true;
        } else if (chkvalue === 'Minor Functional Problems') {
            minProb = true;
        } else {
            nonFunc = true;
        }
    };
    function chkbox() {
        var elem = document.forms['vzi5'].elements['element_2[]'];
            chkvalue = elem.checked;
            iUnderstand = true;
        if (chkvalue === true) {
            iUnderstand;
        } else {
            iUnderstand = false;
            elem.focus();
            $('#check-error').fadeIn('fast').effect("bounce", {times:3}, 'fast', function(){
            setTimeout(function(){
                $('#check-error').fadeOut('slow');}, 2000);
        });
        }
    };
//Calling the validation functions---------------------------
$('#verizon img.apple, #unlocked img.apple').click(function(){
    $(this).closest('div').fadeOut(500).animate({"top": "-414px"}, 100).fadeIn('fast', function(){
    });
        $('#verizon516').animate({"top": "+=557px"}, 500, function(){
            $(this).animate({"top": "-=20px"}, 200);
        });
    $('div.next').click(function(){
        chkradio();
        chkselect();
        chkbox();
        if (sevenPlus === true) {
            if (likeNew === true && iUnderstand === true) {
                alert('Condition is 7+ and functions like new.');
            } else if (minProb === true && iUnderstand === true) {
                alert('Condition is 7+ and has minor functional problems');
            } else if (nonFunc === true && iUnderstand === true) {
                alert('Condition is 7+ and device does NOT function.');
            } else {

            };
        };
        if (fourToSix === true) {
            if (likeNew === true && iUnderstand === true) {
                alert('Condition is 4-6 and functions like new.');
            } else if (minProb === true && iUnderstand === true) {
                alert('Condition is 4-6 and has minor functional problems');
            } else if (nonFunc === true && iUnderstand === true) {
                alert('Condition is 4-6 and device does NOT function.');
            } else {

            };
        };
        if (threeMin === true) {
            if (likeNew === true && iUnderstand === true) {
                alert('Condition is 1-3 and functions like new.');
            } else if (minProb === true && iUnderstand === true) {
                alert('Condition is 1-3 and has minor functional problems');
            } else if (nonFunc === true && iUnderstand === true) {
                alert('Condition is 1-3 and device does NOT function.');
            } else {

            };
        };
    });
});

Comment: By the way, I had "return;" in each of those currently empty else statements, and having that or not having it doesn't seem to make any difference.
Answer: Move the div.next click handler out of the other click handler, it will cause a new handler to get registered every time you click on one of the #verizon img.apple, #unlocked img.apple elements which intern gets called one after another.
/*--------------Validation Functions-------------------*/

function chkradio() {
    var elem = document.forms['vzi5'].elements['element_0'];
    len = elem.length - 1;
    chkvalue = '';
    sevenPlus = false;
    fourToSix = false;
    threeMin = false;
    for (i = 0; i <= len; i++) {
        if (elem[i].checked) chkvalue = elem[i].value;
    }
    if (chkvalue == '') {
        $('#radio-error').fadeIn('fast').effect("bounce", {
            times: 3
        }, 'fast', function () {
            setTimeout(function () {
                $('#radio-error').fadeOut('slow');
            }, 2000);
        });
    }
    if (chkvalue >= 7) {
        sevenPlus = true;
    } else if (chkvalue >= 4 && chkvalue <= 6) {
        fourToSix = true;
    } else {
        threeMin = true;
    }
};

function chkselect() {
    var elem = document.forms['vzi5'].elements['element_1'];
    len = elem.length - 1;
    chkvalue = '';
    likeNew = false;
    minProb = false;
    nonFunc = false;
    for (i = 0; i <= len; i++) {
        if (elem[i].selected) chkvalue = elem[i].value;
    }
    if (chkvalue == '') {
        elem.focus();
        $('#select-error').fadeIn('fast').effect("bounce", {
            times: 3
        }, 'fast', function () {
            setTimeout(function () {
                $('#select-error').fadeOut('slow');
            }, 2000);
        });
    } else if (chkvalue === 'Like New - No Functional Problems') {
        likeNew = true;
    } else if (chkvalue === 'Minor Functional Problems') {
        minProb = true;
    } else {
        nonFunc = true;
    }
};

function chkbox() {
    var elem = document.forms['vzi5'].elements['element_2[]'];
    chkvalue = elem.checked;
    iUnderstand = true;
    if (chkvalue === true) {
        iUnderstand;
    } else {
        iUnderstand = false;
        elem.focus();
        $('#check-error').fadeIn('fast').effect("bounce", {
            times: 3
        }, 'fast', function () {
            setTimeout(function () {
                $('#check-error').fadeOut('slow');
            }, 2000);
        });
    }
};
//Calling the validation functions---------------------------
$('#verizon img.apple, #unlocked img.apple').click(function () {
    $(this).closest('div').fadeOut(500).animate({
        "top": "-414px"
    }, 100).fadeIn('fast', function () {});
    $('#verizon516').animate({
        "top": "+=557px"
    }, 500, function () {
        $(this).animate({
            "top": "-=20px"
        }, 200);
    });
});
//move this out of the other click handler
$('div.next').click(function () {
    chkradio();
    chkselect();
    chkbox();
    if (sevenPlus === true) {
        if (likeNew === true && iUnderstand === true) {
            alert('Condition is 7+ and functions like new.');
        } else if (minProb === true && iUnderstand === true) {
            alert('Condition is 7+ and has minor functional problems');
        } else if (nonFunc === true && iUnderstand === true) {
            alert('Condition is 7+ and device does NOT function.');
        } else {

        };
    };
    if (fourToSix === true) {
        if (likeNew === true && iUnderstand === true) {
            alert('Condition is 4-6 and functions like new.');
        } else if (minProb === true && iUnderstand === true) {
            alert('Condition is 4-6 and has minor functional problems');
        } else if (nonFunc === true && iUnderstand === true) {
            alert('Condition is 4-6 and device does NOT function.');
        } else {

        };
    };
    if (threeMin === true) {
        if (likeNew === true && iUnderstand === true) {
            alert('Condition is 1-3 and functions like new.');
        } else if (minProb === true && iUnderstand === true) {
            alert('Condition is 1-3 and has minor functional problems');
        } else if (nonFunc === true && iUnderstand === true) {
            alert('Condition is 1-3 and device does NOT function.');
        } else {

        };
    };
});

Demo: Fiddle
Comment: Thanks a ton! I probably should have seen that despite the fact that I'm a newbie. Additionally, I was wondering what, if anything, I should do about those empty else statements? I've never seen it in anyone else's code . . .
Comment: much obliged. It looked wrong to me to end that statement with an } else if {, but it certainly works. Thanks!
Comment: @user3127799 read the docs.. you can find details info in the mdn blogs about most of these things like https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Statements and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
Answer: This is because you are binding the click event for div.next inside the click event for #verizon img.apple, #unlocked img.apple, so every time the outer event is clicked, you are re-binding the inner click event. Fix this by moving the event binding for div.next outside the click event for #verizon img.apple, #unlocked img.apple
$('#verizon img.apple, #unlocked img.apple').click(function(){
    // .. contents here
});
$('div.next').click(function(){
    // ... contents here
});

Comment: Thank you!I'm so glad it was something easy :)
Answer: You are binding the click event to $('div.next') every time $('#verizon img.apple, #unlocked img.apple') is clicked. Which means it will fire once for each time it is bound. Move the code for $('div.next') out of the $('#verizon img.apple, #unlocked img.apple') click handler.


What are the best practices for a low deck built half on a concrete slab?

Question: In our current place, we moved the main access door from going into the kitchen, to entering an old laundry room converted to a mud room.  In order to do so, the front door was moved over about 4', and off the existing concrete patio.  The bottom of the door sill is ~11 1/2" above the existing slab, and ~12" above grade.  You can see a plan view of the existing concrete patio and proposed deck below.

The plan is to make a 10'x12' deck.  Why so big for an entry way?  Well, it is next to the kitchen, and it would be a great spot to grill.  Also, I plan on building a bench or two on the deck for kids to take off shoes, boots, etc.. before entering the house.
Since the deck is so low to the ground, I plan on building it directly on the slab, and having it free-standing (i.e.- not connected to the house, thus no ledger board).  By "directly on the slab" I mean to also shim it up, say, 1/2" to allow for circulation and water flow.  I plan on using 12' 2x8 joists, spaced at 12".  First question- does this all seem like a sane idea?
For my second question- obviously this deck will hang over an area where there is no concrete slab.  Would it be enough to place an 8" diameter, 4'deep footer at the two outside corners and in the middle of the 12' span, one joist in from the outside, at the same level as the slab?  (see dotted circles in the drawing).
Any other thoughts?  Am I out of my mind?
Comment: Out of curiosity what software have you used to draw your plan ?
Comment: @DrDro- I used Adobe Illustrator to draw the plan (not a cheap option, but one I happen to have for business purposes)
Answer: I thought this would be a fun thing to do (and perhaps set a precedent on diy.stackexchange.com)- post a picture with the results of my question.
Thanks to the tips here on this question, as well as another I asked, I have completed my deck project.  I ended up with what was described above- a ground-level deck, mostly on the slab.  I took Shirlock's advice, and went with an 8" deck block at the two corners not on the slab.  I compacted the earth a bit with a hand compactor.  Since the deck is not attached to the house, if there is some heave, it wont do any damage, and I can always dig some concrete holes under those two corners next spring if it turns out I need them.  So, without further adieu, the finished deck (yes I realize we have some funky siding..  spring 2011 project ;) ):
Comment: Awesome job!  I especially like the mitered edge banding -- it really makes for a professional-looking job!  Thanks for posting this and I agree it sets a great precedent.
Comment: Thanks Mike!  I thought that edging the deck would finish it off a bit better than just running the planks to the edge.  In the spring we'll stain/seal it and probably put a railing on the two outside edges, and I'm thinking of building in a bench along the side furthest back in the picture.
Comment: +1 Nice job!  And I like the idea of adding after-pictures, I've got one of my own.
Comment: Great job. love the picture frame detail around the edges.  Need a job? LOL  I agree, a nice seat would be an awesome detail, both functional and attractive. You also may consider putting a shallow french drain or band of crushed stone around the parimeter to keep water away from that nice looking wood. Congrats on a fine looking deck.
Comment: Thanks Shirlock.  The step you see in front, goes all the way to the slab to give it a finished look (and that entire step is over the concrete slab).  The raised portion of the deck behind, is actually on posts, raised about 2" off the slab/ground (so other than at the base of the posts, it isn't touching the ground).  We plan on putting nice plants/mulch around the whole thing in the spring.
Comment: This great and I want to do something very similar. Did you ever put the rails up?
Comment: We haven't yet- as the deck is only about 6-8" above grade, there isn't a safety issue, and while it would look nice, has not yet become a priority.
Answer: You didn't say where you are located, but i figured in a cold area like me in Maine.  First of all, 12 inch joist spacing a a waste of time and money.  16 inches will be fine especially if you plan to use 5/4 decking of any type. If you are in a non ground freeze area, just use simple blocking to support the additional 4 foot off the concrete.  Assuming you are in the frozen north, consider using 3 foot porch posts.  they are pre-poured concrete pyramids with a threaded insert dead center on the top. Often easier that sonotubes and mixing concrete. If your existing slab is not underfooted with a frost wall, and has not heaved or cracked over the years, then most likely a simple 8 inch concrete block in the ground the same depth or slightly deeper than the slab will probably do just fine. Remember you are only supporting 2 foot of deck (2 ft supported by slab and 2 ft supported my new foundation) and the decking itself will be spanning 8 to 12 feet onto the existing slab.  Over kill is fine, always safe, but not always a good use of time and money.  Also if you new deck is 12 inches off the ground, please consider some safe egress  steps and side barriers.  The rise of the step should not exceed 8 1/2 inches. A 12 inch step down can be a hazard, especially at night and for younger and older folks. Check your local code or the new IRC  guide lines.


javascript fusion charts not appearing in the new window

Question: I have a web page where fusion chart is rendered, my requirement is to bring this chart to a new window and send it for print.
function that I am using for bring the new window is
 function printBtn(){
    var prtContent1 = document.getElementById("chartdiv");
    var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');

    WinPrint.document.write(prtContent1.innerHTML);

    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
    }

I picked one html file from the FusionChart XT folder and put a 'print' btn.
In the local m/c its works as expected. But when I put the same code and set of js/swf files in the server, the chart in the new page looks like this..

As you can see..only the labels appear and the chart is not seen.
What could I be missing here. Our application is hosted on IBM Websphere App Server. Am bringing javascript charts using FusionChart XT.
Thanks.
Answer: The code you are using to replicate the chart is not a standard method to copy SVG or VML. A number of things will not be copied to the WinPrint window by using innerHTML method. Instead try this:

Load fusioncharts.js in the new window
Then recreate the chart on that window by cloning it from source.


Why did my miner stop working?

Question: It is named "Miner". Other than that I'm not sure if its a IC2, BC3 or some other miner.
My Miner has hit bedrock, and will not retract. Why? I have removed the remaining pipes from the Miner unit and replaced the pipes with cobblestone.
Answer: You have to also remove the Drill Unit or else the Miner will not start to retract.

Why did my miner stop working?


What is the file "fred.9113"?

Question: <code>execve("/usr/sbin/named", ["named", "-t", "/var/lib/named/etc/bind/", "-u", "bind", "-f", "-g", "-d", "9", "-E"], ["TERM=xterm", "LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio="..., "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "LANG=ru_RU.UTF-8", "HOME=/home/michael", "DISPLAY=localhost:10.0", "SHELL=/bin/bash", "LOGNAME=root", "USER=root", "USERNAME=root", "MAIL=/var/mail/root", "SUDO_COMMAND=/usr/bin/strace -o fred -ff -v -s 512 named -t /var/lib/named/etc/bind/ -u bind -f -g -d 9 -E", "SUDO_USER=michael", "SUDO_UID=1000", "SUDO_GID=1000"]) = 0
brk(0)                                  = 0x21873000
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb77f1000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat64(3, {st_dev=makedev(8, 3), st_ino=84, st_mode=S_IFREG|0644, st_nlink=1, st_uid=0, st_gid=0, st_blksize=4096, st_blocks=48, st_size=22937, st_atime=2016/07/24-20:24:11, st_mtime=2016/07/24-20:24:11, st_ctime=2016/07/24-20:24:11}) = 0
mmap2(NULL, 22937, PROT_READ, MAP_PRIVATE, 3, 0) = 0xb77eb000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/usr/lib/liblwres.so.80", O_RDONLY|O_CLOEXEC) = 3
@
@
@
@
@
@
@
@
@
@
@
@
@
@
</code>
Answer: It contains the output of the command
<code>/usr/bin/strace -o fred -ff -v -s 512 named -t /var/lib/named/etc/bind/ -u bind -f -g -d 9 -E
</code>
for the process with PID 9113
Comment: Where did you get the strace log in your question? The first line shows that user `michael` run that command using `sudo`, most likely when he was logged in via ssh.
Comment: Thanks. I didn't run strace. What's happened? Who can do it? I found this file in my home directory.

What is the file "fred.9113"?


How to execute the further code only after the successful JSON response?

Question: I am very beginner in swift and I am trying to fetch some JSON Data from an api and then creating an array from that Data.
Alamofire.request(.GET, URL)
    .responseJSON
    {
        response in
        let JSON = response.result.value
        let response = JSON as! NSDictionary
        let Data = response.objectForKey("data")!
        for slot in timeSlot as! NSDictionary
        {
            let json = slot.value
            let availability = json as! NSDictionary
            let myavailable = availability.objectForKey("available")!
            let slotTime = availability.objectForKey("time")!
            if (myavailable as! NSNumber == 1)
            {
                self.fetchSlot.append(slotTime as! String)
            }
        }
        for x in self.mySlot
        {
            for c in self.fetchSlot
            {
                if (c == x)
                {
                    self.availableSlot.append(x)
                }
            }
        }
    }

Now I am trying to print the "self.availableslot" in the same viewDid load function.
But it always returning an empty array, because it is compiling before all the JSON data is fetched.
Please if there is any way how can I use reload method or completion handler kind of things to get my job done.
Answer: func performAlamoFireRequest(completion: () -> Void) {
    Alamofire.request(.GET, URL).responseJSON {
        response in

        let JSON = response.result.value
        let response = JSON as! NSDictionary
        let Data = response.objectForKey("data")!

        for slot in timeSlot as! NSDictionary {
            let json = slot.value
            let availability = json as! NSDictionary
            let myavailable = availability.objectForKey("available")!
            let slotTime = availability.objectForKey("time")!
            if (myavailable as! NSNumber == 1) {
                self.fetchSlot.append(slotTime as! String)
            }
        }

        for x in self.mySlot {

            for c in self.fetchSlot {
                if (c == x) {
                    self.availableSlot.append(x)
                }
            }
        }
        completion()
    }
}

performAlamoFireRequest() {
//code to perform after here
}

Comment: How to call performAlamoFireRequest function in viewDidLoad ?
Comment: Call it whenever you had your code written originally before I stuck it in a function of it's own.
Comment: It is asking me to pass parameters.
I wanted to call performAlamoFireRequest function in my viewDidLoad only.
Comment: override func viewDidLoad() {
        super.viewDidLoad()
        performAlamoFireRequest()

        }
Comment: Then pass whatever variables you need to pass into the function... Just make sure to keep completion: () -> Void as a parameter.


I have to write a function that has two arguments(two lists of numbers, and returns its inner product), without using list comprehension, any ideas?

Question: def inner_product(vec1,vec2):
    if len(vec1)==len(vec2) and len(vec1)!=0:
        return sum([vec1[n]*vec2[n] for n in range(len(vec1))])
    else:
        return 0

Is the code that I built contain using list comprehension? if yes what can I do instead of this?
Comment: Yes, it's List Comp in the current *form*.  You can change to - 1) for-loop; or 2) generator expression by removing the ```[``` and ```]``` square bracket.
Comment: Yes `[vec1[n]*vec2[n] for n in range(len(vec1))]` is a list comprehension. Just convert it in an explicit `for` loop
Comment: It's weird task though, maybe you need to use functional approach instead: `sum(map(mul, vec1, vec2))`. Imports: [`mul()`](https://docs.python.org/3/library/operator.html#operator.mul).
Answer: Yes.
Without list comprehension, it would be something like below.
def inner_product(vec1,vec2):
    if len(vec1)==len(vec2) and len(vec1)!=0:
        temp=[]
        for n in range(len(vec1)):
            temp.append(vec1[n]*vec2[n])
        return sum(temp)
    else:
        return 0

Comment: How about `temp = 0` and `temp += vec1[n] * vec2[n]`?
Answer: A basic for-loop approach.
def inner_product(vec1, vec2):
    result = 0
    if len(vec1) == len(vec2) and len(vec1) != 0:
        for i in range(len(vec1)):
            result += vec1[i] * vec2[i]
    return result

print(inner_product([1, 2, 3], [4, 5, 6]))
#32
print(inner_product([1, 2, 3], [4, 5, 6, 5555]))
#0

Notice that your current implementation returns 0 if the vectors have different length... but careful that a inner product return zero if and only if the two vectors are orthogonal to each other (assumed both vectors non zero)... and this geometrical result will fail. Raising an exception would be a good choice to fix it: raise Exception("Error, vectors non comparable")


In Skyrim, if Shadowmere (or ally) kills an enemy do I get points?

Question:
Possible Duplicate:
How is Experience handled with Companions?

Playing Skyrim, I just received the semi-invincible horse, Shadowmere from the Brotherhood of Assassins. He automatically attacks enemies, but does he collect XP for me, or do I need to get the final kill to get the XP? Same for summoning allies lie the familiar or the spectral assassin -- do they collect XP for me?
Comment: Yeah, pretty much the same question -- didn't spot that. Sorry for duplicate.
Answer: There is no experience for kills in Skyrim, only for using your various abilities. For instance, if you hit an enemy with a fireball, your Destruction skill will increase slightly.
Shadowmere and other followers can reduce the amount of experience you get because you may be using your abilities less. But no, the killing blow is not any more special than any other blow when it comes to awarding 'experience'; each blow awards experience individually.
Comment: It is worth noting that sometimes the death blow _can_ have a bonus effect. For example the Enchanting perk, Soul Squeezer reads  "Death blows to creatures, but not people, trap 5% of the victim's soul, recharging the weapon."


jQuery don't find any loaded elements after jQuery.load()

Question: jQuery don't find any loaded elements after jQuery.load()
function makeEditForTextBox(textbox,editor) {
    editor.load("templates/textbox-edit.html");
    editor.find("#edit-save").click(function(event) { //here jQuery can't find #edit-save button
       id=editor.find("#edit-id-name").text();
       alert(id);
       textbox.find("input").attr("id",id);
       textbox.find("input").attr("name",id);
       textbox.find("input").attr("placeholder",editor.find("#edit-placeholder").text());
       textbox.find("label").text(editor.find("#edit-label-text"));
       alert("save clicked");
   });
   alert("loaded");
}

textbox-edit.html:
ID/Name
<input type="text" id="edit-id-name">
Label Text
<input type="text" id="edit-label-text">
Placeholder
<input type="text" id="edit-placeholder">
Help Text
<input type="text" id="edit-help-text">
<button id="edit-save">Save</button>
<button id="edit-cancel">Cancel</button>

I have loaded elements in browser, but jQuery can't find them.
Comment: You could use `load()` callback or better in your case, delegate click event  http://learn.jquery.com/events/event-delegation/
Answer: find() is running immediately after load() starts, not when load() finishes. You can put that code in the callback so that it's executed when load has completed.
http://api.jquery.com/load/

.load( url [, data ] [, complete ] )

function makeEditForTextBox(textbox,editor) {
    editor.load("templates/textbox-edit.html", function(){
        editor.find("#edit-save").click(function(event) {
           id=editor.find("#edit-id-name").text();
           alert(id);
           textbox.find("input").attr("id",id);
           textbox.find("input").attr("name",id);
           textbox.find("input").attr("placeholder",editor.find("#edit-placeholder").text());
           textbox.find("label").text(editor.find("#edit-label-text"));
           alert("save clicked");
       });
    });
}


What happen when two threads handled by two processors,trying to access single resource in heap at the same time?

Question: What happen when two separate threads handled by two processors, access same property in heap same time.It makes error or not?
Comment: https://stackoverflow.com/questions/56554603/what-happen-when-two-or-more-thread-trying-access-single-resource
Comment: Have you tried it? What happens?
Answer: It all happens down at the microelectronics level. Essentially the cache subsystems in the two processors have to negotiate with each other to decide which, if either, has the most recent copy of the resource, or fetch it from the DRAM of whichever processor has it. On Intel architectures this happens over an inter-chip network called QPI, on AMD architectures it's Hypertransport (may have a newer name now). Basically both architectures are NUMA - the DRAM is not directly accessible by all processors - but QPI / Hypertransport synthesise an SMP architecture - pretending that all DRAM is directly accessible by all processors. This is what your software  / OS experiences when it runs.
QPI and Hypertransport are pretty complicated, and invisible to software.


Automatic Account lock/logoff script

Question: I have 2 scripts created. The first one called "lock_logoff" and it does just that. It locks the account in the script and then logs them off. The second script unlocks the account. I got tire of going over to my daughter's computer and doing this by hand when she gets grounded from the computer.
Lock script:
sudo passwd -l amber
sudo pkill -u amber
echo "Account locked and logged off! Screaming in 3....2....1..."

Unlock script:
sudo passwd -u amber
echo "Account unlocked!"
What I am trying to do, since there are more than 1 account on this computer, I would like to add a variable to the script so I do not have to have 3 different lock and unlock scripts. Is there a way I can run "lock_logoff jon" or "unlock amber" and it runs the script for that user?
Comment: It never fails. If I search for what I am trying to do and cannot find it, I will find what I am looking for within moments of posting a question. Here is my lock script:
read -p "who to lock?" name
sudo passwd -l $name
sudo pkill -u $name
echo "$name has been locked. Prepare for screaming in 3.....2.....1..."
Answer: You absolutely can use only one script instead of 3. For that, you could just pass arguments from the command line. In every bash scripts and functions, some variables called positional parameters are automatically generated. At the beginning of your script (i.e. when no other command has been executed yet), you will have :
$0 : the name of the script
$1 : the 1st argument passed
$2 : the 2nd argument ...

Note that those arguments are affected by your IFS & your quotation, so john doe will count as 2 arguments whereas "john doe" will count as one. You can read more about it here
Once you've read the arguments, you will also have to ensure that the user really exists (i.e. you didn't call your script with a typo). To do that, you could use the following code snippet :
#!/bin/bash
user_name="$1"

#here, id returns 'true' if the user exists, else 'false'
#>/dev/null 2>&1 hides the output of the id command
if id -u "$user_name" >/dev/null 2>&1; then
    sudo passwd -l "$user_name"
    sudo pkill -u "$user_name"
    echo "Account locked and logged off! Screaming in 3....2....1..."
else
    echo "Error: user $user_name does not exist"
fi

You can now simply call your script like this : ./myscript amber or ./myscript john
Comment: Excellent. This can of course be expanded with an unlock/lock option. "./myscript amber lock" and "./myscript amber unlock" making it 1 script in total.
Comment: Thank you!!! That is much more than I would have cobbled together myself. I just got threw taking a programming fundamentals class last semester and it is starting to come back to me.
Comment: @KC5SDY Glad it worked for you :) If it helped, don't hesitate to accept the answer by clicking the green mark next to it in order to close your question.

Automatic Account lock/logoff script