Use text lines in one file as filename for others

Question: My script reads two files as input: articles.txt and article-titles.txt
articles.txt contains articles that are delimited with "<<<" without quotes.
While article-titles.txt contain a list of titles delimited "\n" without the quotes. The last one may or may not be delimited with a \n
articles.txt:
This is article.txt. This is article.txt. This is article.txt.
This is article.txt. This is article.txt. This is article.txt.
This is article.txt.This is article.txt. This is article.txt. This is article.txt.
>>>

This is article.txt.This is article.txt. This is article.txt.
This is article.txt. This is article.txt. This is article.txt.
This is article.txt. This is article.txt. This is article.txt.
This is article.txt. This is article.txt. This is article.txt.
>>>

This is article.txt. This is article.txt. This is article.txt. This is article.txt.
This is article.txt. This is article.txt. This is article.txt.This is article.txt.

article-title.txt:
This is the filename of the first article
This is the filename of the second article
This is the filename of the third article

My script should split the articles in articles.txt into separate text files.
Name each file according to each line on article-title.txt.
Fill each character space in the filename with a dash "-"
Filenames should end with a .txt
Therefore a successful execution of the script should have three files or whatever number of files required and one file will be named: This-is-the-filename-of-the-first-article.txt
At the moment my scrip outputs a single file
with open("inputfile.txt", "r") as f1, open("inputfile-title.txt", "r") as f2:
    buff = []
    i = 1
    for line1, line2 in zip(f1, f2):
        x = 0
        if line1.strip():
           buff.append(line1)
        if line1.strip() == ">>>":
           data = f2.readlines()
           output = open('%s.txt' % data[x].replace('\n', ''),'w')
           output.write(''.join(buff))
           output.close()
           x+=1
           print("This is x:", x)
           print("This is data:", data)
           buff = [] #buffer reset

Answer: The immediate flaw is that you read in all the article names the first time you see a delimiter, and then further attempts to read from the same file handle will no longer work. See also Why can't I call read() twice on an open file?
For efficiency and elegance, I would also refactor to simply read and write one line at a time.
with open("articles.txt", "r") as text, open("article-title.txt", "r") as titles:
    for line in titles:
        filename = line.rstrip('\n').replace(' ', '-') + '.txt'
        with open(filename, 'w') as article:
            for line in text:
                if line.strip() == '>>>':
                    break
                article.write(line)

This will obviously not work correctly if the number of file names is less than the number of sections in the input file. Conversely, if there are too many file names, the excess ones will not be used. Perhaps a better design would be to inline the file names into the data, or perhaps devise a mechanism for generating fallback file names if there are not enough of them in the input.
Demo: https://ideone.com/hYnOzP
Answer: You should separate your parsing logic and also your writing logic.
First I'd read the article contents and parse them
Secondly I'd read the article titles.
Last I'd use the collected information and write out the content.
One possible way of doing it:
with open("articles.txt") as articles_fp:
    articles = [article.strip() for article in articles_fp.read().split(">>>")]

with open("article-title.txt") as article_title_fp:
    artice_filenames = [
        "-".join(title_line.strip().split()) + ".txt"
        for title_line in article_title_fp
        if title_line.strip()
    ]

for article_filename, article in zip(artice_filenames, articles):
    with open(article_filename, "w") as article_fp:
        article_fp.write(article)

Answer: First read your titles from your article-titles.txt file into a list.
Then, as you read through your articles.txt file, you can pull (or pop if you want) your titles off the list.
The below simply yields titles as it runs through the articles file.
def get_title():
    with open('titles.txt', 'r') as f:
        yield f.readline().strip()

idx = 0
with open('articles.txt', 'r') as f:
    articles = [
        {'title': get_title(), 'lines': []},
    ]
    for line in f.readlines():
        if line.strip() == ">>>":
            articles.append(
                {'title': get_title(), 'lines': []}
            )
            idx += 1
        else:
            articles[idx]['lines'].append(line.strip())

Answer: How your code behaves will depend on the inputs, so it is difficult to exactly replicate your situation. However, there are a few potential issues.
You are currently searching by line both files at the same time. However, since their lines don't line up 1:1, you run into problems (f1 is still reading lines when f2 is done). You don't interact with f2 except for readlines(), which would grab all lines in the file starting at the current (moving) position in the file, which is not what you want. Add some print statements to your code, and you will see how it is behaving.
Instead, I suggest iterating through the 2 files separately, then splitting the two files in their unique ways is clearer. Here is one option. Because you know f1 is deliniated by <<<, one option is to read in the entire file first (if not too large), then use the string.split() function on this deliniation. You can then directly match each individual line of f2 to the split output of f1.
Comment: How so? The question includes all the necessary inputs.
Comment: The immediate problem is that `data` ends up empty on the second and subsequent iterations because the first iteration already exhausted the file handle, as explained in my answer.
Answer: I think you complicated it a bit, this should work:
with open("articles.txt", "r") as f1, open("article-title.txt", "r") as f2:
    files = f2.read().split("\n")
    data = f1.read().split(">>>\n\n")

for file, datum in zip(files, data):
    file_name = file.replace(" ", "-")
    with open(f"{file_name}.txt", "w") as f:
        f.write(datum)

Comment: This will work nicely as long as the files are small, but degrade badly if you need to process large amounts of data.
Comment: @tripleee I agree, I was just trying to get the cleanest way possible to help the OP but failed to actually think about large amounts of data


How can I verify my account?

Question: I'm a newbie at Ingress. I see other, more experienced players have a silver badge saying that their account is verified, but I can't find the corresponding feature in the application. How can I verify my account and get this badge?
I have read that I should be asked for verification when reaching level 2, but I'm already at level 5 and nothing of the sort happened.
Answer: Niantic has removed the verify option since some weeks before it spun from Google.
See the comment of Niantic in this post:
"We've turned verification off."
Support page:

As of September 2015, we've removed the verification feature in Ingress, and it is no longer possible to receive the Verified Agent medal.
  All features that previously required verification will still work for new Agents that have never had the option to verify.
Answer: I'm now L7, and i never had the opportunity to verify.
ingress G+ said it's an error right now and they're working to fix it. Posted within the last 60 days.
they're working on it.
Comment: Would you be willing to link the post in question?
Comment: If you don't need to verify to get a 2000 items inventory limit, you only miss a badge. Nobody will ever brag about this badge.
Answer: When you reach level 2 you'll be asked to enter a verification code that will be sent to you via SMS to verify that you are, in fact, you.
Once that's done you'll automatically get the 'Verified' badge and your inventory space will be expanded from 200 to 2000 items.
Comment: It didn't happen; I have edited my question to make this clearer.

How can I verify my account?


Writing an array to a (server-side) text file

Question: So I've got my javascript array (var seatsArray = [];), let's say it has some contents. I want to write the contents of that array to a .txt file on the server when the user clicks a button. The text file will not already exist so it needs to be created.
Also, if anyone knows how I could allow the user to specify the name of the text file to be created by typing it in a text area, that would be great.
Any ideas?
Many thanks
John
EDIT:
Added the suggested code, however, nothing happens when I hit save?
<form id="my_form" action="">
<input type="text" id="file_name" rows="1" cols="20">
Save
</form>

That is all in the body section.
Thanks
Comment: You'll need to specify what server side language you want this to work with.
Answer: You can layout a web form with, among other things, a text field for file name. Then write a Javascript submit event for the form and, in its handler, before send the data build the url with your data.
For the array you can join its data so its converted into a string with a comma separator
var seatsArray = [1,4,5,6];
var d = seatsArray.join(); // "1,4,5,6"

var url = "http://my_site/my_file.php?my_array="+d + "&file_name=" +
document.getElementById("file_name").value;

document.getElementById("my_form").action = url;
document.getElementById("my_form").method = "POST";
document.getElementById("my_form").submit();

Comment: ok then use method POST and not GET so you have no limit and nothing is visible into the url.
Comment: Will that mean d = 1,4,5,6? Because this array will have hundreds of values inside it so this wouldn't be effective to put into the URL address bar? Thanks
Comment: Added all the code and put it into the original question. Nothing seems to happen when I press save though?


How to get GridView item from AutomationElement?

Question: I can get the AutomationElement for a ListView/GridView with the FindAll method. The classname for the individual items in a row is ContentPresenter. I would like to get the value but I can only get their position (column, row).
I have tried many patterns in the ValuePattern is not supported.
Answer: By default this is not possible with .NET UIAutomation. The strings underlying the GridView are too dumb. If there is a TextBox in the GridView it is possible to get it and manipulate it using the ValuePattern.
You could also add an intelligent kind of label implementation which supports the ValuePattern. This was not possible in my case but might be if you program both sides of the UIAutomation by yourself.


Should I switch from propane to electric heat?

Question: After a downright frightening heating bill, I am thinking of switching to electric heat. I want this to be as little impact to the house as possible. I currently live in a 1100 sq ft manufactured home (mobile home... its a trailer) with a bedroom on each of the polls and a massive kitchen and living room area. My plan is:

A small space heater per bedroom
A baseboard heater for the kitchen livingroom area

My home has 100A line coming in with a 60A main breaker. The electrical is already heavily separated and my panel has enough room for two more 15A breakers. I do not have ready access to a 230V line. (I know enough not to do any work here myself)
Is there anything that I need to know before committing to this? Does anyone have any similar stories that can help me with this?
P.S. It may be worth noting that I currently pay $5.10/gal (!!) for propane and $0.08/kwh for electric. The current system is forced hot air.
UPDATE: I have equipped the main rooms with electric, oil-filled heaters. During the day they keep the house warm enough and at night our bedrooms are fine (the living room and kitchen suffer but I'm the only one who wakes up early enough to notice so moot point).
Comment: Do the research and make sure you will be saving money.  No sense spending money to change systems, only to find out you actually spend more.
Answer: You should consider a few conditions when deciding what is the most efficient (often cheapest) method for heating your home.
The Department of Energy site has some good resources about regional heating fuel costs.
Their heating fuel comparison calculator is a useful example:
http://www.eia.doe.gov/ask/conversionequivalents_faqs.asp#compare_heating_fuels
Consider installation costs as well as operating costs. There are obviously some pretty efficient heating techniques (geothermal and solar) that unfortunately, still have extremely high installation costs. This often makes their installation untenable.
Comment: The energy calculator was wonderful. With it I roughed out about $20 per million btu for electric, $70 per million btu for propane. Geothermal is out because I don't own the land under me and I don't plan on being there long enough to recoup solar (solar electric) nor do I want to put holes in my roof/wall for additional duct work (solar heat).
Comment: @BobRoberts -- keep in mind that an air to air heat pump is cheaper than straight resistance heat yet still in terms of electric bills :)
Answer: Consider putting your money in to conservation instead of new equipment. For example:

Turn down the thermostat. Dropping it a few degrees takes about 10% off your fuel usage.
Get a digital thermostat. It lets you set the temperature exactly where you want it, instead of guessing and over- or under-heating.
Get a programmable thermostat. You can let the house be cooler while you're sleeping under heavy covers, or while you're out during the day.
Insulate yourself. A wool underlayer doesn't affect your appearance or mobility, but makes your body warmer. I wear these pretty much all winter long:

http://www.rivbike.com/products/show/wool-semi-tights/22-271

Move around when you get cold, instead of turning up the heat.
Insulate the structure. Make sure the walls, floor, and ceiling all have insulation.  There are limits (thickness of the walls, for example), but do what you can.
Reduce air infiltration. Air exchanges carry a lot of heat out of a house. Look for crevices that let air in/out. Maybe some weather stripping around the doors. Of course, you want to keep enough air moving to keep it healthy.
Insulate windows. A single pane of glass is only R-1. That's almost nothing. Even 3 panes of glass is only R-3 - a huge improvement, but still much lower than your walls probably are. Some options:

Replace with better windows. This is pretty expensive.
Put a layer of plastic on the inside or outside (or both sides!) of your windows. Even though they don't insulate much, they slow down convection over the surface of the glass.
Put up blinds and/or drapes and close them when the sun goes down.
Cut styrofoam insulation panels to the size and shape of your window frames. Insert them when the sun goes down. To make them look nice, cover in fabric.
Comment: Great ideas! It's also cheaper too. =)
Answer: Two 110-volt 15 A circuits would give you 15 A × 110 V = 3.3 kW of power.  I think that's too little.
Here's my back-of-the-envelope calculation: I live in a house that's a little bigger than yours, but presumably better insulated, so let's assume they're equivalent.  I use ~100 gallons of heating oil per month in the winter.  A gallon of heating oil has 41 kWh of energy, so I use ~4100 kWh of energy per month.  That's for heat and hot water.  A month is 720 h long, so the average power is 5.7 kW.  In reality I need more power than that, for more heat is needed at night and on particularly cold days.
How large is your propane tank, and what is the fastest you go through it in the winter?
Comment: We have 200gal, and between the most recent bill and the previous bill, used 130 gal in 90 days. There is only one heating zone. My house was built in 2004 and is reasonably well insulated
Answer: I know of a person who uses two electrical oil-filled radiators with total output of 2,5 kW to heat a room in a 440 sq ft log house in a region where -10 Celsius is typical in winter. However, he only does so from late fall till early winter and from early spring till summer since it's a summer house and he lives in an apartment most of the time. He does so for three reasons - it's very clean, it doesn't need any manual labor to run and it can be left unattended for the workdays when he is in the city. He never brought up what he thinks of the prices but I guess he doesn't suffer much or he would complain otherwise.
My two cents are the following: First, electricity is safer when done right - gas equipment can leak gas and cause a devastating explosion. Second, try to keep at least part of the already installed equipment so that in case of a power outage you have a backup way to heat your house. With electricity you depend on the supplier heavily and once in a while even major cities experience days long blackouts.
Comment: Thank you for your answer. I will keep the current system only out of the fact that it has my AC built in and I need the propane for my stove/oven. If the power goes off though, my goose is cooked (or frozen perhaps) as the forced hot air requires a blower.
Answer: Look at using a heat pump, as the give about 4 unit of heat for each unit of electric used, however they are not cheap.
ALso spending a bit on inproving your insulation may give a much better payback then spending the money on the heating side.
Comment: I don't believe I will go with the heat pump. I like the idea but I don't believe the payoff will come before before I move. I will be looking into my insulation though.
Comment: That link is dead. Can you update it?
Answer: I think you're on the right track. I live in a city and my 80% efficient, 15 year old natural gas heating system is up and down. It costs so much to run I decided to exhaust all alternatives before paying for a system and continuing to pay outrageous amounts for natural gas. My house: 1925 bungalow 2000 square feet with no insulation in the plaster walls. Here is what I have done to be comfortable without a huge bill.

I closed in my crawl space: closed vents, applied 6 mil vapor barrier, etc. Now the cold winter wind doesn't blow under and through my house. Big comfort gain.
I bought two oil filled radiator heaters - only buy the ones that have real, programmable thermostats that read in degrees. These serve as my thermostats for different areas of the house to keep the temperature consistent. We tested many other heaters then sent them back.
I get my baseline of heat to 64 or 65 degrees with the cheapest heat source I can find. For me that is an unvented propane infrared wall mounted heater - nearly 100% efficient - all of the heat stays in the house. I just open doors to adjacent rooms to provide more air than necessary for combustion - otherwise your air quality will suffer.

Everybody wants to sell you more insulation - its very expensive and still doesn't transition you to an affordable heating source. If your house is sealed to prevent air infiltration more expensive insulation won't pay your power/gas bill. Going to 100% efficiency in a heat source will get you a long way there. Electric heaters converts nearly all of the power to heat except for what runs the blower - unvented gas heaters also have a very high efficiency ratio.
Then you can say goodbye to high heating bills without sacrificing your comfort.
Answer: I changed from propane is 100% electric. We have a 1344 sq ft double wide mobile in the country. We have 3 infra red heaters, 2 in the kitchen living room area and 1 in the rear hallway. We have a direct replacement 20kw electric heater with central air in the original place. Down to 30 degrees the small heaters keep it at 70 degrees, they run 24/7. The main heater only comes on below 30 degrees when the others cant maintain. Small heaters set at 74 degrees main heater set to come on at 69 and off at 71. Recovery time on main heat from 69 to 71 degrees around 10 to 15 minuets.Winter rates @ .086 up to 1000 kwh and .051 after that.Last year my total electric bill for heating/ac and everything averaged 198.00 per month.25 kwh equal 1 gallon of propane-25kwh times .051=127.50 propane,same rate all the time does not change
Comment: Hello, and welcome to Stack Exchange. This is great information, but a little hard to understand. Would you edit it to clean it up a bit, perhaps break it into paragraphs? Thanks.
Answer: In your case, electricity appears to be a much cheaper source of heat than propane.
A gallon of propane yields 91,600 BTUs of heat.  Google can convert that for you:
https://www.google.com/search?q=91600+btus+in+kwh

So with propane costing you $5.10 / gallon, the same heat from electric is costing you 26.84531 * $0.08 or $2.15 - less than half the price.
When you consider that electric is lower maintenance - I see baseboard heaters all over, every day, that have been working for 20 years without any service - it's an even bigger savings.
Electric heat also lends itself to more thermostats and easily controlling more zones, even room by room - not easy to accomplish with other heat.
I've had good luck with those oil-filled space heaters too.
Your electrician will be able to check if the load can handle it, but there's probably room for a 20A or 30A baseboard heater for the main room, and that  might do it for you.  You might still need the propane on top for the coldest weather, depends on your insulation and your climate.  Make sure you tell him you're using the space heaters in the bedrooms.  He might rearrange the panel so those are on opposite legs of the service.
Answer: My electric conversion above required 2 60 amp circuits and my breaker box was not big enough to handle the furnace. I had 200 amps at the outside pole and was only using 100 amps for the house. I installed a 100 amp box at the pole and put two 60 amp double breakers in side. I then ran 4 #6 cable wires and 2 10 guage ground wires in 1.5 inch conduit under ground.These wires go under the home and straight up to the heater. There are breakers at the pole and on the furnace.Also if 1 gallon of propane is 1.30 we heat with 1 kwh = .05135. Therefore Im paying about 1.37 = 1 gal propane. Price is the same 24/7. Cannot run dry. no explosions. No gas line checks. No 300 gallon min fills. Not at the mercy of farmers drying corn or supply lines down for maintanance. This my 3rd or 4th year on the conversion. I dont think this would work as well as it does for me if I didnt use  radiant heaters with this setup. Im happy with it but it may or my not work in your situation. email me if you want moer info.


Convolution process with gaussian white noise

Question: A Gaussian process $z(s)$ can  be established by convolving a gaussian white noise process $x(s)$ with a smoothing kernel $k(s)$ http://ftp.stat.duke.edu/WorkingPapers/01-03.pdf
$$z(s)=\int_{S}^{} \! k(u-s) x(u).du \ \  \text{where } s\in R $$
As a result, the covariance between any two points $s$ and $s'$ can be expressed as follows
$$ c(s, s')=\int_{S}^{} \! k(u-s) k(u-s').du= \int_{S}^{} \! k(u-(s-s')) k(u).du$$
I need help understanding two issues :
1) white noise process is discontinuous and thus Riemann integration cannot be used in the first equation
2) How is the covariance equation derived
3) How did $s'$ jump to the first kernel
Comment: The input process should not necessarily be Gaussian.
Comment: @msm Yup i understand that, but in the case that $x(s)$ is a gaussian white noise, how are these equations derived ? thanks
Comment: a white noise is a random i.i.d. zero mean sequence $W_n$.  The "continuous" analog doesn't exists (the limit when the sample rate $\to \infty$) but there is the Wiener process $B(t)$ , whose "derivative" is such a white noise with infinite sample rate : $B(t) = \lim_{N \to \infty} \frac{\sum_{n =1}^{\lfloor N t \rfloor} W_n}{\sqrt{N}}$ (the $\frac{1}{\sqrt{N}}$ is necessary for $\mathbb{E}[ |B(t+a)-B(t)|^2] = a\mathbb{E}[|W_n|^2]$). $\quad$ So what I mean is that you can convoluate $B(t)$ with $k'(t)$ and you should get the covariance you'd like
Comment: @user1952009. Thank you. My question is related to the gaussian white noise $x(u)$. In the first page of the paper linked, an illustration of convoltution with white noise is provided. I dont understand how this integral is managed and how they derived the covariance
Comment: read https://en.wikipedia.org/wiki/White_noise#Continuous-time_white_noise  and think to the continuous white noise of your paper and the $w(t)$ of wiki as the derivative of my $B(t)$ (that isn't defined, but it isn't a problem since $B \ast k'(t)$ is) https://en.wikipedia.org/wiki/Wiener_process
Comment: @user1952009 please can you please elaborate more on how the covariance is then derived.
Comment: Possible duplicate: https://math.stackexchange.com/q/1912591/532409 "Convolute White noise"
Comment: https://math.stackexchange.com/q/134011/445105 Scalar product with white noise is closely related to convolutions
Answer: White noise can only be defined in the sense of distributions or as a measure. A good definition can be found in Adler and Taylor (2007, Sec. 1.4.3), see also this SE answer.
To calculate second moments you want to use stochastic integration Adler and Taylor (2007, sec. 5.2) (also see below) for deterministic functions $f,g$
$$
\mathbb{E}[W(f)W(g)]
\overset{\text{def.}}=\mathbb{E}\Bigl[\Bigl(\int f(x)W(dx)\Bigr)\Bigl(\int g(x)W(dx)\Bigr) \Bigr]
=\int f(x)g(x) dx, \tag{1}
$$
which can be viewed as a special case of the Itô Isometry.
Convolution
We can consider convolutions as a special case
$$
    (f*W)(t) = \int f(t-s)W(ds) = W(f(t-\cdot))
$$
then the covariance function (expectation is zero) is given by
$$
    C(t,s) = \mathbb{E}[ (f*W)(t)(f*W)(s)] =  \int f(t-x)f(s-x)dx
$$
Stochastic Integration
The trick to prove (1), is to show that the mapping
$$
W:\begin{cases}
      L^2(\mathbb{R}^n, \mathcal{B}, \nu)
      &\to L^2(\Omega, \mathcal{A}, \mathbb{P})\\
      f &\mapsto W(f) := \int f(t) W(dt)
\end{cases}
$$
preserves the scalar product.
We first consider simple functions $f=\sum_{i=1}^n a_i \mathbf{1}_{A_i}$ for disjoint $A_i$, then
$$
   W(f)=\int f(t) W(dt) \overset{\text{def.}}= \sum_{i=1}^n a_i W(A_i)
$$
Comment: in particular the expectation is zero and variance given by $\sum_{i=1}^n a_i \nu(A_i)$ considering the definition of $W$.

To calculate the scalar product between $f$ and $g=\sum_{i=1}^n b_i \mathbf{1}_{B_i}$ we assume without loss of generality $A_i=B_i$ (consider all of their interesections). Then
$$\begin{aligned}
\langle W(f), W(g) \rangle_{L^2(\mathbb{P})}
&= \mathbb{E}\Bigl[\sum_{i=1}^n a_i W(A_i) \sum_{j=1}^n a_j W(A_j)\Bigr]\\
&= \sum_{i=1}^n a_i b_i \mathbb{E}[W(A_i)^2]\\
&= \int f(t) g(t) \nu(dt)\\
&= \langle f, g\rangle_{L^2(\nu)}
\end{aligned}$$
Since the simple function are dense in $L^2$ and the scalar product is continuous we can deduce that $W$ is an isometry (where $W(f)$ for general $f$ is defined as the limit of $W(f_n)$ for simple functions $f_n$ approximating $f$). (1) then directly follows from the respective definitions of the scalar product (i.e. the second and penultimate term).


Unscrew a screw in a hole

Question: There is a screw in a hole in my laptop. I fail to unscrew it with a screw driver. How can I unscrew it?
The end of the handle of the screwdriver is loose, and what is the looseness supposed to be used for?
Thanks.

My tools
Answer: The loose end is for your index finger to press the screwdriver against the screw and thus provide the second fixed point for its axis while the thumb and the middle finger are turning the screwdriver. It allows the most precise operation of all manual screwdrivers.
I would also speculate that this might not be the right tool for the work. This kind of screwdrivers are for precision work where you need to be very exact in where you touch your device and exert a very limited force. You need a regular screwdriver, which would allow to exert higher torque and at the same time press stronger along the screwdriver/screw axis to prevent them from losing each other.
For the screw you want to turn, you need one of the bits in your second photo, in the holder with the word "Poholy" on it, number 5...7 from the left in the photo (4...6 if you turn it upside up). Take the one that fits the screw best. You will also need a handle, which is missing in your photo. It looks something like the blue one in this photo.
You can use the electrical screwdriver from Worx that you showed in another post, but choose the correct bit and as low torque as possible to start with. With the electrical screwdriver, it's very easy to damage the screw cap.
Comment: @Tim, grab it with the pliers instead of your thumb and middle fingers. But I would rather buy a dedicated screwdriver in your place. They a couple of Euros and are really useful in the household.
Comment: Thanks. Is this a right tool for unscrewing the screw in the hole http://diy.stackexchange.com/questions/90568/whats-the-name-of-this-tool ?
Comment: @Tim, can you mark with a circle or arrow the screw you are having troubles with? It looks like you have all the needed tools but I am not sure what the trouble is exactly. I would avoid using the electric screwdriver in this case, it's more for assembling furniture or hanging shelves.
Comment: The screw deep in the hole in the bottom left corner of the laptop, below the screw driver.
Comment: picture updated.
Comment: @Tim, answer updated.
Comment: Yes, the handle is not shown in the second picture. The bits are too thick to reach the screw in the hole, so I used the screw driver in the first picture., but was unable to drive the screw because it was too tight.
Comment: @Tim, now the story is clear. It happens all the time, so I also have a separate set of simple screwdrivers for such situations. One last thing you can try before getting another tool is take your precision screwdriver and, while pressing it against the screw with one hand, try to turn it using the pliers I also see in your set. They are not the most suitable for this job, but may work. Just make sure the tip of the screwdriver is not too small for the screw, otherwise you may kill the latter.
Comment: What does "turn it using the pliers" look like?
Comment: what's a dedicated screwdriver here?
Comment: @Tim, just a screwdriver that fits this specific screw and hole (i.e. depth, diameter). Take you laptop to a local DIY or electrical store, they'll show you. You can also buy a set, it's cheaper per tool. I have something like [this](http://www.spear-and-jackson.com/product/new-products/vde-screwdriver-set-6pc). (Note that these specific screwdrivers are electrically isolated, meaning they are thicker for most of the length than the non-isolated ones. So make sure to check what you buy fits your hole.)

Unscrew a screw in a hole


NTFS drive mount

Question: I have both windows 8.1 and ubuntu 14.04 installed on my system.
I was not able to mount my drives in ubuntu but after disabling fast startup in windows it worked perfectly fine.
I recently installed cinnamon shell in my ubuntu and after that i'm not able to mount my windows drive( C:). My D: drive is easily mounted but in case of my C: drive it shows that windows is hibernated and ntfs drive is in unsafe mode.
I tried shutting and restarting windows with both fast startup enabled and disabled but its still no use.
What can i do to mount my C: dive ?
Comment: Possible duplicate of [Unable to mount Windows (NTFS) filesystem due to hibernation](https://askubuntu.com/questions/145902/unable-to-mount-windows-ntfs-filesystem-due-to-hibernation)
Answer: Here is a detailed answer to your problem: Unable to mount Windows (NTFS) filesystem due to hibernation
What i did most of the times, was to open the drive in read only mode as i mostly only copy files from ntfs drives or watch movie from it.
Here is how to do that:
Open the application 'disks utility'. Select the drive on right hand side. chose the volume label that you want to open as read only.
There is a settings icon somewhere below it. click it and select the read-only option.
That should do it.

NTFS drive mount


Dynamic change of JavaFX controls from other objects

Question: I'm working on a simple javaFX desktop software, it essentially allow a user to control various lights via serial communication.
It's composed of three classes:

he UI Controller (written using javaFX scene builder 2.0 and a custom library for material-like controls, jfoenix)
a "Storage" object with static properties (like which light is on and what color it should display), this class must contain only static properites, so that there are no conflicts with other objects trying to modify some values.
This object is also responsable for the serial communication (using jssc)
A threaded object that controls lights using timers

I must say that i have a working solution built using swing, but i honestly don't like it at all...
Here's the compiled UI: https://i.stack.imgur.com/UM0so.jpg
There are two problems:

I want that each button on the top (like "barra 1") displays the status of the corrisponding light, for example, if "barra 1" is on, it should be green, when it's off, it should be red. the problem here is that i have to create an object of the controller class in order to access to all the buttons, but as it should be, in the instantiated object, all the buttons are gone, i should recreate them, and that's obivuosly not the solution... what can i do?
That's simple, I already know that my "listener" is incorrect, but I just can't find the mistake... as soon as I drag any of the sliders, a Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: argument type mismatch exception is thrown... (and there's no reference to any of my classes)

Here you can find the code:
Storage class

package com.matteoformenti.rgbcontroller;

import java.awt.*;

/**
 * Created by Matteo on 28/12/2015.
 */
public class Storage
{
    private static final String ON_COLOR = "#4CAF50";
    private static final String OFF_COLOR = "#F44336";

    private static Color color;
    private static boolean bars[] = {false, false, false, false, false};
    private static boolean circles[] = new boolean[2];
    private static boolean usePot = false;

    //-------------------------------------------------------//

    public static boolean getBarValue(int barNumber)
    {
        return bars[barNumber];
    }

    public static void setAllBars(boolean value)
    {
        for(boolean v : bars)
            v = value;
        setAllBarsColors();
    }

    public static boolean[] getAllBars()
    {
        return bars;
    }

    public static void setCircleValue(int circleNumber, boolean value)
    {
        circles[circleNumber-1] = value;
    }

    public static boolean getCircleValue(int circleNumber)
    {
        return circles[circleNumber-1];
    }

    public static void setAllCircles(boolean value)
    {
        for(boolean v : circles)
            v = value;
    }

    public static boolean[] getAllCircles()
    {
        return circles;
    }

    public static void setColor(Color c)
    {
        color = c;
    }

    public static void setRed(int red)
    {
        if(red > 255)
            red = 255;
        if(red < 0)
            red = 0;
        int g = color.getGreen();
        int b = color.getBlue();
        color = new Color(red, g, b);
    }

    public static void setGreen(int green)
    {
        if(green > 255)
            green = 255;
        if(green < 0)
            green = 0;
        int r = color.getRed();
        int b = color.getBlue();
        color = new Color(r, green, b);
    }

    public static void setBlue(int blue)
    {
        if(blue > 255)
            blue = 255;
        if(blue < 0)
            blue = 0;
        int g = color.getGreen();
        int r = color.getRed();
        color = new Color(r, g, blue);
    }

    public static void setHue(int h)
    {
        int rgb = Color.HSBtoRGB(h, 100, 100);
        int red = (rgb >> 16) & 0xFF;
        int green = (rgb >> 8) & 0xFF;
        int blue = rgb & 0xFF;
        color = new Color(red, green, blue);
    }

    public static void invertBarValue(int i)
    {
        bars[i] = !bars[i];
        setBarColor(i);
    }
    public static void invertCircleValue(int i)
    {
        circles[i] = !circles[i];
    }

    public static void setBarColor(int i)
    {
        Controller c = new Controller();
        c.test();
        /*Controller.bar1.setStyle("-fx-background-color: " + ON_COLOR + ";");
        if (bars[i] == true)
            Controller.getBarButton(i).setStyle("-fx-background-color: " + ON_COLOR + ";");
        if (bars[i] == false)
            Controller.getBarButton(i).setStyle("-fx-background-color: " + OFF_COLOR + ";");*/
    }

    public static void setAllBarsColors()
    {/*
        for (int i = 0; i < 5; i++)
        {
            if (bars[i] == true)
                Controller.getBarButton(i + 1).setStyle("-fx-background-color: " + ON_COLOR + ";");
            if (bars[i] == false)
                Controller.getBarButton(i + 1).setStyle("-fx-background-color: " + OFF_COLOR + ";");
        }*/
    }
}

Controller class:

package com.matteoformenti.rgbcontroller;

import com.jfoenix.controls.JFXButton;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Slider;
import javafx.scene.layout.Background;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;

import java.awt.*;

public class Controller
{

    @FXML
    private JFXButton bar1;

    @FXML
    private JFXButton bar2;

    @FXML
    private JFXButton bar3;

    @FXML
    private JFXButton bar4;

    @FXML
    private JFXButton bar5;

    @FXML
    private JFXButton circle1;

    @FXML
    private JFXButton circle2;

    @FXML
    private Slider rSlider;

    @FXML
    private Slider gSlider;

    @FXML
    private Slider bSlider;

    @FXML
    private Slider aSlider;

    @FXML
    private JFXButton pot;

    @FXML
    private JFXButton stroboBars;

    @FXML
    private Button stroboBarsConfig;

    @FXML
    private JFXButton stroboCircles;

    @FXML
    private Button stroboCirclesConfig;

    @FXML
    private JFXButton fadeColors;

    @FXML
    private Button fadeColorsConfig;

    @FXML
    private ColorPicker colorPicker;

    @FXML
    private Pane frame;

    public void test()
    {
        bar1.setStyle("-fx-background-color: #33b5e5;");
    }

    @FXML
    void bar1Pressed(ActionEvent event)
    {
        Storage.invertBarValue(0);
    }

    @FXML
    void bar2Pressed(ActionEvent event) {Storage.invertBarValue(1);}

    @FXML
    void bar3Pressed(ActionEvent event)
    {
        Storage.invertBarValue(2);
    }

    @FXML
    void bar4Pressed(ActionEvent event) {Storage.invertBarValue(3);}

    @FXML
    void bar5Pressed(ActionEvent event) {Storage.invertBarValue(4);}

    @FXML
    void circle1Pressed(ActionEvent event) {
    }

    @FXML
    void circle2Pressed(ActionEvent event) {

    }

    @FXML
    void potPressed(ActionEvent event) {

    }

    @FXML
    void rSliderChanged(ActionEvent event)
    {
    }

    @FXML
    void gSliderChanged(ActionEvent event) {

    }

    @FXML
    void bSliderChanged(ActionEvent event) {

    }

    @FXML
    void aSliderChanged(ActionEvent event) {

    }

    @FXML
    void colorPickerChanged(ActionEvent event)
    {
        Color colorAWT = Utility.javaFXtoAWTColor(colorPicker.getValue());
        frame.setStyle("-fx-background-color: #" + colorPicker.getValue().toString().substring(2,8) + ";");
    }

    @FXML
    void stroboBarsPressed(ActionEvent event) {

    }

    @FXML
    void stroboBarsConfigPressed(ActionEvent event) {

    }

    @FXML
    void stroboCirclesPressed(ActionEvent event) {

    }

    @FXML
    void stroboCirclesConfigPressed(ActionEvent event) {

    }

    @FXML
    void fadeColorsPressed(ActionEvent event) {

    }

    @FXML
    void fadeColorsConfigPressed(ActionEvent event) {

    }
}

And the fxml layout

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.paint.*?>
<?import com.jfoenix.controls.*?>
<?import javafx.scene.text.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<Pane fx:id="frame" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="260.0" prefWidth="620.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.matteoformenti.rgbcontroller.Controller">
   <children>
      <HBox fx:id="buttonsBox1" layoutY="30.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="40.0" prefWidth="620.0">
         <children>
            <JFXButton fx:id="bar1" alignment="CENTER" buttonType="RAISED" onAction="#bar1Pressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Barra 1">

               <HBox.margin>
                  <Insets bottom="10.0" left="10.0" right="5.0" top="10.0" />
               </HBox.margin>
            </JFXButton>
            <JFXButton fx:id="bar2" alignment="CENTER" buttonType="RAISED" layoutX="20.0" layoutY="20.0" onAction="#bar2Pressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Barra 2">

               <HBox.margin>
                  <Insets bottom="10.0" left="5.0" right="5.0" top="10.0" />
               </HBox.margin>
            </JFXButton>
            <JFXButton fx:id="bar3" alignment="CENTER" buttonType="RAISED" layoutX="80.0" layoutY="10.0" onAction="#bar3Pressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Barra 3">

               <HBox.margin>
                  <Insets bottom="10.0" left="5.0" right="5.0" top="10.0" />
               </HBox.margin>
            </JFXButton>
            <JFXButton fx:id="bar4" alignment="CENTER" buttonType="RAISED" layoutX="135.0" layoutY="10.0" onAction="#bar4Pressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Barra 4">

               <HBox.margin>
                  <Insets bottom="10.0" left="5.0" right="5.0" top="10.0" />
               </HBox.margin>
            </JFXButton>
            <JFXButton fx:id="bar5" alignment="CENTER" buttonType="RAISED" layoutX="190.0" layoutY="10.0" onAction="#bar5Pressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Barra 5">

               <HBox.margin>
                  <Insets bottom="10.0" left="5.0" right="5.0" top="10.0" />
               </HBox.margin>
            </JFXButton>
            <JFXButton fx:id="circle1" alignment="CENTER" buttonType="RAISED" layoutX="280.0" layoutY="20.0" onAction="#circle1Pressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Cerchio 1">

               <HBox.margin>
                  <Insets bottom="10.0" left="20.0" right="5.0" top="10.0" />
               </HBox.margin>
            </JFXButton>
            <JFXButton fx:id="circle2" alignment="CENTER" buttonType="RAISED" layoutX="340.0" layoutY="10.0" onAction="#circle2Pressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Cerchio 2">

               <HBox.margin>
                  <Insets left="5.0" right="5.0" top="10.0" />
               </HBox.margin>
            </JFXButton>
            <JFXButton fx:id="pot" alignment="CENTER" buttonType="RAISED" layoutX="395.0" layoutY="10.0" onAction="#potPressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Potenziometri">

               <HBox.margin>
                  <Insets left="20.0" top="10.0" />
               </HBox.margin>
            </JFXButton>
         </children>
      </HBox>
      <HBox alignment="CENTER" fillHeight="false" layoutY="80.0" prefHeight="40.0" prefWidth="620.0">
         <children>
            <VBox prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS">
               <children>

                  <Slider fx:id="rSlider" max="255.0" onDragDetected="#rSliderChanged" value="128.0" />
               </children>
               <HBox.margin>
                  <Insets left="10.0" right="10.0" />
               </HBox.margin>
            </VBox>
            <VBox prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS">
               <children>

                  <Slider fx:id="gSlider" max="255.0" onDragDetected="#gSliderChanged" value="128.0" />
               </children>
               <HBox.margin>
                  <Insets left="10.0" right="10.0" />
               </HBox.margin>
            </VBox>
            <VBox layoutX="110.0" layoutY="10.0" prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS">
               <children>

                  <Slider fx:id="bSlider" max="255.0" onDragDetected="#bSliderChanged" value="128.0" />
               </children>
               <HBox.margin>
                  <Insets left="10.0" right="10.0" />
               </HBox.margin>
            </VBox>
            <VBox layoutX="210.0" layoutY="10.0" prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS">
               <children>

                  <Slider fx:id="aSlider" max="255.0" onDragDetected="#aSliderChanged" value="128.0" />
               </children>
               <HBox.margin>
                  <Insets left="10.0" right="10.0" />
               </HBox.margin>
            </VBox>
         </children>
      </HBox>
      <ColorPicker fx:id="colorPicker" layoutX="10.0" layoutY="130.0" onAction="#colorPickerChanged" prefHeight="25.0" prefWidth="600.0" />
      <HBox alignment="TOP_CENTER" layoutY="175.0" prefHeight="50.0" prefWidth="620.0">
         <children>
            <HBox prefHeight="50.0" prefWidth="150.0">
               <children>
                  <JFXButton fx:id="stroboBars" alignment="CENTER" buttonType="RAISED" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onAction="#stroboBarsPressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Strobo Barre" textAlignment="CENTER" HBox.hgrow="ALWAYS">
                     <HBox.margin>
                        <Insets bottom="10.0" left="10.0" right="5.0" top="10.0" />
                     </HBox.margin>
                  </JFXButton>
                  <Button fx:id="stroboBarsConfig" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#stroboBarsConfigPressed" prefHeight="25.0" prefWidth="25.0" style="-fx-background-color: #33b5e5;" textFill="#33b5e5">
                     <HBox.margin>
                        <Insets bottom="10.0" right="10.0" top="10.0" />
                     </HBox.margin>
                  </Button>
               </children>
            </HBox>
            <HBox layoutX="150.0" layoutY="10.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="50.0" prefWidth="150.0">
               <children>
                  <JFXButton fx:id="stroboCircles" alignment="CENTER" buttonType="RAISED" onAction="#stroboCirclesPressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Strobo Cerchi" textAlignment="CENTER" HBox.hgrow="ALWAYS">
                     <HBox.margin>
                        <Insets bottom="10.0" left="10.0" right="5.0" top="10.0" />
                     </HBox.margin>
                  </JFXButton>
                  <Button fx:id="stroboCirclesConfig" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#stroboCirclesConfigPressed" prefHeight="25.0" prefWidth="25.0" style="-fx-background-color: #33b5e5;" textFill="#33b5e5">
                     <HBox.margin>
                        <Insets bottom="10.0" right="10.0" top="10.0" />
                     </HBox.margin>
                  </Button>
               </children>
            </HBox>
            <HBox layoutX="320.0" layoutY="10.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="50.0" prefWidth="150.0">
               <children>
                  <JFXButton fx:id="fadeColors" alignment="CENTER" buttonType="RAISED" onAction="#fadeColorsPressed" ripplerFill="WHITE" style="-fx-background-color: #F44336;" text="Strobo Cerchi" textAlignment="CENTER" HBox.hgrow="ALWAYS">
                     <HBox.margin>
                        <Insets bottom="10.0" left="10.0" right="5.0" top="10.0" />
                     </HBox.margin>
                  </JFXButton>
                  <Button fx:id="fadeColorsConfig" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#fadeColorsConfigPressed" prefHeight="25.0" prefWidth="25.0" style="-fx-background-color: #33b5e5;" textFill="#33b5e5">
                     <HBox.margin>
                        <Insets bottom="10.0" right="10.0" top="10.0" />
                     </HBox.margin>
                  </Button>
               </children>
            </HBox>
         </children>
      </HBox>
   </children>
</Pane>

Thanks a ton for your help, have a nice day!!
Formenti Matteo
Comment: You shouldn't create a new instance of the controller class. You should get the already loaded one from the `FXMLLoader` - see here http://stackoverflow.com/questions/10751271/accessing-fxml-controller-class

As to your second question - I don't really understand what the question is, or which method you are referring to.
Comment: Thank you!! That's what i was searching for!!! This is what happens as soon as i drag any of the sliders http://pastebin.com/JdDJ0GvR
Comment: Unrelated, but never import java.awt or javax.swing classes in a JavaFX application unless you really need to you (and you probably don't need to).
Answer: The exception you are getting is because you are trying to hook a MouseEvent handler to an ActionEvent handler - see here. Changing the argument type to MouseEvent should get rid of the exception.
However! this event deals with drag-and-drop, which is probably not what you are after! See this tutorial - you should either bind to the value property of the slider, or add a ChangeListener to it.


Block filters using fragment shaders

Question: I was following this tutorial using Apple's OpenGL Shader Builder (tool similar to Nvidia's fx composer, but simpler).
I could easily apply the filters, but I don't understand if they worked correct (and if so how can I improve the output). For example the blur filter: OpenGL itself does some image processing on the textures, so if they are displayed in a higher resolution than the original image, they are blurred already by OpenGL. Second the blurred part is brighter then the part not processed, I think this does not make sense, since it just takes pixels from the direct neighborhood. This is defined by
float step_w = (1.0/width);

Which I don't quite understand: The pixels are indexed using floating point values??
Blurred Image http://img218.imageshack.us/img218/6468/blurzt.png
Edit: I forgot to attach the exact code I used:
Fragment Shader
// Originally taken from: http://www.ozone3d.net/tutorials/image_filtering_p2.php#part_2

#define KERNEL_SIZE 9

float kernel[KERNEL_SIZE];

uniform sampler2D colorMap;
uniform float width;
uniform float height;

float step_w = (1.0/width);
float step_h = (1.0/height);

// float step_w = 20.0;
// float step_h = 20.0;

vec2 offset[KERNEL_SIZE];

void main(void)
{
   int i = 0;
   vec4 sum = vec4(0.0);

   offset[0] = vec2(-step_w, -step_h);  // south west
   offset[1] = vec2(0.0, -step_h);      // south
   offset[2] = vec2(step_w, -step_h);       // south east

   offset[3] = vec2(-step_w, 0.0);      // west
   offset[4] = vec2(0.0, 0.0);          // center
   offset[5] = vec2(step_w, 0.0);       // east

   offset[6] = vec2(-step_w, step_h);       // north west
   offset[7] = vec2(0.0, step_h);       // north
   offset[8] = vec2(step_w, step_h);        // north east

// Gaussian kernel
// 1 2 1
// 2 4 2
// 1 2 1

   kernel[0] = 1.0;     kernel[1] = 2.0;    kernel[2] = 1.0;
   kernel[3] = 2.0; kernel[4] = 4.0;    kernel[5] = 2.0;
   kernel[6] = 1.0;     kernel[7] = 2.0;    kernel[8] = 1.0;

// TODO make grayscale first
// Laplacian Filter
// 0   1   0
// 1  -4   1
// 0   1   0

/*
kernel[0] = 0.0;    kernel[1] = 1.0;    kernel[2] = 0.0;
kernel[3] = 1.0;    kernel[4] = -4.0;   kernel[5] = 1.0;
kernel[6] = 0.0;   kernel[7] = 2.0; kernel[8] = 0.0;
*/

// Mean Filter
// 1  1  1
// 1  1  1
// 1  1  1

/*
kernel[0] = 1.0;    kernel[1] = 1.0;    kernel[2] = 1.0;
kernel[3] = 1.0;    kernel[4] = 1.0;    kernel[5] = 1.0;
kernel[6] = 1.0;   kernel[7] = 1.0; kernel[8] = 1.0;
*/

   if(gl_TexCoord[0].s<0.5)
   {
       // For every pixel sample the neighbor pixels and sum up
       for( i=0; i<KERNEL_SIZE; i++ )
       {
            // select the pixel with the concerning offset
            vec4 tmp = texture2D(colorMap, gl_TexCoord[0].st + offset[i]);
            sum += tmp * kernel[i];
       }

        sum /= 16.0;
   }
   else if( gl_TexCoord[0].s>0.51 )
   {
        sum = texture2D(colorMap, gl_TexCoord[0].xy);
   }
   else // Draw a red line
   {
        sum = vec4(1.0, 0.0, 0.0, 1.0);
   }

   gl_FragColor = sum;
}

Vertex Shader
void main(void)
{
    gl_TexCoord[0] = gl_MultiTexCoord0;
    gl_Position = ftransform();
}

Comment: what's the question ? texture coordinates are addressed in the range [0-1], yes.
Answer: Texture coordinates conventionally reach from (0,0) (bottom left) to (1,1) (top right), so in fact, they are floats.
So if you have texturecoordinates (u,v), the "original" coordinates are computed by (u*textureWidth, v*textureHeight).
If the resulting values are not integral numbers, there may be different ways to handle that:

just take floor or ceil of the result in order to make the number integral
interpolate between the neighbouring texels

However I think every shading language has a method to access a texture by their "original", i.e. integral index.
Comment: So then step_w = (1.0/width) should be the numerical distance to the next pixel..
Comment: ugh. This answer has many approximations. 1/ bottom left vs. top right does not mean much to GL. It does not give orientation to textures. 2/ there are no such things as "original" coordinates. There are very good reasons why texture coordinates go from 0 to 1. One of them is mip-mapping. 3/ texels are addressed in their middle...
Comment: Use ARB_texture_rectangle extension.
Answer: @Nils, thanks for posting this code. I've been trying to figure out a simple way to do a convolution on the GPU for some time now.
I tried your code out and ran into the same dimming problem myself. Here's how I solved it.

You have to be careful with your step size to use texture width not
image width. It usually gets re-sized to a power of 2 when the
texture is bound in opengl.
You must also be sure to normalize your
kernel by summing up all values in your kernel and dividing by that.
Also it helps if you convolve R G and B separately without the
illumination, (the fourth component of the sample).

Here's a solution that doesn't have the dimming issue and that also bypasses the need for an offset array for 3x3 kernels .
I've included 8 Kernels that worked for me without dimming.
uniform sampler2D colorMap;
uniform float width;
uniform float height;

const mat3 SobelVert= mat3( 1.0, 2.0, 1.0, 0.0, 0.0, 0.0, -1.0, -2.0, -1.0 );
const mat3 SobelHorz= mat3( 1.0, 0.0, -1.0, 2.0, 0.0, -2.0, 1.0, 0.0, -1.0 );
const mat3 SimpleBlur= (1.0/9.0)*mat3( 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 );
const mat3 Sharpen= mat3( 0.0, -1.0, 0.0, -1.0, 5.0, -1.0, 0.0, -1.0, 0.0 );
const mat3 GaussianBlur= (1.0/16.0)*mat3( 1.0, 2.0, 1.0, 2.0, 4.0, 2.0, 1.0, 2.0, 1.0 );
const mat3 SimpleHorzEdge= mat3( 0.0, 0.0, 0.0, -3.0, 3.0, 0.0, 0.0, 0.0, 0.0 );
const mat3 SimpleVertEdge= mat3( 0.0, -3.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0 );
const mat3 ClearNone= mat3( 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 );

void main(void)
{
   vec4 sum = vec4(0.0);
   if(gl_TexCoord[0].x <0.5)
   {
      mat3 I, R, G, B;
      vec3 sample;

      // fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value
      for (int i=0; i<3; i++){
        for (int j=0; j<3; j++) {
          sample = texture2D(colorMap, gl_TexCoord[0].xy + vec2(i-1,j-1)/vec2(width, height)).rgb;
          I[i][j] = length(sample); //intensity (or illumination)
          R[i][j] = sample.r;
          G[i][j] = sample.g;
          B[i][j] = sample.b;
        }
      }

      //apply the kernel convolution
      mat3 convolvedMatR = matrixCompMult( SimpleBlur, R);
      mat3 convolvedMatG = matrixCompMult( SimpleBlur, G);
      mat3 convolvedMatB = matrixCompMult( SimpleBlur, B);
      float convR = 0.0;
      float convG = 0.0;
      float convB = 0.0;
      //sum the result
      for (int i=0; i<3; i++){
        for (int j=0; j<3; j++) {
          convR += convolvedMatR[i][j];
          convG += convolvedMatG[i][j];
          convB += convolvedMatB[i][j];
        }
      }
      sum = vec4(vec3(convR, convG, convB), 1.0);

  }
   else if( gl_TexCoord[0].x >0.51 )
   {
        sum = texture2D(colorMap, gl_TexCoord[0].xy );
   }
   else // Draw a red line
   {
        sum = vec4(1.0, 0.0, 0.0, 1.0);
   }

   gl_FragColor = sum;
}

Block filters using fragment shaders


Atiyah-MacDonald Ex.3.15: Every set of generators of $A^n$ has at least $n$ elements

Question: There is the following question in Atiyah-Macdonald:

Let $A$ be a ring, and let $F$ be the $A$-module $A^n$. Show that every set of $n$-generators of $F$ is a basis of $F$.

Deduce that every set of generators of $F$ has at least $n$ elements

There is a detailed set of hints that give the first part of the question. Although I am not sure why they assume there are $n$ generators. They use the fact that we have $n$ generators $x_1,...,x_n$ to define $\phi:F\rightarrow F$ by $\phi(x_i)=e_i$. But if we have more than $n$ generators its not clear to me what to do. For example, if $x_1,...,x_n$ are generators, let's take the set of $n+1$ generators $x_1,x_1...,x_n$. Their image is no basis since we have two of the same elements.
I am not sure how to do the second part of the question.
The idea is (I imagine) to show that every basis of $F$ has at least $n$ elements. Then the result follows from the first part. Assume $x_1,...,x_d$ with $d<n$ is a set of generators for $F$. We can define a morphism $\phi: F\rightarrow A^d$ with $\phi(x_i)=e_i$. This is clearly subjective. I think the following works to show that it is injective but I'm not sure if this is  valid property for a basis of a free-module. Since $e_j$ is a basis for the free module $A^d$, $\sum a_i e_i=0$ implies each $a_i=0$. This then gives that if $0=\phi(f)=\phi(\sum a_ix_i)=\sum a_i\phi(x_i)=\sum a_ie_i$. Hence each $a_i=0$ and therefore $f=0$. So $\phi$ is an isomorphism. This gives that $F\cong A^d$ as $A$-modules. But the first part also gives that $F\cong A^n$ as $A$-modules. If we know that $A^d\cong A^n$ implies that $d=n$ we are done.
But this also confused me as this seems to prove something stronger. It proves that every set of generators has exactly $n$ elements. The question only asked to show that each set of generators has at least $n$ elements.

Why do they make the assumption that we have $n$ generators and what do we do if we have more than $n$ generators?
Is my solution for the second part correct?
Is it true that $A^d\cong A^n$ implies $d=n$ and if so how do we prove this? Or perhaps is there some easier result along the lines of: if $A^d\rightarrow A^n$ is a surjection then $d\geq n$, this seems like it would work better with the wording of the question being "at least $n$ elements.
Answer: For the first part, suppose $x_1,...,x_n$ are generators of $A^n$. Since $\{e_1,...,e_n\}$ is a basis we know that the map which sends $e_i\to x_i$ for $1\leq i\leq n$ can be extended to a homomorphism of modules $\phi:A^n\to A^n$. It is obviously surjective because $x_1,x_2,...,x_n$ are all in the image of $\phi$. Now, there is a standard result that a surjective endomorphism of a finitely generated module is an isomorphism. Hence $\phi$ is an isomorphism, and so $\{x_1,...,x_n\}$ is a basis. Of course this solution wouldn't work if the set of generators had more than $n$ elements.
Now, you ask if $A^d\cong A^n$ implies $d=n$. The answer is yes. Let $M=A^n$ and suppose $\{e_1,...,e_r\}$ is some basis of $M$. Using Zorn's lemma we know that there exists some maximal ideal $I\subseteq A$. Then the quotient $M/IM$ is a vector space over the field $A/I$, where the scalar multiplication is $(a+I).(m+IM)=a.m+IM$. Try to show that $\{e_1+IM,...,e_r+IM\}$ is a basis of this vector space.
So, if $M$ has a basis of $r$ elements then $M/IM$ is an $r$-dimensional vector space over $A/I$. Since the dimension of a vector space is well defined, it follows that all bases of $M$ have the same number of elements.
Anyway, the second part of the question doesn't require that. If $\{x_1,...,x_d\}$ is a basis with $d<n$ then we again can define $\phi:A^n\to A^n$ which sends $e_i\to x_i$ for $1\leq i\leq d$ and, say, $e_i\to 0$ for $i>d$. It is a surjective endomorphism of a finitely generated module, and so has to be an isomorphism. But this is absurd, as it is clearly not injective.


Multiple siblings, place some in same row & fill extra space

Question: I have no control of the html. I have a parent with multiple children.Only some of them must be in the same row, while the rest of them stay unaffected and one of them must take up all the extra space. Content is auto generated and % is not an option.
Other options except inline to place on the same row to avoid the problem are welcome as well.

.parent {
  background: red;
}

.same-row-child {
  background: green;
  display: inline-flex;
}

A

B

C

To sum up: Α in the first line unaffected.
 B+C in the same line with B taking up all the extra space.
Comment: You misunderstand the use of flex ;)  this is a tutorial/reminder quiet clear https://css-tricks.com/snippets/css/a-guide-to-flexbox/ and if you do not want the parent to be a flex box, then float is the way
Comment: okay, and what about 3 div on the same row ... is it the last to use the remaing space or is it to be shared with the other but not the first ? .. Your question needs clarification , inline-table, inline-block,inline-flex,inline-grid makes no difference for where it stands but will matter for the children it holds.
Comment: I've simplified it to 3 divs. 1 is the unrelated as hinted from the name. That should be unaffected & have it's own row. The other two should be merged in the same line, but one of them must take all the extra available space.
Comment: okay, what is the idea with inline-flex ?
Comment: To place it in the same line, then trying to grow it. I see two possible solutions. To change the way i place them in the same line or to find a way to grow the inline element.
Answer: If the idea is to use flex, then it should be the parent the flex box:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/
display:flex; display:inline-flex; It enables a flex context for all its direct children.

.parent {
  background: red;
  display: flex;
  flex-wrap: wrap;
}

.other-child {
  width: 100%;
}

.same-row-child {
  background: green;
}

.parent :last-child {
  flex: 1;
  margin-left:2px;
}

A

B

C

looks like not the option you would use See next option

The oldish way is float and overflow, and the one to float is the one that comes first and is supposed to shrink on itself.

see https://css-tricks.com/all-about-floats/
Aside from the simple example of wrapping text around images, floats can be used to create entire web layouts.

.parent {
  background: red;
}

.other-child {}

.same-row-child {
  float: left;
  background: green;
  margin-right: 2px;
}

.parent :last-child {
  float: none;
  overflow: hidden;
  margin: 0;
}

A

B

C

Comment: Float literally does exactly what i need without affecting the parent. For whatever reason my brain tried to forget the pain of the float & only tried to solve it with modern solutions.Thanks for the complete answer & educating me, have a nice day.


Monitoring CPU usage of 2 JVMs running on a single machine

Question: I have two JVMs running on a single machine. I am able to monitor the CPU usage of every single JVM using jConsole but now I have a different scenario.
I also need CPU usage of both JVMs combined. This would give me graph that will show the CPU usage of both JVMs combined.
Can anyone suggest me some tool that could give me the desired result?
Also, I should be able to specify the 2 JVMs for which I need combined results as there could be more than 2 JVMs running simultaneously on the machine.
Comment: Can you run the two programs in the same JVM?
Comment: Not possible...This is product requirement / architecture that both the things should run on different jvm's.
Comment: So this cannot be done even for testing purposes?  Also you can't run the JVMs on a machine or virtual machine by themselves?
Comment: No we can't do this for testing also reason for that being this is integral part of product architecture and would require a lot of changes.
Comment: So I assume you have no way of unit testing this configuration ;) Can you use a lone real/virtual machine to run them both.
Answer: JConsole uses JMX to get the CPU usage from the JVMs. You can write your own JMX client which find this info from the required JVMs directly and combine them (and show them in a graph or something).
Answer: jvmtop shows you all (accessible) jvms and there cpu/memory usage in a top-like manner.


no icons or filesystem in partition while installing Ubuntu 12.04

Question: here a picture:

and a link: https://mail-attachment.googleusercontent.com/attachment/?ui=2&ik=4e292ad6a2&view=att&th=13894b3608347cfe&attid=0.1&disp=inline&realattid=1407738951781842944-1&safe=1&zw&sadnir=1&saduie=AG9B_P-90UfqvUx1Y8mLZGbSwSYU&sadet=1342528638595&sads=J5vmqv6WayRs5pHno-5pbw0_ku8
what can cause it or how to fix? happened also after recreating the Disk On Key of Ubuntu Desktop 12.04 64 Bit
also while exiting the icons have appeared suddenly.
and after wxiting, i was in the LiveCD but none of the program i've installed there was there.
may it be a bug? should tell it in launchbag?
Thanks for helping.
edit:
finally, my way to recognize was trying to reduce every partition, and the one which here minimun of size was bigger than the other-it's windows!
Hope this is helping for you (:
Comment: Check the [md5sum](https://help.ubuntu.com/community/HowToMD5SUM) of your Ubuntu ISO image , and try using Live USB for installation.
Comment: @ObsessiveFOSS - i would suggest you to post it as answer ,linking to the bug report too. Thanks.
Comment: @tijybba Added an answer.
Answer: This is actually a usability bug that is known at launchpad. Please mark it as affecting you as it clearly affects you. There are currently no plans to fix it, but if you mark it as affecting you, it might persuade a developer.
Comment: done: https://bugs.launchpad.net/ubuntu/+source/ubiquity/+bug/947107/comments/8 thanks!
Answer: I would recommend just creating another Live CD. If you are concerned you might have the same issue with your currently downloaded disk image, re-download Ubuntu 12.04 then create another Live CD.


How to stop crouching in Breath of the Wild

Question: Link keeps crouching ... at the most inopportune times .. usually when I'm being chased.  How do I make Link stand up?  And how did I make him crouch in the first place?  I'm using the Wii U GamePad.
Answer: Pressing the left stick makes Link crouch. I do this all the time during fights and battles because I get tense. To stop crouching, press the left stick again.
Comment: Thanks.   I didn't even know you _could_ press the joysticks on the Wii U Gamepad!   This also answers my other unasked question .. what is making the Scope appear mysteriously at times.  (Answer, I'm pressing the Right joystick.)
Comment: This is really annoying.  There should be a timer on this to make certain that you really want to crouch.


Affect all but one image with CSS code

Question: I'm looking to affect all but one (maybe two) images on my website. I', having a little trouble figuring it out.
Is there some sort of code I add to not affect certain images please?
Here Is the code i'm currently using:
// IMAGE 5 STYLING
#collection-56aa7c3422482efd63ae16e1, #collection-

56aa841e5dc6de4554608778, #collection-55b98395e4b08fff340c1e65,
#collection-5807e5edf7e0abd4e55c38bb{
.sqs-block-image .image-block-wrapper {
height: 150px !important;
width: 150px !important;
margin: 0 auto !important;
padding-bottom: 0px !important;
margin-bottom: 0px !important;
border-radius: 300px !important;
transition: all ease-in-out 600ms !important;
    img {
      height: 150px !important;
      width: 150px !important;
      padding: 0 !important;
      left: 0 !important;
      top: 0 !important;
      border-radius: 300px !important;
    }
}
.image-caption {
text-align: center;
margin-left: 0px !important;
}
.image-caption p strong {
text-transform: uppercase;
color: #555 !important;
color: #555 !important;
border-bottom: solid 1px #ccc;
padding-bottom: 10px;
transition: all ease-in-out 600ms !important;
}
  .sqs-block-image:hover {
  .image-block-wrapper {
 -webkit-transform:rotate(10deg) !important;
    -moz-transform:rotate(10deg);
    -o-transform:rotate(10deg);}
.image-caption strong {
  letter-spacing: 2px;
}
  }}
// END OF IMAGE 5 STYLING

Thank you for your help :)
Sophie.
Comment: Unfortunately, saying repeatedly that you are new to coding won't help us help you. instead, look up how to use CSS classes. It's all you need for this.
Comment: What effect are you looking for?  Does your page have HTML or is it a pure CSS site?
Comment: Why couldn't you create a certain class for the images you want to change and leaving that class out for the ones you do not want to change?
Comment: Hi there - Thanks for replying to my post - I believe it's a CSS code: http://www.thedistancelive.com/kind-words << the images turn into circles and rotate.. I would like for all but one image (the image right at the bottom of the page) to be normal, and not affected by the code.

Hope that makes sense :)
Comment: Hi Thomas Byy, I'm very new to coding, sorry i should have mentioned this in my post :)
Answer: A quick way to do it would be a css selector img:not(.not-affected-img) and add the .not-affected-img class to the images that shouldn't be affected.
Although you should actually add a class to the changing images:
.image-effect:hover {
  transform: rotate(10deg);
}

Comment: Hi Gabriela, Thanks for your reply :)

Could you walk me through this please?, I'm sorry Im completely new to this..

Sophie x
Comment: In your html you should add the class to the images you want to affect:
``
Answer: You can use the :not() CSS pseudo-class to not include an element. For example:
img:not(.dontselect) {
  // styles for all imgs EXCEPT .dontselect
}

Comment: Hello, thanks for your reply - I;m very new to coding so please bear with my uneducated questions.. How would i target the specific image please? and when i have where would i put this into the code ?
Comment: @SophieJones No problem; you would put this into your CSS styles and to target the specific image, you would need to have a way to identify it, such as its ID. Before the :not(), you need to put all of the elements you want to select, such as img, and inside the parentheses, you need to put the element(s) that you don't want to apply style to, such as #imageID. Hope that helped.

Affect all but one image with CSS code


How can I reclaim heat from an enclosed furnace room?

Question: Our home has two furnaces (oil fired hot air) and an electric water heater in an enclosed room (approx 6'6" x 9').  Three walls of the room divide it from the remainder of a finished basement, the fourth is an outside wall that includes a vent for combustion air intake.
In cold weather, especially when both furnaces run frequently, the room becomes quite warm -- into the 90s (F) at times.   I'd like to be able to divert some of this heat into the house without leaving the door open (which is quite effective, but inconvenient, as it opens into a spot that we often walk through).   I've already sealed as many air leaks in the ductwork as I can find (a total of four zones are served by the two furnaces, so there is a lot of sheet metal in there), I think a lot of remaining heat is being radiated from the furnaces themselves and the flue pipes (they are single-walled until they exit the room).
I'm thinking of putting  a pair of vents -- one high, with a thermostatic fan to blow the warm air into the room, and a low one, to balance the airflow -- in the wall shared with the office.   Outside of heating season, the vents could be closed to prevent outside air (from the combustion air intake vents) from circulating into the office.
The only specific risk I can see would be the risk of CO being pulled into the room if there is a furnace failure.   We have working CO detectors in the house, and I suspect it would be circulated throughout the house anyway due to leaks in the return ducts (around the filters, for example), so I'm not sure if this adds risk or not.   I know that furnaces in many homes I've seen are not in enclosed rooms, so perhaps I'm overthinking this.
Answer: Another alternative would be to install a door with louvers in it to allow the air to circulate.  It could be a simple door with just one vent, or a full louver door like the one below..
Comment: The problem is that when the furnace isn't running, the room would be filled with cold combustion air.
Comment: I don't think I understand your comment.  What is the difference between having a furnace in a room with a vented door compared to an unfinished basement?
Comment: The difference is if you're using the basement as living space or not.
Comment: Where I live this happens all the time.
Comment: I'm not following you. A furnace need combustion air. In a basement, it can draw that from inside the house...where you'd want the louvered doors like that. Alternatively, you can add a vent to the mechanical room and it will use outside air for that...in which case you don't want a louvered door.
Comment: This may be a stupid suggestion, 2 actually. Can additional insulation be added to the ductwork to minimize heat losses? It might even be worth while to have an HVAC company come in to help gain access to add insulation.   Next is probably a stupid suggestion, and others please chime in:  Instead of sucking the air out of the room, risking pulling CO with it, would it be practical to blow air INTO the room with a vent for warm air to exit? That would minimize the chance of interfering the the exhaust of the furnaces because the room would be slightly pressurized.
Answer: Do NOT power-vent that room into living space. You never want to vent a room containing combustion devices into living spaces...as you state, that's asking for CO problems. It's not an issue of the furnace being defective, it's an issue of you sucking exhaust out of the normal path (the chimney) due to negative pressure.
You could get around this by using a direct vent/intake system where it becomes a completely closed circuit (furnace draws directly from outside).
I'm not an HVAC specialist, but a 90 degree room seems to me that there's something else amiss here...like maybe your circulating fan is underpowered?
Comment: Our furnace room was like that due to bad insulation on the hot water pipes. Another thing to check.
Comment: On the temp in the room, I think it's a combination of the flue pipes and numerous places where small amounts of air leak from the ductwork. Also, each of the three zone dampers has a slot where the actuator ahem goes into the duct; I think they account for a fair amount.
Comment: @AlexFeinman - Hot water pipes are insulated and the tank is fairly new, so reasonably well insulated, I think.
Comment: If you have leaky ductwork...fix that. Get some proper metal tape (not duct tape) and seal all the seems/holes.
Comment: @DA01 - I've sealed all that I can get to.  Biggest leaks were around the condensate drains from the A/C and the duct-mounted humidifier.   What remains now are relatively small, except for the slots the actuator arms for the zone dampers use.   Because the two furnaces are side-by-side and have a wall directly behind them, there's no access to a lot of the sheet metal to check for possible leaks.   The metal tape is great, btw.
Comment: Mastic gives better performance than the metal tape.
Comment: I see how sucking air from the furnace room (negatively presurizing the furnace room) could defeat the furnace conbustion vent and bring CO into the house.  What about instead blowing air from the house, INTO the furnace room?  That might be quieter too, and should not defeat the furnace's combustion vent.  Get a door with two vents on it, put a can on the bottom one on the inside of the mechanical room, blowing INTO the mechanical room.  Any positive pressure left over after combustion gas exits would come out the top vent into your living space, heating the house.  Pros/Cons?
Answer: I would exchange heat passively, with something like the louvered door suggestion above.
Any use of a fan could, as suggested, introduce CO into your living space, or worse damage your furnaces if the exhaust is not allowed to exit properly.


Pascal program does not show maximum value

Question: Please help me my program just keeps on displaying the last name and number here is the program.
I really dont see what is wrong here but I do hope that you guys may see it please really need some help its killing my brain
Var
Counter:Integer;
MaxValue:Integer;
NumofVotes:Array[1..4]of Integer;
ChristianName:Array[1..4]of String;
Surname:Array[1..4]of String;
WinnerFName:String;
WinnerSName:String;
WinnerParty:String;
CandidateParty: Array[1..4] of String;

begin
  FOR Counter:= 1 to 4 Do
  If Counter= Counter Then
  begin
Writeln ('Please enter Christian name of Candidate ', Counter, ':');
Readln (ChristianName[Counter]);
Writeln ;
Writeln ('Please enter Surname of Candidate ', Counter, ':');
Readln (Surname[Counter]);
Writeln ;
Writeln ('Please enter number of votes received by Candidate ', Counter, ':');
Readln (NumOfVotes[Counter]);
Writeln ;
Writeln ('Please enter party of Candidate ', Counter, ':');
Readln (CandidateParty[Counter]);

  end;

  IF Counter = 1 THEN
begin
MaxValue:= NumofVotes[Counter];
WinnerFName:= ChristianName[Counter];
WinnerSName:= Surname[Counter];
WinnerParty:= CandidateParty[Counter];
end

ELSE
IF (NumofVotes[Counter]>MaxValue) THEN
begin
WinnerFName:= ChristianName[Counter];
WinnerSName:= Surname[Counter];
MaxValue:= NumofVotes[Counter];
WinnerParty:= CandidateParty[Counter]
end;
Writeln ;
Writeln ('The winner of the elections for this constituency is:');
Writeln ('FirstName: ', WinnerFName, ' Surname: ', WinnerSName);
Writeln ('From the ', WinnerParty);
Writeln (WinnerFName, ' has won with ', MaxValue, ' votes');
Writeln ;
Writeln  ;
Writeln ('Press <Enter> to end');
Readln  ;

end.

Comment: If you properly format your code, you'll be able to see (by the level of indent) that the flow doesn't go quite like you think it does. **Learn to format your code** so you can read it and follow the execution path. (The **emphasis** is because this has been said here hundreds of times, and no one ever seems to notice it. It gets rather frustrating having to repeat yourself over and over again.) With that being said, **learn to format your code properly**. :-) For a clear example of why this is important, see [this answer](http://stackoverflow.com/a/23681072), which I didn't write.
Comment: `If Counter= Counter Then` .. what kind of a test is that? A Counter is always a Counter.   `IF Counter = 1 THEN` .. you can't use 'for' loop index variable after the loop in pascal. Even if you could, how could it be '1', the last time it was '4'.
Comment: I did that because when I didn't do that the program came up weird it displayed all four questions at the same time instead of displaying them sequentially
Comment: Sorry I just took that out and it still works thanks much but what about it no testing for the maximum value??
Comment: Thanks much sir i'm just in high school trying to do some programming cuz I really like programming but i seemed to have got it to work here is what I got
Comment: @user - Counter is not 1. So take out the 'if counter = 1' block. What do you have? 'IF (NumofVotes[Counter]>MaxValue) THEN'. But you never assigned anything to 'MaxValue'. And there's no loop to compare anything after you read the values.
Comment: Sorry looks like i cant put it in inless its 8 hours after but ill show after
Comment: Also, not to nitpick but a Christian name is one given at baptism, traditionally. Not everyone is baptized, nor is everyone even of the religion where that might be a consideration.
Answer: The code seems to lack one pair of begin ... end keyword. As a result, the for instruction ends at the first end keyword, that is just after reading all candidates data. Then the Counter is 4 and the comparision in IF Counter = 1 fails – execution proceeds to ELSE. There the uninitialized MaxValue is probably zero, so the fourth NumofVotes is greater than that, which eventually causes the fourth candidate to be printed.
To make the code do what you expected, add begin just after the FOR ... DO and close it with end just before Writeln ; Writeln ('The winner ... is:');


Find the sum of the series?

Question: I need to find the sum of this series, where k is from 1 to infinity?
$$\sum_{k=1}^\infty\frac{k^3+6k^2+11k+5}{(k+3)!}$$
Comment: $$k^3+6k^2+11k+5 = (k+3)(k+2)(k+1) - 1$$
Comment: @Nick: It converges. There is a factorial at the denominator.
Comment: It converges, use the sum to infinity formula!
Comment: @ClementC.: Slip of tongue :D
Answer: That series can be written:
$$\sum\limits_{k=1}^\infty\left(\frac 1{k!}-\frac 1{(k+3)!}\right)$$
so it is $(e-1)-(e-1-1/1-1/2-1/6)=5/3$
Answer: HINT:
As the numerator is cubic, we need to express  $\displaystyle k^3+6k^2+11k+5$
as $1\cdot(k+3)(k+2)(k+1)+b_1(k+3)(k+2)+b_2(k+3)+b_3$ where $b_i$s are arbitrary   constants
Observe  that we have to start with $k+3$ as it is there in the factorial of the denominator.
Had the numerator been square polynomial like $A k^2+Bk+C$ with the denominator $(k+r)!$
we had to start with $A\cdot (k+r)(k+r-1)+a_1(k+r)+a_2$

Here we have
$$\frac{k^3+6k^2+11k+5}{(k+3)!}=\frac{(k+3)(k+2)(k+1)+b_1(k+3)(k+2)+b_2(k+3)+b_3}{(k+3)!}$$
$$=\frac1{(k)!}+b_1\frac1{(k+1)!}+b_2\frac1{(k+2)!}+b_3\frac1{(k+3)!}$$
Multiplying either sides by $(k+3)!$ we get $$k^3+6k^2+11k+5=(k+3)(k+2)(k+1)+b_1(k+3)(k+2)+b_2(k+3)+b_3$$
Methods to determine $b_i$s:
Method $\#1:$
Set $k+3=0$ to find $b_3$
$k+2=0$ to find $b_2$ in terms of $b_3$ which is known
and so on
Method $\#2:$
Compare the coefficients of the different powers of $k$

Find the sum of the series?


Wicket calling js based on condition

Question: I am trying to solve the following problem, off course unsuccessfully.
On my website I have form with DataTextField where user put date.
When user confirms (AjaxButton) the form I need to find out the date and if the date is from "future" I need to call javascript(confirmation dialog).
The question is How to call js when condition is done?
I am helpless and appraise some help.
Comment: Please show the snippets from your code
Answer: Without any code fragments it's hard to tell you what goes wrong but basically:
<code>onSubmit(AjaxRequestTarget target)
{

target.appendJavaScript("if(confirm('Date in future!')){}; return;");

}
</code>

Wicket calling js based on condition


Use Validator/Dive to enter an array and validate nested structs in go

Question:
type myType struct {
        value      int               `json:"value"`
        Name string            `json:"name" validate:"required"`
        URL     string            `json:"URL" validate:"required"`
        args     []otherType  `json:"args" validate:"dive", "required"`
}

type otherType struct {
  name string `validate:"required"`
  origin string `validate:"required"`
}

err := paramsValidator.Validate(someInstantiationOfThisStruct)

Hello there! I'm a tad bit stumped on using validator's dive feature. This specific combination of validation scheme isn't present in the documentation for the validator, and I was unable to get it working with a little bit of tweaking.
I would like to simply enter the args array in the primary struct, and validate each of two sets of otherType. However I don't quite understand how this is supposed to transpire.
I understand dive incorrectly and it's not working of course, as the validator is unable to determine incorrect validations using Validate().
Is there any particular thing I'm doing wrong? In general how should I approach evaluating and validating args that are in an array?
Answer: I came searching for the answer here but the solution didn't work for me.
In order to validate nested struct using go-playground/validator add dive.
So add below code to the nested struct at top level
`validate:"required,dive,required"`

Note: add without spaces, also make sure the fields are exposed (use PascalCase) to package incase u importing the struct
type myType struct {
        value      int               `json:"value"`
        Name string            `json:"name" validate:"required"`
        URL     string            `json:"URL" validate:"required"`
        Args     []OtherType  `json:"args" validate:"required,dive,required"`
}

type OtherType struct {
  Name string `validate:"required"`
  Origin string `validate:"required"`
}

Note: This validation is as per my use case where i want Args to be required and also want it to be exposed to other packages. Just trying to help other who come searching for the same issue as "Dive" is not documented properly in go/playground documentation
Answer: I was able to figure it out. I am so sorry for even posting! I was stumped for thirty minutes, but the solution was not that particularly bad.
type myType struct {
        value      int               `json:"value"`
        Name string            `json:"name" validate:"required"`
        URL     string            `json:"URL" validate:"required"`
        args     []otherType  `json:"args" validate:"dive", "required"`
}

type otherType struct {
  name string `validate:"required"`
  origin string `validate:"required"`
}

is the updated code. There was a missing , between "dive" and "required", and I had posted code that read
`validate: "dive, required"

dyslexia sorry! :(


How to calculate square of a number?

Question: I have two text boxes. One textbox for input and other for output. when number entered in first textbox by button click then i want to find square of that number in second textbox by clicking Square button. But i am not able to get the desired result. Nothing is displayed in second textbox when Square button is clicked.
Here is Code snippet:
@Html.TextBoxFor(model => model.textBox, new {  @readonly = "readonly" })

@Html.TextBoxFor(model => model.textBox1, new {  @readonly = "readonly" })
<input name="button" type="submit" id="btntwo" value="2" />

<input name="button"  type="submit" id="btnthree" value="3" />

<input name="button" type="submit" id="btnfour" value="4" />
<input name="button" type="submit" id="btnSqr" value="Sqr" />

Here is code snippet for controller:
if (button == "Sqr")
{
    model.value1 = model.textBox;
    model.textBox1 = (float.Parse(model.value1) * float.Parse(model.value1)).ToString();
}

Note: I have only provided the code which is required to solve the issue.
Comment: Your title is a bit misleading, your second snippet shows you know how to calculate the square of a number. Does setting a breakpoint show the correct value?
Comment: Please fix the title of this question. You obviously do know how to calculate the square of a number, what you're having problems with is displaying a number.
Comment: Did you return model to view again?
Comment: Include `@Model.textBox1` in your view and check if its returning the correct value
Comment: Thanx to everyone. My model was not returting . I have fixed it and get desired result
Answer: Here is my assumptions of what you are doing "IF You Use Server Side Solution"
public ActionResult FindSquare()
    {
       SquareModel model = new SquareModel(); // model contains textbox, textbox1
        return View(model);
    }

And when you submit form on button click
public ActionResult FindSquare(SquareModel model, FormCollection collection)
 {
     if(!string.IsNullOrEmpty(collection["button"]) && collection["button"].ToString() == "Sqr")
     {
         double value = Convert.ToDouble(model.textBox);
         var result = value * value;
         model.textBox1 = Convert.ToString(result);
         return View(model);
     }
 }

Edit:
Remove removeonly from your view page.
Answer:
Use Client Side Script to do it easily

$('#btntwo').click(function (e) {
var num = parseInt($('#textBox').val());
$('#textBox1').val(num*num);
 return false;
});

If you want to continue in server side, you have to remove  @readonly =
  "readonly".
Comment: I know it is bit easier in client side. But i want to do in server side. Because i have done complete work for arithmatic operations. So anyone help me out to get out of this.
Answer: I suspect the issue you're having is related to the fact you've got two textboxes (textBox and textBox1), and both are read-only. Nothing can be changed, so perhaps the controller is not firing at all?
I'd also be worried your controller implementation is not wired up properly. You've provided too little code to validate the mainstay failure points for postback processing are not the cause.

How to calculate square of a number?


Style tab-selected element?

Question: I have a menu bar with drop-down sub menus that I've created with CSS. Everything works just fine when I'm using a mouse, but if I use the tab key to select the menu items, the sub menu won't open and I'm unable to go to any of the sub pages without using my mouse.
Is there a way to open the sub menus with the tab key without using JS?
Here's a JS Fiddle
HTML

        Page 1

        Page 2

                Sub Page 1

                Order Savings

        Page 3

CSS
#main_menu{
    background: #000;
    display: inline-block;
    padding: 10px;
}

#main_menu > span{
    display: inline-block;
    vertical-align: top;
}

#main_menu > span:not(:first-child)::before{
    content: "|";
    color: #FFF;
    font-size: 20px;
    font-weight: 700;
    margin: 0 6px;
    vertical-align: top;
}

#main_menu a{
    color: #FFF;
    font-size: 20px;
    font-weight: 700;
    text-decoration: none;
}

#main_menu > span > span{
    display: none;
}

#main_menu > span:hover > span,
#main_menu > span:focus > span,
#main_menu > span > span:hover,
#main_menu > span > span:focus{
    display: block;
    padding-top: 1em;
    position: absolute;
    z-index: 1000;
}

#main_menu > span > span > span > a{
    background: none repeat scroll 0 0 #000;
    border: 1px solid #fff;
    display: block;
    padding: 5px 7px;
}

#main_menu > span > span > span > a:hover,
#main_menu > span > span > span > a:focus{
    border-color: #00cc00;
    color: #00aa00;
}

Comment: I can't even tab onto that frame
Comment: @Huangism Click on the "Page 1" link, and then you can tab to "Page 2".
Answer: When tabbing the focus goes to the anchor element not to the span. Updating the CSS rule to use the a selector, you get
#main_menu > span:hover > span,
#main_menu > a:focus + span > span,
#main_menu > span > span:hover,
#main_menu > span > a:focus + span{
    display: block;
    padding-top: 1em;
    position: absolute;
    z-index: 1000;
}

Here is the JSFiddle.
Comment: I can't believe I missed that. It seems to be working, but I can't tell because once I tab to an item in the sub menu, the sub menu vanishes. Do you know how to keep that from happening? I've tried it in Firefox and Chrome.
Comment: Nevermind. It's apparently not possible yet, but will be simple once  [`:has()`](http://dev.w3.org/csswg/selectors-4/#relational) from the level 4 CSS selectors sees browser support, which will hopefully be soon.
Comment: Yep. Couldn't find a way to get this working without Javascript. :)

Style tab-selected element?


Is there a better way to remove a column from a tensor in tensorflow?

Question: I'm working on an image clustering problem that involves deleting columns. The only way I can think of is using tf.concat to concatenate two slices of the original tensor, and some whitespace. I have to do this many times and I'm worried that it may be slow. Is there a better way to do this?
new_tensor = tf.concat(1,
     [tf.slice(data, [0, 0, 0], [to_remove - 1, image_size, 1]),
      tf.slice(data, [to_remove, 0, 0],
                     [image_size - to_remove - 1, image_size, 1]),
      tf.zeros([image_size, 1], tf.float32)])

Comment: Could you paste your code so that other people can understand your intention?
Answer: You can use tf.gather, which better corresponds to what you are trying to do, but honestly I'm not sure if it will be any faster:
ind = tf.concat(0, [tf.range(0, to_remove), tf.range(to_remove + 1, data.get_shape()[0])])
removed = tf.gather(ind, data)
zero_filled = tf.concat(0, [removed, tf.zeros([image_size, 1], tf.float32)])

Btw, in slice you can use -1 to denote "till the end of this dimension".


prevent any input containing quotes or brackets

Question: I need to prevent a user to create any input containing any quotes or brackets
<code>    if(strpos($str, '"') !== false ||
    strpos($str, "'") !== false ||
    strpos($str, "<") !== false ||
    strpos($str, ">") !== false ||
    strpos($str, "(") !== false ||
    strpos($str, ")") !== false ||
    strpos($str, "{") !== false ||
    strpos($str, "}") !== false){
        echo "input is not allowed";
    }
</code>
1 - is there a shorter way to write this
2 - is this an enough safe way to sanitize inputs before place them inside a mysql database (using prepared statements)
Comment: "2 - is this an enough safe way to sanitize inputs before place them inside a mysql database" NO! Read about prepared statements
Comment: For 2 look at [this](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php).
Comment: Remember that "sanitizing" is generally for cosmetic things, like trimming excess spaces or removing non-UTF-8 characters, not things like injection or escaping protection. Each context you use this data in has wildly different constraints and threat vectors. Use the escaping method for any given context *if* and *when* you're in that context, be it HTML, JSON, SQL or otherwise.
Comment: So what? That doesn't help an attacker. If they can `$_POST` something, and you put that something in the `:abc` placeholder, then that's all they can do: Exactly what you allow them to. They can't put in arbitrary SQL. The name of the placeholder is largely irrelevant, even if you do `execute($_POST)` and just hope for the best.
Comment: @kuh-chan - I use prepared statements of course, but still don't need quotes and brackets inside the database
Comment: @qadenza If you do not need those characters I could recommend to use [CHECK constraint](https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html) or [triggers](https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html)
Comment: @Luuk - I don't need those characters but I need to say the user that he needs to remove those characters because some of the input can be his username or password
Comment: @qadenza: A good [note](http://www.sussex.ac.uk/its/help/faq?faqid=839) on the screen about which characters should be sufficient. Implementing the check database-side will REALLY prevent those characters from entering the database.
Comment: This kind of code, regardless of the intent, makes it look like you're trying to prevent XSS or SQL injection using the ham-fisted, completely unreliable method of just not allowing certain characters. Why are you forbidding single quotes? Do you want someone with an apostrophe in their name being forbidden from expressing their name properly?
Comment: In your question, you should specify the purpose of "prevent(ing) a user to create any input containing any quotes or brackets".
Comment: @tadman - can you give me any example where a database is attacked by a string `not-containing` quotes and brackets
Comment: Some of the vectors involve using things that are quotes as far as MySQL is concerned, but aren't quotes as far as `"` is concerned, so-called "Unicode smuggling". Tools like [sqlmap](http://sqlmap.org) have a huge bag of tricks that involve working around naïve SQL injection protection like stripping characters. The only reliably safe way is *placeholder values*.
Comment: This code is effectively worthless. It will reject `James O'Malley` but not `James O'Malley` or `"Eat My Shorts"` or `⋜Ha!⋝`.
Comment: @tadman - placeholder value - i suppose it can also be compromised - using brutal force (guessing) - for example
Comment: How could a placeholder value be brute forced or compromised? It will *only* ever go to where it's intended to go, and will never run arbitrary SQL commands. The way the MySQL protocol is structured these values are sent over separately from the SQL statement itself, there is no way they can get confused with SQL code.
Comment: @tadman - `$sql = "insert into table (name) values(:abc)"` - `:abc` could be guessed - isn't it?
Comment: @tadman - but the value you placed inside `:abc` is later placed into a table during `execute()` proccess
Comment: Which is what you've allowed them to do by virtue of your `execute()` call. If you don't want them to have that control, don't take their input or provide a binding for the input to go. The name of the placeholder doesn't really matter, what does matter is what you bind that placeholder to, and you have *full* control over that.
Comment: @tadman - I don't have full control - because I must bind the value of users input and not any other value
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/225840/discussion-between-tadman-and-qadenza).
Answer:
Yes, using Regex:
<code>$str = 'Test {';
$exp = '/[\"\\\'\<\>\(\)\{\}]/';
if (preg_match($exp, $str)) {
  die("Input is not allowed");
}
</code>

No. You should take a look at PreparedStatements.
Answer: Try it this way.
<code>$pattern = array('/[^0-9a-z]+/i', '/[^0-9a-z]+(?=$)/i');
$replacement = array('', '');
$subject = trim(str_replace(" ", "", $str));

$new_str= filter_var(preg_replace($pattern, $replacement, $subject), FILTER_SANITIZE_STRING);
</code>
What ever that's not in the pattern will be removed...