What to use to build an enclosure for projector screen case?

Question: I need to create an enclosure for a projector screen case mounted on the ceiling. The size is 50 inches wide, 4 inches high, 4 inches deep.
Requirements:

The enclosure is just for visuals, just to hide the plastic case of the projector screen, so it creates a more "built-in" looking.
It will be finished just like the ceiling: white.
Must be lightweight. I can't use thick wood (probably your first thought!). I was thinking about some kind of very thin wood (I remember seeing them before, they are a little flexible but stay straight if no force is applied). Remember the idea here is just to hide the projector screen case, nothing else. So less is better!
It must be easily removable. It means this enclosure will not be attached to the ceiling, but will just use something to attach it to the projector screen case (that's why it needs to be lightweight). Don't worry about how to attach it, if it's lightweight even a velcro will make it. It is because the projector screen is battery powered so occasionally it is necessary to replace the battery.
Ideas about how to finish (specially the sides) so it looks like something built to the ceiling.

The whole idea is just to hide the plastic casing.
I'm looking mainly for ideas about what materials to use to create the enclosure, what to use to connect the sides, what to use to finish it.
Thank you!
Comment: How will you attach it to the ceiling? What are the dimensions of the screen? What are the dimensions of the space in which the enclosure should live? It's always best to start with a drawing containing the initial measurements.
Comment: i would use foamcore and magnets or command strips. you might need to go to 1/4" drywall for the long run, as foam core usually maxes out at 48.
Comment: @DavidD Thanks, I'm more interested in knowing what materials to use to build the enclosure. My question is not about how to attach it. I provide the dimensions in the first paragraph.
Answer: Think about running down to you hobby shop or home store and checking out their supply of balsa wood. That stuff is really light and easy to work with. It comes in many different sizes, sheets and square stock. It can be glued with regular wood glue or super glue and can be painted to match the ceiling.
Comment: Great! Was looking for recommendations like that! I'm not familiar with the names, so I don't even know how to search for them. If you have any other idea, please share! Thank you!
Comment: Yup, balsa wood sounds ideal for this situation. You can cut it with a sharp hobby knife or pocket knife, so it doesn't even require any special tools. You do want to be aware that it's somewhat brittle - a 50" long piece will want to go all wobbly on you and will likely snap if not handled gently. It may also be a bit pricey to get that much balsa, but it is an _excellent_ option.
Comment: @FreeMan I've seen them before, I remember exactly what you described. Managed properly, it is the best option I believe.
Comment: Would you use wood glue or maybe metal L bracket to secure the sides? Can I just paint them with white paint or need anything extra?
Comment: @igorjrr both of your questions are addressed in the answer above.
Comment: @igorjrr  Glue or Velcro...  or double sided tape. I doubt you'd need the metal l brackets.
Comment: @FreeMan and JACK the lumber I use does not carry balsa, but has Lauan wood 1/8 thick. Are you familiar with that, would it work for me? Thanks for helping!
Comment: @igorjrr  I'm unfamiliar with Lauan wood but I have to imagine it's heavier than balsa wood.  Try a few other locations, home stores, hobby, arts and crafts.
Comment: @igorjrr Highly unlikely you'd find balsa at the home improvement center. I would consider it somewhat unusual to find it at a lumber yard. It is, in the US at least, well within the realm of hobby/model making and or arts & crafts. Luan is usually the veneer used on interior doors, I wouldn't think it would have much structural strength and would probably be more floppy than balsa. With balsa, you could probably go 1/4" for strength and still be about as light as the Luan. Which you choose, though, is up to you
Answer: 1/8" (or 3mm) melamine faced "hardboard" (what Masonite® is but that's a brand name rather than the generic product.) Thin, fairly light, will need a saw to cut it, already white (on one face.)
Or skip the building supply store, head to the art supply store, and get some "foamcore" used for making 3-D architectural models (among many other uses) - cuts easily with a sharp knife, already white, very lightweight.
Comment: Thanks for the foamcore idea! I'll certainly check, seems to be a lightweight material that could work. Would you say it blends well with a white ceiling (that is, won't call too much attention)? If wood I know would look good, but I'm not familiar with the foamcore. Thank you!
Comment: Foamcore is another excellent suggestion!
Comment: if you go foamcore, you can easily build a box by gluing wood or styrofoam blocks in the inside corners. You can also make it look quite nice (hiding the layered edges) by gluing outside corner trim along the edges. A lot of my house is foamcore (eg wainscoting panels) and 3d-printed plastic, and I often joke: "Hey watch out! that's load-bearing foamcore!"...
Comment: @dandavis Thank you! Could you please clarify the "...by gluing outside corner trim". Sorry, I could not understand what outside corner trim refers to.
Comment: trim is long skinny pieces of wood/pvc used to decorate a house. Inside corner trim includes quarter-round and cove, which you could use to hold the box together. Outside corner molding looks kind of like two yardsticks glued together in an elbow. google "outside corner trim" for examples and shopping links.


gem install bundler error

Question: I am newbie here. When I tried to install gem install bundler, it gave me
ERROR:  Could not find a valid gem 'bundler' (>= 0) in any repository
ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
    bad response Forbidden 403 (http://rubygems.global.ssl.fastly.net/latest_specs.4.8.gz)

So I need to install 'bundler'?
Comment: *I think*, you should ask a question, that reflects what you actually want. "what do you think?" looks like a meta-question. See [How do I ask a good question?](/help/how-to-ask).
Comment: The problem was caused by an [internet connection that wasn't working](https://askubuntu.com/questions/674056/gem-install-bundler-error/674062#comment975517_674062).
Answer: Doing some digging, I found that your issue is related to being behind a proxy or firewall or having a virus.
The fastest workaround is to change your gem source address from https://rubygems.org to http://rubygems.org with the following command:
gem sources -a http://rubygems.org

confirm withy and retry.
Comment: i terminated my wireless connection and put my internet usb instead and it is working perfectly. Thanks

gem install bundler error


Compute a measure of "near multiplicity" from a list of noisy values

Question: Question
I posted this question on StackOverflow before but someone advised me to ask it there because it looks like a numerical algorithm problem.
Let us say I've got a list of values which have a common multiple greater than 1. For example, let us take the multiple to be 3 and form a collection of multiples of this value:
harmonicList = [3,6,6,3,3,9,27,3,15,18,9]

Now I add some noise:
harmonicList = [ v + (random() * 2 - 1 ) * 0.1 for v in harmonicList]

I'm searching for an algorithm that will return a number near 1.0 when the items in the list are near to being multiples of a common value but near 0.0 when the numbers are not near to being multiples -- such as, for example when the list is a collection of prime numbers.
Is there such a measure of "near multiplicity"?
Why I want to solve this problem
I'm currently trying to detect Chessboard in a screenshot using Hough Transform. Sometimes the case is ideal, and it works very well :

But sometimes not :

I would like to detect the cases where there is a lot of aberrations. Thus, my idea is to compute the intersections of the lines detected, and create a collection of length  (only if the lines where horizontal or vertical). If the detection was good, I know that there will be a great "harmonicity" inside this collection I can then use that algorithm and a threshold.
Comment: Is this something principle component analysis is intended to solve? https://en.wikipedia.org/wiki/Principal_component_analysis
Comment: I've no idea but will have a look
Comment: EDIT: I've moved my comment to an answer below.
Answer: You can look at this as a maximum likelihood estimation problem. The general idea is to find parameters which make the model fit the data in the sense that the data have greatest probability under the model for the specified parameters. Maximum likelihood is a very widely used approach for fitting statistical models.
In this case, your model is p(x) = sum of p_1(x, mean = k times a minus b, standard deviation = something small) over k from 1 to number of multiples, where a is the spacing between multiples and b is an offset, and p_1 is the Gaussian density exp(minus 1/2 times ((x minus mean)/(s.d.)) squared)/(s.d. times sqrt(2 pi)).
Compute log likelihood, i.e. log(p(x_1) times p(x_2) ... times p(x_n)) = log(p(x_1)) + ... + log(p(x_n)) where n = number of data which is typically easier to handle numerically than the equivalent likelihood. Note log likelihood is a function of a and b, so maximize log likelihood over a and b to find the "best" values.
EDIT: Here's an implementation of the formulas above. I'm using Maxima, a computer algebra system for this. See: http://maxima.sourceforge.net
Here is the Maxima program:
p_1(x, mean, sd) := exp(-(1/2)*((x - mean)/sd)^2)/(sd*sqrt(2*%pi));

p(x) := sum (p_1(x, k*a + b, sd), k, 0, k_max);

log_likelihood(xx, a, b) := lsum (log (p(xx1)), xx1, xx);

Here are the data for the example stated in the question:
harmonicList : [3,6,6,3,3,9,27,3,15,18,9];

harmonicList : map (lambda ([v], v + (random(1.0) * 2 - 1 ) * 0.1), harmonicList);

These are some additional parameters. k_max is the maximum number of multiples to look at; that can probably be estimated by looking at the range of the data. sd is the standard deviation of the noise. It should probably be stated as a fraction of a, the distance between multiples.
k_max : 10;
sd : 0.2;

Here is a contour plot of the log likelihood, given harmonicList as the data.
contour_plot (lambda ([a, b], log_likelihood (harmonicList, a, b)),
              [a, 1, 5], [b, 0, 3],
              [gnuplot_preamble, "set cntrparam levels 12"],
              [grid, 120, 120]);

Here is the resulting contour plot:

Note that the greatest values (a little above zero) are in the vicinity of (a = 3, b = 0) and (a = 3, b = 3).
EDIT 2: Here is my response to the question about answering the question of whether the data could be fit by any multiplier.
You could approach that question like this. The plausibility of "data can be fit by some multiplier, offset pair" can be modeled as p(model | data) which is
p(model | data) = p(data | model) p(model) / (p(data | model) p(model) + p(data | no model) p(no model))
This shows what terms one needs to pull together to get a complete answer, namely p(data | model), p(model), p(data | no model), and p(no model).
About p(model) and p(no model), since it's possible that there is no such multiplier and offset, we have p(model) < 1. This might be estimated as the base rate of data sets which can be modeled by multiplier and offset. About p(data | no model), this is probably something like a uniform distribution.
As for p(data | model), note that p(data | model) = p(data, model) / p(model). Now p(data, model) =  integral(p(data | a', b') p(a', b' | model) over all conceivable values a', b' of multiplier a and offset b). Note that p(data | a', b') is, by definition, the likelihood of model = (a', b') given the data. Remember that likelihood = exp(log likelihood).
Here p(a', b' | model) is one's prior over the parameter values, assuming that the data are accounted for by some multiplier, offset pair. Are all parameters equally probable a priori? If so p(a', b' | model) is a constant. My guess is that some values are more probably than others due to the constraints of the problem -- since the images are screenshots, there are probably limits on what the multiplier and offset can be, and probably some values are less probable given those limits.
EDIT 3: Here is the contour plot for primeList as given in a comment below.
Comment: I've updated my answer to talk about an answer to that question.
Comment: @snoobdogg: I posted a Python implementation of Robert Dodier's idea [on stackoverflow](https://stackoverflow.com/a/48833918/190597) since it is only about implementation, not theory.
Comment: @snoobdogg I've pasted in a contour plot for primeList. Note that the greatest values are something like -100 instead of 0. That means that the multiples model is a very poor fit for the primeList data compared to the harmonicList. About Maxima, the project hosting site (Sourceforge) is updating their data center but hopefully that will be resolved soon.
Comment: Is there a way to turn the log likelihoods into a single number which is a measure of how likely the data came from multiples of an underlying value?
Comment: What will happens if instead I use a  sequence where there is a poor multiplicity ? like primeList : [2,3,5,7,11,13,17,19,23];
primeList : map (lambda ([v], v + (random(1.0) * 2 - 1 ) * 0.1), primeList); how is the countour plot ? I could try it myself but I can't download maxima today, I get the following message when trying to access their page : "Project web is currently offline pending the final migration of its data to our new datacenter."


Is it safe to use an HVAC system even though the duct wrap contains asbestos?

Question: In our rental house the furnace ducts are very dirty. We brought an expert to clean it, but he said he just won't do it because the tape around the ducts (in the attic) is probably asbestos.
After notifying the landlord, he got another company to have the material tested. The results came back, confirming that there is indeed asbestos in the tape. However, the test "results" also state that "as the material is on the outside of the ducting/unit, the asbestos material is not being subjected to the furnace air flow, and therefore is not causing a contamination issue, not a reason for concern".
Our concern is with the fact that the guy from the asbestos test company barely took a look at the duct system: he did not look inside the ducts, and did not see an area where the tape starts to crumble (in the attic, outside the duct). All he did was to take sample of the wrap material next to the furnace itself.
The questions are :

How can we know if the system is really safe to use? Is the braking tape a reason for concern?
Isn't the landlord supposed to make sure the heating system is in a usable condition? Currently he says that since the test indicates that this is not a concern, then he won't do anything. Also, he does not want to take care of cleaning it (even tough it hasn't been cleaned in years, possibly decades).
Suppose we do believe the conclusions of the test results. How can we get the system cleaned?

Related question:
Must I remove asbestos from my heating vents?
Edit:
Thanks for all the tips. I don't mind writing the check for a 2nd opinion test, but here's a breakdown of professionals that I spoke with:

HVAC cleaning companies: don't want anything to do with it.
Asbestos companies: don't understand what I'm talking about, and propose to take more samples and test them.
Other HVAC companies: "we don't clean ducts" / "We won't touch anything with asbestos" etc.

Any recommendations on companies that do systematic evaluation of the system (that has asbestos in it)?
Comment: Even though cleaning the ducts shouldn't release any Asbestos (IF done properly), most HVAC men will turn tail and run if they even hear the word, because they don't want to be responsible. In their mind, it is better lose $120 for a service call than a $120,000 lawsuit.
Comment: Tape crumbing in the attic, outside the duct, does not introduce asbestos into the INSIDE of the duct - unless, of course, you start tearing ducts apart. The best way to deal with known asbestos that isn't getting into the air is to Leave It The Heck Alone. Since neither tape nor wrap are used on the INSIDE of the ducts, there's no reason to expect asbestos to be there.
Answer: If you don't trust the expert brought in by the landlord, then you might want to pay to have your own expert validate your concerns.
As far as to what the landlord does and does not have to do, you'll have to review the lease and laws in your state.  At this point, he has paid for a report of a presumed expert that says the ducts are safe as is; it will be difficult to challenge this without an alternative expert opinion.
Answer: I would get an 2nd opinion report. And then based upon that report make a decision on whether to move or not. A report that conflicts with the one that the landlord contracted for should be strong grounds to get you out of any lease.
Answer: The test lab's report, undoubtedly reflects the scope of work for which the test lab was contracted. That was almost certainly along the lines of:

Obtain a field sample of the tape.
Test the field sample for the presence of asbestos

Given that scope, under the scientific method there is only evidence to support conclusions regarding hazards posed by the tape. The scope of the investigation does not provide a scientific basis for conclusions regarding the overall safety of the system or potential problems with indoor air quality.
The lab delivered what the Owner paid for and did not deliver what the Owner did not pay for. That's the way the lab makes money and retains clients.
If you want an investigation which is oriented toward systematically uncovering unknown problems, you've got to be the person writing the check.
Answer: There are a few routes to consider. (each escalating as you go down)
Get a second opinion
You're concerned the inspection isn't up to snuff and you might be at risk of getting exposed to asbestos. This is a valid concern that shouldn't be taken lightly, asbestos contamination kills people, simple as that.
You need to get a second opinion that YOU pay for. As other's have said if the property owner is paying there is a potential conflict of interest on the inspectors part. (though I doubt many inspectors wouldn't take asbestos seriously, it's just too dangerous legally speaking)
If the second inspection says there is potential for contamination you should have legal guidance and demand termination of the lease without penalty and get out NOW!
Request action taken or let off lease
Simply said, no one told you there was asbestos there. If your landlord is a decent enough person they might let you off your lease early, or if the asbestos is a VERY small amount might take the time to have it properly removed. Either way document what is said here. Just know unless local laws say otherwise the landlord has no obligation to help here.
Consult local building code
If the inspection checks out and you're still concerned or no longer desire to live in a building with asbestos consider getting in touch with local building code enforcement and ask about what the policies are about buildings with asbestos in them.
The rules here vary dramatically from place to place and can get pretty convoluted, but they tend to boil down to three basic plans...

Any building with asbestos in it built before a certain date are not subject to code related to the use of asbestos unless certain conditions are met. (essentially conditions with a high likelihood of contamination)
Buildings with asbestos in it built before a certain date are not subject to code related to the use of asbestos unless certain conditions are met, but may not be rented, sold, or leased until brought up to code.
Use of asbestos is a violation of code and once discovered you have only a set time frame to rectify the problem before you'll start to receive fines.

If your location falls into the first set then code won't be much help, if it falls under the other two you could request an inspection potentially invalidating your lease, and/or getting the asbestos removed.
The Legal Route
Asbestos is taken VERY seriously in most of the US. In many states there are VERY strict laws about what can be done with properties that have asbestos in them. Most states require potential tenants to be informed of asbestos being on the property prior to signing of the lease, failure to do so can make the lease invalid as well as potentially putting the property owner in legal hot water.
Now what YOUR local laws are could vary dramatically, before you say anything about breaking lease, legal action, etc. I would research your local laws and consult with legal representation about what your rights are here. The legal route is simply the least pleasant way of handling this, but if you're risking asbestos contamination your considering frustration against jeopardizing the health of anyone entering your property.


Coping CSV file from Gmail Attachment by name

Question: I want to only copy the CSV attachment to google sheets from an email.
The email has multiple attachments, in different file formats.
The attachment I want to copy over is consistently the same name in csv format.
I am using this code but its not pulling the attachment I want to copy to google sheet.
Can someone help me with this.

function getCSV() {

 var myLabel = GmailApp.getUserLabelByName("I-Data New"); // specify label in gmail
 var threads = myLabel.getThreads(0,1);
 var msgs = GmailApp.getMessagesForThreads(threads);
 var attachments = msgs[0][0].getAttachments();

 var csv =  attachments[0].getDataAsString();
 var data = Utilities.parseCsv(csv);

var a = data.length ;
var b = data[0].length;

var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = SpreadsheetApp.openById('12ApSC0WVn1sZxb9VF6_CZR9L5xuGY5WHMLyyGMc').getSheetByName('IData');
  sheet.getRange('A2:AM6026').clearContent();
  var range = sheet.getRange(2,1, data.length,data[0].length);
range.setValues(data);

}
Answer: Loop over the attachments and get the filename. Quick edit to your existing code:
function getCSV() {

  var myLabel = GmailApp.getUserLabelByName("I-Data New"); // specify label in gmail
  var threads = myLabel.getThreads(0, 1);
  var msgs = GmailApp.getMessagesForThreads(threads);
  var attachments = msgs[0][0].getAttachments();

  attachments.forEach(att => {
    const name = att.getName()
    if (name == "myFileName.csv") {
      var data = Utilities.parseCsv(att.getDataAsString());

      var sheet = SpreadsheetApp.openById('12ApSC0WVn1sZxb9VF6_CZR9L5xuGY5WHMLyyGMc').getSheetByName('IData');
      sheet.getRange('A2:AM6026').clearContent();
      var range = sheet.getRange(2, 1, data.length, data[0].length);
      range.setValues(data);
    }
  })
}

Comment: @RogerWareham good to hear. Please accept the answer so this topic is marked solved.


passing variable value to href argument

Question: I'm sure this is an easy one but I'm really stuck here..
This is the code

                                <a href="/update-user?id="

I need to pass the value that's gonna be in the id="id" to the href id and data-id
The table is populated by this function here
var i = 0;

function next(){
    i++;
    var value = $.ajax({
        type: "get",
        url: "http://localhost:3000/api/users",
        dataType: 'json'
    }).done(function (users) {
        console.log(users[i]);
        $('#id').text(users[i]._id)
        $('#sku').text(users[i].sku)
        $('#name').text(users[i].name)
        $('#type').text(users[i].type)
        $('#price').text(users[i].price)
        $('#shipping').text(users[i].shipping)
        $('#description').text(users[i].description)
        $('#image').html("")
    });
    return value.responseJSON;
}

Many thanks everyone!
Comment: IDs have to be unique. You can't use the same IDs in every row of the table.
Comment: Use classes instead. Then you can do `$('#tableid tr').eq(i).find(".id").text(users[i]._id)`
Answer: Give the anchor a class.

                                <a class="link" href="/update-user?id="

then you can access it and updates its href
`$("#table tr").eq(i).find(".link").attr('href', '/update-user?id=' + users[i]._id);

You can do similarly with the data-id attribute of the delete button.
Answer: Is this what u mean?
Only when there is 1 link on the page this will work, would advice you to use a class or id for the targeting. Like the way we did for .delete. Else every a href will be changed.

var i = 0;

function next(){
    i++;
    var value = $.ajax({
        type: "get",
        url: "http://localhost:3000/api/users",
        dataType: 'json'
    }).done(function (users) {
        console.log(users[i]);
        var uID = users[i]._id;
        $('#id').text(users[i]._id)
        $('#sku').text(users[i].sku)
        $('#name').text(users[i].name)
        $('#type').text(users[i].type)
        $('#price').text(users[i].price)
        $('#shipping').text(users[i].shipping)
        $('#description').text(users[i].description)
        $('#image').html("")

        $('a').attr("href", "/update-user?id="+uID)
        $('.delete').attr('data-id', uID)
    });
    return value.responseJSON;
}

                                <a href="/update-user?id="

passing variable value to href argument


RestyGWT JSON mapping with private fieldVisibility

Question: I am currently prototyping replacing the GWT-RPC based backend of our application to a REST based API using RestyGWT on the frontend and Spring MVC on the backend.
My issue occurs during the Java <-> JSON type conversions that both frameworks attempt to resolve automatically. All of our data objects use private fields, and many of the fields do not provide java bean style setter methods. By default, neither framework would inspect the private fields of a class and so this conversion fails.
For Spring MVC it was simple enough to fix this by adding an annotation to the data objects:
<code>@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
</code>
For RestyGWT I have not found a suitable fix. The only available workaround I have found is to use default access to all fields and constructors which is far from ideal. Does anybody have a solution that will allow RestyGWT to inspect the private fields of a Java object?
Answer: Try using @JsonProperty and @JsonCreator (do not remeber if both are necessary) on your fields.
<code>public abstract class Parent
{
    @JsonCreator
    public Parent(@JsonProperty("name") String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return name;
    }

    private String name;
}
</code>


Can mobs spawn on glass?

Question: I seem to recall at some point that a glass floor was not a candidate for mob spawning (which would be nice given that one cannot place torches on glass). However, I can't seem to confirm that information at the moment... is ittrue? (i.e. if I have a glass roof, and a glass loft, do I need to worry about somehow keeping it lit)?
Comment: @Halo49999 It depends on how you place the half slabs: Mobs can spawn if you place the half on the "top" side of a block. Mobs can **not** spawn if you place the slab on the "bottom half" of a block.
Comment: Mobs can now spawn on slabs as of 1.7 not sure about glass or stairs i am still doing tests.
Answer: Mobs don't spawn on glass, ice, half-slabs, and stairs. Your loft should be safe as per the minecraft wiki.
Spiders can climb glass walls, so you may want to add a small overhang or a row of ladders if there's an entrance.
Comment: I love that to stop things climbing your walls, you put down ladders.
Comment: @Ullallulloo you are wrong, **spiders can [climb soul sand](http://www.youtube.com/watch?v=vQNiWkZpEfA)**
Comment: From the wiki - "Enemy mobs can spawn on any *fully-opaque* cube block...". Since stairs are half-transparent to light, I'd say enemy mobs could **not** spawn there.
Comment: ...or soul sand if you get some of that. >.>
Comment: What about stairs? As stairs are weird-heighted blocks like steps and soul sand, I would think they might be safe, but I don't know for sure.
Comment: @Kevin Soul Sand is a normal sized block, you just sink in some, and I believe that mobs can spawn there. I was just saying that spiders can't climb it.
Comment: @NickT: Hmm...apparently so. I got that off the wiki originally, but it seems they've removed it from there now.
Answer: No mobs except for spiders (it seems like as of 1.5.1) can spawn on glass. Spiders require a 3x3 area to spawn in. If you place halfslabs so that you have 2x2 cubes of non-opaque blocks and halfslabs around them, they will not spawn. But if you place glass on the same y axis and 2x2 cubes of non-opaque in them, for some reason, they spawn. Don't believe me? Try it. I did it 5 minutes ago.
Comment: They still don't spawn on glass... they spawn on the 2x2 solid blocks, just as other mobs can.
Comment: Glass is a weird block. What's happening is that the spiders are spawning on the opaque blocks, and the glass doesn't count as "solid" blocks that interfere with their bounding box placement, the way slabs do. You see this as well with glass over chests—you can still open them—or glass above rails—you and mobs won't suffocate when your head goes inside the glass. Mobs still won't spawn *on* glass though.
Comment: @Arperum The thing is, they don't. I've built my mob trap high up in the sky and my spawn platform is made in the pattern above. There are absolutely NO spiders spawning if I place half slabs there. I waited 10 minutes and there were over 60 mobs in my trap. I went to the chamber above and: NO spiders. I can record it and put it on YouTube if you want...
Comment: @SeiKun Nothing can spawn on halfslabs that are on the bottom half.

Can mobs spawn on glass?


Is this fix for Avast Antivirus crashing safe to use?

Question: Well I have installed avast anti virus on Ubuntu 12.04.  But after updating, it crashes!  So I have made some tweaks like below:

Press Ctrl+Alt+T to open the Terminal. When it opens, run the command below.
sudo gedit /etc/init.d/rcS

Type your password and hit Enter.
When the text file opens, add the line:
sysctl -w kernel.shmmax=128000000

Make sure the line you added is before:
exec /etc/init.d/rc S

This is what it should look like:
#! /bin/sh

# rcS

#
# Call all S??* scripts in /etc/rcS.d/ in numerical/alphabetical order
#

sysctl -w kernel.shmmax=128000000

exec /etc/init.d/rc S

Save the file.
Reboot.

My question is: Did I do anything wrong? I mean as I have made some tweaks, will it lower the security of Avast down like viruses do? Please if you are a programmer check this if it contains bug or harmful intentions... Thanks.
Comment: Where is this fix from? Are there instructions somewhere recommending this? If so, a link to them should be added to the question (by editing the question).
Comment: Why would you do something like that? Do you actually know if it has something to do with Avast? What you've done shouldn't be harmful security wise, but looks completely irrelevant to the problem. Also, next time, ask first.
Comment: I had the exact same problem for a while. I never could get the above fix to work either. It may be a 12.04 issue.
Answer: This does not look to be harmful. Basically, these changes seem to me as if they were meant to ensure, that every time you start your computer, the virtual RAM filesystem that is available in /dev/shm/ is resized to some great size, probably to ensure that some temporary files that are going to be stored there will fit.
On the other hand, I have no clue why would this possibly could lead to fixing application crashes. It will not do any harm, but I doubt this fix can help.
Also, I need to admit I am not sure whether these changes will have any effect on ubuntu machine. These changes modify init.d files, while Ubuntu has migrated long time ago to another startup system, called Upstart, and it is possible that not only they will not fix anything, but will simply have no result.
Anyway, it's safe to try if you want to.
Comment: Agree, it looks fine, but I have no idea why it would actually fix anything. You (TmRn) might be better off using a different AV package. [ClamAV](http://www.clamav.net/lang/en/download/third-party-tools/3rdparty-gui/) has been around forever. The link is to some third party GUI tools that can make it easier to use.
Answer: I have just changed from Ubuntu 10.04 LTS which needed the same fix as shown in the first reply. Now I'm on Lubuntu 12.04 and have applied the fix as follows in LX terminal:
sudo leafpad /etc/init.d/rcS

Then add line as in the first answer.
If  you want to run avast just in the current sesssion (or to check if it works), then go to LX terminal and run this line:
sudo sysctl -w kernel.shmmax=128000000

Answer: Here at Avast forum moderators say that it really fixes the problem and users confirm that:
http://forum.avast.com/index.php?topic=57775.0
But wouldn't it make Ubuntu slower?
Answer: Have you tried this?
http://www.upubuntu.com/2011/08/how-to-install-avast-free-antivirus-on.html
I have not yet tried it. I am a newbie to Ubuntu


Are there any UX guidelines for preventing a user from submitting multiple form submissions?

Question: For example, if I'm a hairstylist and I want to provide my users with an ability to schedule an appointment with me online, outside of using a text verification code, is there any way of preventing people from booking multiple slots?
The idea is that if a Hairstylist A provides online booking and Hairstylist B wants to ensure B get all the business. So they go online to Hairstylist A's online form and books all the appointments so that to clients it appears Hairstylist A is unavailable, leaving Hairstylist B to get all the clients.
Are they any UX practices outside of HoneyPot Captcha or text verification codes to prevent people (or bots) from booking appointments superfluously?
Comment: No way to be 100% sure the bad guy don't use bot, fake facebook accounts... Maybe best way is to charge something on credit card for appointments.
Answer: You could require a booking approval process, where the user selects their time slot, then waits for booking confirmation from Hairstylist A. Before confirming, Hairstylist A could use their own judgement in deciding if the request is phony or not.
If a simple user registration is not out of the question for this scenario, you could require login to where you could limit the number of appointments any one user can book. Identify the user via email address and/or phone number and/or some other unique means, and then keep track of if that unique user has reached their limit.
One thing I have seen medical practices do is to charge a fee if the customer does not show up. This works best if billing information is already disclosed. People take these kinds of appoints a bit more seriously when money is on the line. Whether or not this would be a hinderance to your clients is something to consider.
With any process there are pros, cons and potential ways for abuse. Generally these types of decisions are not about how to completely eliminate abuse, but more about how to reduce the likelihood of it occurring. Any solution you put in place someone likely will find a way around it at some point. You just have to ask yourself how much effort you want to put into prevention.
One important thing to ballance is to not make it too inconvenient for honest customers to use your system, due to complicating the process with steps taken to curb the potential cases of abuse. (For some reason DRM comes to mind when thinking about this concept)
Comment: Additionally, I would suggest looking into how 3rd party solutions that provide appointment booking as a service handle this type of thing. Since it's their business, there are likely some additional things they are doing that you might be able to apply the same concepts to what you are trying to accomplish.
Answer: One of the way you could allow booking to your users is by authenticating them from facebook accounts. Also maybe limit booking from 1 account for max two slots, so that its not being misused.
Another way could be Phone (OTP authentication) verification with slot booking limits.
For Customers wanting to book more slots you could provide them a simple contact form to get in touch with you bypassing the booking system. ( I guess this would be mostly when someone would like to book your services for a complete day or so, In that case I would like to treat them as a special customer)


Derivative of a random process using a Karhunen-Loève-expansion/basis expansion

Question: Suppose a random function $X(t)$ can be written with the help of the Karhunen-Loève expansion (or some other basis expansion) by
$$X(t) = \sum_{k=1}^\infty \xi_k \psi_k(t),$$
where  $\psi_1(t), \psi_2(t),\dots$ are orthonormal eigenfunctions corresponding to the non-negative eigenvalues $\lambda_1,\lambda_2,\dots$ of the covariance operator $\Gamma$ and the random variables $\xi_k = \int_{a}^bX(s)\psi_k(s)ds$  are the uncorrelated scores with $E(\xi_k)=0$, $E(\xi_k \xi_l)=0$  for $k\neq l$ and $E(\xi_k^2)=\lambda_k$.
I am interested in the derivative $X'(t)$ of $X(t)$. Suppose the eigenfunctions $\psi_k(t)$ are differentiable, then, a natural approach would be to use the basis expansion above to get
$$X'(t) = \sum_{k=1}^\infty \xi_k \psi_k'(t).$$
This approach doesn't work always. For example, in the case where $X(t)$ is a Wiener process, $\psi_k(t)=\sqrt{2}\sin((k-1/2)\pi t)$ and $\lambda_k \sim 1/k^2$. However, while the derivative of $\psi_k$ exists and is obviously bounded, it is well known that the Wiener process is a.s. not differentiable.
Why can't I see this fact from the derivative of the expansion? Which property am I missing?
(What irritates me additionally is the fact that the variance of the right hand side, $E((\sum_{k=1}^\infty \xi_k \psi_k'(t))^2) = \sum_{k=1}^\infty \lambda_k \psi_k'(t)^2 \leq const \sum_{k=1}^\infty 1/k^2$, is bounded?!)
Can someone enlighten me why this natural approach doesn't work in general and/or give me some conditions when it works?
Answer: This is very analogous to Fourier series expansion. Try expanding a straight square wave in a Fourier series, and you will see the Gibbs phenomenon. It essentially comes down to the fact that you'll have pointwise convergence, but not uniform convergence. The Dirichlet conditions give you some limit on the sorts of behavior allowed in your $X(t)$ in order to get better behavior in the convergence. That, at least, works for Fourier series; however, any sort of eigenvector expansion such as you're employing, especially if it's an orthonormal expansion, will behave much like a Fourier series.


How to calculate dead/live load on this 2x4 structure

Question: Here is my general plan.

These will be built in the corner of a room and each bay will have a lag into the wall's 2x4 including one in the adjacent wall. The idea is to build these 2x4 frames and wrap them with 1/4" plywood.
I have a few questions.

How can a calculate what kind of load the wood itself can take? I'd probably use #2 Hem-fir.
Being 2x4's, I'd have 3.5" for the lag to hold, eg. I could use a big bolt. How can I calc the right bolt and does that affect the load rating? Is there a point it causes the wall's stud to fail?
I was looking at 5mm birch ply to wrap with, do I get more strength by using 1/4" ply or does the added weight counteract it?
If I built the whole thing with 2x2's (1.5"x1.5" actual), how much would it change things?
Comment: The back 2x4 will likely never fall off the wall, however, you have weak points at every butt joint.  What type of fasteners are you using to connect the 2x4s together?
Comment: @Tester101 Considering this will be boxed in with 1/8 or 1/4 inch plywood, do you think that will help give it structural integrity? If I added simpson 90 plates to each joint and then added the plywood (glued and nailed) does that up the box strength from sagging, or what I'm more worried about, the bolts fastening that back 2x4 to the wall, having that 2x4 break.

I expect these to hold books, so a good amount of weight. I also have to imagine a scenario where a kid might lean or hold onto the edge furthest away from the wall
Comment: As mentioned, the joints are weak... I'd suggest brackets to tie them together. And to help prevent sag, I'd put a long and substantial bracket at the outside corner. You're unlikely to find a stud within 15" on the adjacent wall, so consider a couple of substantial toggle bolts.
Comment: @Tester101 I was planning to use 16D nails or 3" deck screws, which is better?
Comment: @AloysiusDefenestrate By brackets do you mean something like simpson ties? Or did you mean a bracket under the shelf? I was hoping to make this a floating shelf and avoiding any kinds of bracket under/over or having a vertical support in the front.
Comment: I guess it depends on what type of weight you're going to put on the shelf, and how long you want it to last.  Nails are not great, because they don't have much holding strength (i.e. they can be pulled out). While screws are not great, because they have poor shear strength.  You'll want to consider some type of bracket (possibly custom made) as Aloysius suggests, or reconsider the design.
Comment: The plywood should add strength, though how much I cannot say.  I'd be less worried about the 2x4 coming off the wall, than the 2x4s cross braces pulling away from the 2x4 on the wall. You could always build the shelves the way you plan, and then test their strength. If they don't seem strong enough to you, redesign them a bit.
Comment: @Will -- for all the corners, I was thinking about simple brackets on the interior... Simpson makes them; anything that's around 2" square per leg will do fine. And for the 'end' bracket, I was thinking of a substantial "L" bracket, say, 12" per leg, placed in the interior. (This will fight against the sag that others have mentioned.)
Answer: Updated: I see a lot of questions referring to spans, strengths etc. Here is a very useful link for calculators regarding all things mentioned.
http://www.awc.org/codes-standards/calculators-software
Edit: Based on your diagram now showing.
I do not what type of finish look you are going for but as mentioned by others, the chance of hitting studs where you need them and lack of support are problematic. Either rethink your material or consider either metal bracing for a rustic look or a cable system if you want something that doesn't stand out.

Since your diagram is not showing up and you have a shelving tag, I will give it a go.
For a shelf you can use a sagulator calculator to give you the info you need. Which can be found here. http://woodbin.com/calcs/sagulator.htm
Strength values for lag bolts into 2x4s.

A 3/8" lag bolt 2" deep has a pull force of 1900lbs.
At 1/2" at 3.5" deep and you have a pull force of 3500lbs.

If you are looking for a box frame dead load, let me know.
Comment: Thank you for the numbers on the lag bolts, that's really helpful. Can you tell me what the pull force of a 2x4? Also, I don't know why I would be hard to hit the studs considering I"ve spaced the bays at 16" and my studs are 16 on center. I agree the adjacent wall probably isn't going to have something in the 15" available but maybe I'm missing something?
Answer: I don't know how you'd make such calculations, but I have enough experience with exactly this structure that I'll weigh in.

The others are right--the weak point is where the cross members attach to the rear ledger. You can resolve that by using at least two 4" construction screws or light lag screws, properly piloted and countersunk, at each joint. Also put plenty of fasteners through the decking plywood into the ledger, and also into the face board. The ledger connection is most critical. Construction glue may help but isn't ideal in an end-grain situation like the butt joints. It would help immensely with the decking joint.
As far as what it'll carry, you'll see substantial rotational sag long before it tears apart (or off the wall) due to the soft nature of the materials involved and the inherent imprecision of wooden structures. You may also see indentation of the substrate (assuming drywall). That said, it'll probably carry 50 lbs. per linear foot, evenly distributed front-to-back, reliably and without a problem.

Note: With any such structure, keep fasteners arranged near the edges to reduce torsional load. In your drawing, for example, you show lags centered vertically on the ledger. You'd want to stagger them to be placed near the top and bottom edges, weighting quantities toward the top, where the most load is located.


Canvas element weird reaction on 3rd runs

Question: i don't understand why the following code, sometimes shows all the items i select, most of the time shows some, and mostly in 3rd tries, simply doesn't show anything.
Because it does different things on multiple tries, im unable to pinpoint the couse of error.
For example you load in 3 picture, it doesn't show them (from inspect element i can see them), then you load in 7 pictures with the 3 previous included in them, it only shows thous 3..
I use Chrome. Looks Simple code.
here's the full code(you have to have the pictures in the same folder):
<!DOCTYPE>

    <input type="file" id='pictures' multiple="">

Comment: You need to wait until the images have loaded before drawing them.

`image.onload=function(){ctx.drawImage(image...)};`
Comment: when i added `image.onload= function(){ctx.drawImage(image,x,y,50,50)}` to `draw()` it didn't help.
Comment: You should probably also include the `x+=50+buffer;` inside that load handler.
Comment: You can use [this gist](https://gist.github.com/3925183). If it doesn't help, put a demo on [JSFiddle](http://jsfiddle.net)
Comment: when i do include `x+=50+buffer;` and i insert multiple different images, then i will produce one image multiple times. Don't understand why :D
Answer: You'll need to do a few things: http://jsfiddle.net/NMtfc/2/
for (i = 0; i < namelist.length; i++) {
    var image = new Image();

    canvas.appendChild(image);
    (function(img) {                         // this closure will allow us to maintain our reference to the image object correctly
        img.onload = function() {            // wait til the image loads
            ctx.drawImage(img, x, y, 50, 50)
            x += 50 + buffer;                // increment x here so it isn't the same for each element.
        }
    })(image);
    image.src = namelist[i];
}

I just realized that it can also be written simply as:
for (i = 0; i < namelist.length; i++) {
    var image = new Image();
    image.onload = function() {
        ctx.drawImage(this, x, y, 50, 50)  // 'this' will refer to the image.
        x += 50 + buffer;
    };
    image.src = namelist[i];
}

Comment: BIG THANKS, i was on this for 3 hours. :)
Comment: I have been looking and havet found any reference. How does the `image` get to the function(img). I think it's because you but it at the end `(image)` what what kind of notation is that?
Comment: It's commonly referred to as a "closure" or self-invoking function. I create a function then immediately call it passing in the current `image`, as you said by typing `...})(image);`


How to disable automatic download of new podcast episodes in Rhythmbox?

Question: After adding a new podcast to Rhythmbox it starts downloading the newest episode automatically without asking the user for permission.
I do find this behaviour pretty annoying especially when you have a lot of podcasts and are using 3G broadband to access the internet.
Can you update the podcast feed and then choose manually which episode you want to download? Did not find this in the settings/preferences...
Comment: If you think your question was answered right please mark the answer with the green arrow.
Answer: Run Rhythmbox then Edit menu -- Preferences  -- Podcasts tab -- Check for new eposodes and select Manually.
Comment: This doe snot seem to do it. The podct are still downloading when I start Rhythmbox even though it is set to Manual in Preferences -> Podcast Tab
Comment: Just wanted to say how that is counter-intuitive. "Check" for new episodes is very different from "Download" new episodes. (I used to use Amarok, but with Ubuntu 11.10, I am trying new things. I didn't like the lack of customization of Banshee, so am trying Rhythmbox.)
Comment: This does not answer the question, which it seems can only correctly be answered by stating that no, it is not currently possible.


Will fruit rot?

Question: I'm stockpiling fruit to sell on another island. Do I have to worry about fruit spoiling/going bad the same way that turnips do? Or is that trait specific to turnips?
Answer: Fruit won't spoil, turnips spoil as part of the price management minigame. They are unique in that regard.

Will fruit rot?


Dead Space takes a long time to load

Question: I just downloaded Dead Space from steam (a game I have played through many times - on PC and PS3).  This is the first time I have played it from steam, and it is on my gaming laptop.
The game is taking a very long time to load when I open doors, use the turbo lift, and load the game.  I am running the game from a Vertex 4 SSD and the laptop has a 3.7GHz i7, 32 GB of RAM, and a GTX 470... The game run just fine and the only time it slows down is when it loads.
Is there some way, a setting or something, that I can change to make the game load faster.
Comment: I doubt its a virus thing. Like 5pike said, check for updates. Ask on the Steam community if anyone had the same issues as you have. Your computer is above fine for the game. So it has to be within the game and Steam. If it was a general computer thing, you would know since it would affect other software besides DS.
Comment: You have got enough RAM to put the entire game in system memory. If there is a delay when you load an area you already have visited during a session, that should throw off suspicion from the SSD, since the data should not need to page back to the hard drive. Unrelated but similar; Running Duke Nukem Forever in windowed mode reduced loading speeds to a tenth of Full screen loading times. Sometimes it's up to how the game is implemented.
Answer: Although it pertains a different kind of loading length issue, try turning off VSYNC. Other than that, I can't really say myself. Some people say it's the game with the absolutely fastest load times from 2008. Some people complain about minute-long loading times. Either way, like 5pike suggested, checking for driver updates is a panacea for fixing any kind of slowness (whether it be loading, stuttering or lag) in computers, most of the time.
Answer: Sadly no.
What you can try is search your laptop for viruses with an application and do the deep check one it individually scans every file and if you have a virus take it to the geek squad for an easy fix.
If you have no viruses it could be the amount of data it's loading is difficult for it so try and delete what your positive you don't need .
The last hope would be to back up you files and wipe all other data from the laptop called the factory reset in the settings and if all that doesn't work it's because the laptop is simply old.
Comment: The "check for virus" is a good tip, but I highly doubt it's a virus thing. OP's laptop seems to be quite capable of running this game, so I think the problem is within the game itself (or steam). My suggestion - Do the usual: Check for driver updates, make an [integrity check in steam](https://support.steampowered.com/kb_article.php?ref=2037-QEUH-3335), reinstall the game ... A complete wipe of your laptop should be the last resort.
Comment: What? Since when does steam carry viruses?
Comment: About 2 months ago there was an emergency update done to steam and some people have been getting viruses like crazy since then
Comment: Sorry but that's just about the only ways don't dislike because you didn't want to hear that
Comment: Yeah I was talking about steam because sometimes steam carries some pretty bad viruses
Comment: I see, but viruses usually cause other problems. This would be a very peculiar virus - only effecting the door loading.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9351/discussion-between-deathdealer-and-5pike)
Comment: I'm really OCD about what I do on my laptop.  And since Dead Space loading is the only thing that seems to take longer than it should I don't think a virus is the problem.  (I do run virus scans a couple times a week, too).

Dead Space takes a long time to load


Avoid duplication in localization files

Question: I am currently working in a project where, for some reason, there are two files for each language that have almost the same content:
config/locales/en/my_translations.yml
config/locales/en/my_special_translations.yml
config/locales/pt/my_translations.yml
config/locales/pt/my_special_translations.yml

The files with the same name have the same content, translated to different languages. The problem here is that my_translations and my_special_translations have a really lot of duplicated code. Below I show an example with fake data to show where is the duplication and the differences:
config/locales/en/my_translations.yml
es:
  animals:
    happy_animals:
      dog: Dog
      cat: Cat
      horse: Horse
    sad_animals:
      cow: Cow
      elephant: Elephant

config/locales/en/my_special_translations.yml
es:
  special_animals:    # This line is different
    happy_animals:
      dog: Dog
      cat: Cat
      horse: Horse
    sad_animals:
      cow: Farm cow   # This line is different
      elephant: Elephant

This is just an example, but I have files with hundreds of lines where just a few or them are different. Is there any way to reduce or avoid this duplication between files?
EDIT
I am using this code the following way:
animals_scope = special? ? 'special_animals' : 'animals'
animals_hash = I18n.translate(animals_scope, locale: current_locale)
animals_hash.keys.each do|animal_key|
  # Stuff
end

That is, for each element in the .yml file I am performing some actions
Comment: Why do you need the `special_translations` in the first place? Isn't it possible to handle the special case when using the `I18n.t`? Something like: `<%= t(( cow_spcial? ? 'cow_special' : 'cow'), scope: 'animals') %>`
Comment: I have updated my question, maybe it is more clear now. Thanks ;)
Answer: You could use YAML anchors and aliases and only override the values that are different:
es:
  animals: &ANIMALS
    happy_animals:
      dog: Dog
      cat: Cat
      horse: Horse

    sad_animals:
      cow: Cow
      elephant: Elephant

  special_animals:
    <<: *ANIMALS
    sad_animals:
      cow: Farm cow

Avoid duplication in localization files


Grohe Ladylux kitchen faucet leaking underneath

Question: My Grohe Ladylux kitchen faucet is running significant water down the hoses from the housing underneath the counter.  Is changing out the cartridge going to solve this problem, or what will help?
Comment: Can you post a picture? Which hoses, the supply hoses (from the shutoff valves to the faucet knobs) or the spray hose (from the faucet knobs to the sink sprayer)? Have you tried just tightening the fittings yet?
Comment: we are sorry you are having issues with the Ladylux kitchen faucet. If you still need assistance please email us at email@example.com and ask for Deidrea Hubeck our customer service supervisor. She will be happy to help you. Thanks,
GROHE
Answer: If it's leaking where the hose meets the pull-out faucet head you unscrew the hose from the handle and there's an o-ring you can replace. Any plumbing supply shop that deals with Grohe should have it.
Before fitting the new o-ring make sure the installation area is clean and apply an o-ring compatible grease to all contact areas so the new o-ring doesn't bind up or get torn when installing it.
Answer: We had this same faucet installed a month ago... worked great for awhile then same leaking occurred up under faucet housing. We narrowed it down to the cold water side in housing, and it doesn't leak continually which made it hard to locate. We are replacing this faucet with a different brand!
Answer: I just replaced my Grohe Ladylux spray head on a faucet installed in 2003 because the spray function failed and cannot be repaired.  I ordered the Grohe o-ring required for the new head after reading the old o-ring won't prevent leaking at the head connection to the pull-out line, but it will take longer to arrive. After trials with  both heads, I learned the old o-ring won't work with the new spray head because it requires a fatter o-ring of the same diameter. I had one from an inexpensive generic faucet repair kit that fit perfectly and gave me a nice, tight, waterproof connection. The construction of the old and new spray heads is enough different that you need this kind of remedy for a new Grohe spray head, but it doesn't have to be a Grohe washer. (It has nothing to do with the old o-ring being compressed.  Mine functioned perfectly with the old spray head.  I believe it is all about a change in manufacturing specs.)


TensorFlow broken data stream reading image file

Question: I have installed tensorflow 0.8.0 in anaconda env called "tensorenv". I then began running basic codes in it in a file called basic_python.py.
import matplotlib.image as mpimg

# First, load the image
filename = "MarshOrchid.jpg"

image = mpimg.imread(filename)

# Print out its shape
print(image.shape)

import matplotlib.pyplot as plt

plt.imshow(image)

plt.show()

This code runs perfectly well. But when i just add to this code the following line
import tensorflow as tf

to the beginning of the code above the following trace is printed:
    Traceback (most recent call last):
  File "basic_python.py", line 6, in <module>
    image = mpimg.imread(filename)
  File "/home/shubham/anaconda3/envs/tensorenv/lib/python3.5/site-packages/matplotlib/image.py", line 1304, in imread
    im = pilread(fname)
  File "/home/shubham/anaconda3/envs/tensorenv/lib/python3.5/site-packages/matplotlib/image.py", line 1283, in pilread
    return pil_to_array(image)
  File "/home/shubham/anaconda3/envs/tensorenv/lib/python3.5/site-packages/matplotlib/image.py", line 1400, in pil_to_array
    x = toarray(im)
  File "/home/shubham/anaconda3/envs/tensorenv/lib/python3.5/site-packages/matplotlib/image.py", line 1383, in toarray
    x_str = im.tobytes('raw', im.mode)
  File "/home/shubham/anaconda3/envs/tensorenv/lib/python3.5/site-packages/PIL/Image.py", line 678, in tobytes
    self.load()
  File "/home/shubham/anaconda3/envs/tensorenv/lib/python3.5/site-packages/PIL/ImageFile.py", line 235, in load
    raise_ioerror(e)
  File "/home/shubham/anaconda3/envs/tensorenv/lib/python3.5/site-packages/PIL/ImageFile.py", line 59, in raise_ioerror
    raise IOError(message + " when reading image file")
OSError: broken data stream when reading image file

What should I do because in another simple program for addition which I wrote, there this tensorflow import did not cause any problem. But here it causes a lot of problem.
Comment: Can you re-download the image and try again?
Comment: I just did that and same thing happened again. When I dont use that tensorflow import statement the program works pretty well!!!!
Comment: https://github.com/python-pillow/Pillow/issues/1057#issuecomment-68203875 suggests you to install `libjpeg8-dev`, so maybe can try `sudo apt install libjpeg8-dev` and reinstall `pillow`?
Comment: I already have that Installed
Answer: Try to import PIL before tensorflow. In your case, just put "import tensorflow as tf" after all other imports.
Answer: This is a known issue. Upgrade Pillow using pip install Pillow --upgrade should fix it.
Comment: Sounds like a comment!


Kubuntu 14.10, updates gives GPG error

Question: I'm running Kubuntu 14.10. About a week or so ago, I noticed that doing a 'sudo apt-get update' gives me the following error at the end.
Fetched 16.0 MB in 24s (650kB/s)
Reading package lists... Done
W: GPG error: http://ppa.launchpad.net utopic Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY CFBCA7A67412649C

Any ideas? Some Google searching reveals an old bug that seems to have already been fixed so I don't know if it's the same problem as mine or not.
Comment: Could you add any more information, such as what source that is coming from?
Answer: Execute the following commands in terminal
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys CFBCA7A67412649C

and then update
sudo apt-get update

Comment: Thank you, that did the trick. I couldn't tell where it was coming from by looking at the error but by importing the key I saw the PPA it was from.

Kubuntu 14.10, updates gives GPG error


water leak from ceiling

Question: I'm Ahammed Sheriff from Oman. Here we have a building with 6 floors. On the basement floor of the building there is leakage on the ceiling. Is there any way to stop the leakage from the ceiling? Thanks in advance.
Comment: Hello, and welcome to Stack Exchange. We'd really need more information to be able to help; what is above the leak? is this a recent thing? when does it get better or worse? is there any sort of odor?
Answer: You must search for the source of this leak by inspecting the walls immediately above where you see water. In many cases like this you will see damp spot on the walls above and these must be cut open to inspect pipes for the  leak. If the walls are covered with gyproc or similar this is not a difficult job. Finding the leak is essential or it will destroy walls and flooring.

water leak from ceiling


Php 7.3 extension imagick and gmagick on Ubuntu 18.04

Question: How can i install php extension imagick and gmagick on ubuntu 18.04 LTS,
i tried imagick using :
sudo apt-get -y install gcc make autoconf libc-dev pkg-config
sudo apt-get -y install libmagickwand-dev
sudo peclX.Y-sp install imagick

But got error
ubuntu@ip:~$ sudo pecl7.3-sp install imagick
sudo: pecl7.3-sp: command not found

Also tell me about gmagick, I have installed both graphicsmagick and imagemagick just need to install php extention for both of them.
I am using Php7.3 ondrej,
Installed: php7.3 php-pear php7.3-curl php7.3-dev php7.3-gd php7.3-mbstring php7.3-zip php7.3-mysql php7.3-xml

Comment: Please run `apt search php-imagick` and see if imagick shows up! Also run the search for `php-gmagick` if both show then install with `sudo apt install php-gmagick php-imagick` My version of php is 7.2 so check and let me know!
Answer: I use php7.2 but from the same repo as your version of php. Check if these packages are present with the commands
apt search php-imagick | grep php-imagick
apt search php-gmagick | grep php-gmagick

If the search turns up positive, install both with the command
sudo apt install php-gmagick php-imagick

Restart apache afterward with
sudo systemctl restart apache2


No. of homomorphisms from $\mathbb Z_n$ to $\mathbb Q$

Question: How many homomorphisms are there from $\mathbb Z_n$ to $\mathbb Q$ ?
Comment: Is there an element $g$ of $\mathbb{Q}$ such that the following holds? $$\underbrace{g+\cdots+g}_{n}=0$$
Comment: @angryavian: yes !!! , there is no such non-zero $g$ in $Q$ , thanks
Answer: Hint If $\eta:G\to H$ is a morphism of groups, and if $x\in G$ has finite order say $|x|=k$, then $(\eta x)^k=\eta(x^k)=\eta 1=1$ so $\eta x$ has finite order, and $|x| \mid |\eta x|$. Now look at the elements of finite order of $\Bbb Q$ (is this additive or multiplicative here?)
Comment: (I'm not sure if the OP is thinking $\Bbb Q$ as an additive of multiplicative group. In the former case the only torsion elt is $0$, in the latter, there are two torsion elts.)
Answer: Assuming you are taking the operation to be addition in $\mathbb{Z}_n$ and $\mathbb{Q}$, then $\phi(0) = 0$, as is true for all homomorphisms.  Then:

$\phi(1) = \text{something}$
$\phi(1+1) = \phi(1) + \phi(1) = \text{something + something}$
$\phi(1+1+1) = \cdots$

What happens when this process is iterated $n$ times?
Comment: "No nontrivial homomorphism" as they say
Comment: Iterating $n$ times will results in $\phi(0)=$something, which is non-zero. Contradiction. So there is no homomorphism. Right?
Comment: @KushalBhuyan;No there is the zero homomorphism i.e. $\phi(x)=0\forall x$ and this is the only one


Removing knockouts in old work metal boxes

Question: I recently had an existing old work box (metallic, installed with the supports that look like 'F') where there was a cable coming in from the top and another from the bottom. I wanted to add a third cable from the back of the box. So I took my trusty hammer and screwdriver, aimed the screwdriver at the part of the back knockout away from the tab, smacked it, and broke the box tabs right through the drywall... :(.
Once the box was out of the wall, it was still pretty much impossible to knock out the knockout from the inside of the box. I then flipped it around and tried from the back and it came out super easily.

Are knockouts typically "one direction only"?
Is there a different way to get them out in a situation like this? Or is it standard to have to take the existing cables out, the box out, punch them out, then put everything back together?
Comment: Your problem description made me laugh out loud. Not in spite or schadenfreude, but in sympathy. That sounds *exactly* like something that I'd do...
Answer: A lot of handy boxes and old work "gem" boxes have knockouts that are made to knock from the outside in.  This picture of a Steel City handy box shows it clearly

If you have to remove these from the inside, there is a trick.  You can't pull the KO with a hammer.  But if you drive a small self drilling screw into the KO from the inside

then back it out a few turns, you can pull on that screw with pliers to remove the knockout.  If you can't get it with pliers, try a mini prybar
Comment: @batsplaterson FYI I just tried this. I got the screw in, then pulled with all my might with pliers to no avail. But then I tried a little mini pry-bar on the screw and the knockout came right out! Thanks again!
Comment: @DavidDoria The back-end of a claw hammer should work too ;-)
Comment: @DavidDoria that's great, I am glad it worked for you.  I will edit the answer to include that method.
Comment: just be sure there is not some surprise romex behind where you're drilling.
Answer: I recently had this issue and solved it this way:
Drill small hole in the center of the desired knockout (from the inside).
Drive a long self-tapping metal screw into the newly drilled hole until it is firmly in place.
Take a claw-hammer or kitty-paw to pull on the screw until you can get pliers onto the knock-out enough to twist//work it out.
Answer: Yes, knockouts are often one direction only, esp. in outlet boxes. If you can see that the KO is not even with the rest of the box, you need to take a something like a flat blade screwdriver, put it in the recessed side and give it a couple of medium hits with a hammer.  Then once you get it started, use a pair of pliers (whatever type is best, maybe needle nose) to pry on the KO until it breaks loose.
Comment: @isherwood Thanks for the advice, I edited and hopefully substantially improved my answer.
Comment: @isherwood Surprised you said that?! I would think that the last part of my answer "...you really need to  knock it out from the recessed side"  I think that qualifies as a "how".  If not please tell me how to improve my answer.   The "that's how" at the end is something my autistic grand-daughter says practically at the end of most of her sentences (7 years old).  Just threw it in there for comic relief.   Take care, you are doing a great job here.
Answer: Yes, they are one way unless you really want to bend up the box. When the box is installed, I usually take a small screwdriver, slotted, and tap it into the crack between the knockout and the box and twist the knockout out a bit. Then grab it with a pair of needle nosed pliers and twist it completely out...  be careful not to damage the insulation on existing cables when twisting out the knockout.
If there is room between the wall and the box, you might be able to get a small screw driver in there and tap the knockout into the box and then grab it with your needle nosed pliers.
Answer: I've gotten a few out with just a flat head screw driver at an angle and using a hammer to tap it into the crack or to make a gap. Once it's in, you can pry or twist with the screw driver to widen the gap and get something bigger in to finish the job.
It's not exactly easy, but it works without extra hardware or a drill.
And yes, like the others say, they are intended to be one-way from the outside in. I'd have to assume they didn't want the knockouts to be accidentally knocked out while the installer was putting wires in or a repair being done. Trying to fish one back into place would be even harder than trying to pull one out.
Comment: @ThreePhaseEel, that makes sense. I'd assume those are also useful for when someone removes a circuit/wire/something and leaves a knockout empty.
Comment: They make special snap-in plugs to replace missing KOs for that reason :)


Rebuild query which looking for specific string

Question: I have products numbers which looks like below:
One example product (contain couple articles)
14.12312.1
14.12312.2
14.12312.3
14.12312.4
14.12312.5

Other example product (contain couple articles)
003.23.1
003.23.66
003.23.44
003.23.77
003.23.5

Important thing here is dots are separators:
<producentNumber>.<specialnumber>.<articlevariation>

Now i got query which could take first part of specific product for instance i can pass: 003.23. (with last dot) and then it gives me all starts with it so:
003.23.1
003.23.66
003.23.44
003.23.77
003.23.5

This is the query which is doing that:
SELECT ID, Nummer FROM [Cenea].[dbo].[T_Artikel]
                  WHERE
                  SUBSTRING(Nummer, 0, LEN(Nummer) + 2 -  CHARINDEX('.', REVERSE(Nummer)))  IN
                  (
                                                                                '003.23.'
                  )

However now is the change that within last part of the articles number could appears dots and not only the numbers so it means i can have like this:
 003.23.1
 003.23.66..dwqd
 003.23.4422.323.3
 003.23.77....f
 003.23.5

So when i pass 003.23. i will get not all but just 003.23.1 in this case. The logic stays as it was first two dots are holding the base but after the second there could be anything. Question is how to rebuild my sql query to adapt the change to get alkl articles?
Hope everything is clear and please provide working code as i have to make change on production today.
Comment: no solution yet means it is not clear.Simply first say when you pass "003.23." then what output you should get.?and also what is your input table.According to me LIKE '003.23.%',it should work.
Answer: You can use LIKE to get all rows where Number starts with <some value>:
SELECT ID, Nummer FROM [Cenea].[dbo].[T_Artikel]
WHERE Number LIKE '003.23%'


How to skip invalid characters in XML file using PHP

Question: I'm trying to parse an XML file using PHP, but I get an error message:

parser error : Char 0x0 out of allowed range in

I think it's because of the content of the XML, I think there is a speical symbol "☆",  any ideas what I can do to fix it?
I also get:

parser error : Premature end of data in tag item line

What might be causing that error?
I'm using simplexml_load_file.
Update:
I try to find the error line and paste its content as single xml file and it can work!! so I still cannot figure out what makes xml file parse fails. PS it's a huge xml file over 100M, will it makes parse error?
Answer: Do you have control over the XML? If so, ensure the data is enclosed in <![CDATA[ .. ]]> blocks.
And you also need to clear the invalid characters:
/**
 * Removes invalid XML
 *
 * @access public
 * @param string $value
 * @return string
 */
function stripInvalidXml($value)
{
    $ret = "";
    $current;
    if (empty($value))
    {
        return $ret;
    }

    $length = strlen($value);
    for ($i=0; $i < $length; $i++)
    {
        $current = ord($value[$i]);
        if (($current == 0x9) ||
            ($current == 0xA) ||
            ($current == 0xD) ||
            (($current >= 0x20) && ($current <= 0xD7FF)) ||
            (($current >= 0xE000) && ($current <= 0xFFFD)) ||
            (($current >= 0x10000) && ($current <= 0x10FFFF)))
        {
            $ret .= chr($current);
        }
        else
        {
            $ret .= " ";
        }
    }
    return $ret;
}

Comment: Not sure if this would help in this case. You can't fix encoding problems with CDATA, only escaping issues like "&" instead of "&".
Comment: This function is broken. `ord()` is only operating on single-bytes.
Comment: I can't control XML but I can ask...but it's the solution?? let me check it
Comment: Yes, I agree. Dominic has the solution.
Comment: user315396: Sorry but no way you've fixed "out of allowed range" with a CData section.
Comment: Hi, I'm having problems making this function work for me. In my particular case, I'm receiving the string from a $_GET variable, utf8_encoded like 'Canci%EF%BF%BDn' and I need to remove the '%EF%BF%BD' part.
See: http://codepad.viper-7.com/NJoPRG
Comment: @Jhong thank you very much for this function, it saved me from a lot of pain. But I want to know more about this 'illegal' characters, what they are and, especially if there's MORE like them that can break my xml processing using DOMDocument and lead to incomplete results for me... Do you have somewhere such explained?
Comment: FWIW, if you're getting an error loading an XML string into DOMDocument::loadXML(), `return utf8_encode($ret)` will also encode it as UTF-8, after removing the invalid characters.
Comment: This worked for me. I was having the "Char 0x0 out of allowed range in Entity" error while calling DOMDocument::loadXML():
Answer: I decided to test all UTF-8 values (0-1114111) to make sure things work as they should. Using preg_replace() causes a NULL to be returned due to errors when testing all utf-8 values. This is the solution I've come up.
$utf_8_range = range(0, 1114111);
$output = ords_to_utfstring($utf_8_range);
$sanitized = sanitize_for_xml($output);

/**
 * Removes invalid XML
 *
 * @access public
 * @param string $value
 * @return string
 */
function sanitize_for_xml($input) {
  // Convert input to UTF-8.
  $old_setting = ini_set('mbstring.substitute_character', '"none"');
  $input = mb_convert_encoding($input, 'UTF-8', 'auto');
  ini_set('mbstring.substitute_character', $old_setting);

  // Use fast preg_replace. If failure, use slower chr => int => chr conversion.
  $output = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $input);
  if (is_null($output)) {
    // Convert to ints.
    // Convert ints back into a string.
    $output = ords_to_utfstring(utfstring_to_ords($input), TRUE);
  }
  return $output;
}

/**
 * Given a UTF-8 string, output an array of ordinal values.
 *
 * @param string $input
 *   UTF-8 string.
 * @param string $encoding
 *   Defaults to UTF-8.
 *
 * @return array
 *   Array of ordinal values representing the input string.
 */
function utfstring_to_ords($input, $encoding = 'UTF-8'){
  // Turn a string of unicode characters into UCS-4BE, which is a Unicode
  // encoding that stores each character as a 4 byte integer. This accounts for
  // the "UCS-4"; the "BE" prefix indicates that the integers are stored in
  // big-endian order. The reason for this encoding is that each character is a
  // fixed size, making iterating over the string simpler.
  $input = mb_convert_encoding($input, "UCS-4BE", $encoding);

  // Visit each unicode character.
  $ords = array();
  for ($i = 0; $i < mb_strlen($input, "UCS-4BE"); $i++) {
    // Now we have 4 bytes. Find their total numeric value.
    $s2 = mb_substr($input, $i, 1, "UCS-4BE");
    $val = unpack("N", $s2);
    $ords[] = $val[1];
  }
  return $ords;
}

/**
 * Given an array of ints representing Unicode chars, outputs a UTF-8 string.
 *
 * @param array $ords
 *   Array of integers representing Unicode characters.
 * @param bool $scrub_XML
 *   Set to TRUE to remove non valid XML characters.
 *
 * @return string
 *   UTF-8 String.
 */
function ords_to_utfstring($ords, $scrub_XML = FALSE) {
  $output = '';
  foreach ($ords as $ord) {
    // 0: Negative numbers.
    // 55296 - 57343: Surrogate Range.
    // 65279: BOM (byte order mark).
    // 1114111: Out of range.
    if (   $ord < 0
        || ($ord >= 0xD800 && $ord <= 0xDFFF)
        || $ord == 0xFEFF
        || $ord > 0x10ffff) {
      // Skip non valid UTF-8 values.
      continue;
    }
    // 9: Anything Below 9.
    // 11: Vertical Tab.
    // 12: Form Feed.
    // 14-31: Unprintable control codes.
    // 65534, 65535: Unicode noncharacters.
    elseif ($scrub_XML && (
               $ord < 0x9
            || $ord == 0xB
            || $ord == 0xC
            || ($ord > 0xD && $ord < 0x20)
            || $ord == 0xFFFE
            || $ord == 0xFFFF
            )) {
      // Skip non valid XML values.
      continue;
    }
    // 127: 1 Byte char.
    elseif ( $ord <= 0x007f) {
      $output .= chr($ord);
      continue;
    }
    // 2047: 2 Byte char.
    elseif ($ord <= 0x07ff) {
      $output .= chr(0xc0 | ($ord >> 6));
      $output .= chr(0x80 | ($ord & 0x003f));
      continue;
    }
    // 65535: 3 Byte char.
    elseif ($ord <= 0xffff) {
      $output .= chr(0xe0 | ($ord >> 12));
      $output .= chr(0x80 | (($ord >> 6) & 0x003f));
      $output .= chr(0x80 | ($ord & 0x003f));
      continue;
    }
    // 1114111: 4 Byte char.
    elseif ($ord <= 0x10ffff) {
      $output .= chr(0xf0 | ($ord >> 18));
      $output .= chr(0x80 | (($ord >> 12) & 0x3f));
      $output .= chr(0x80 | (($ord >> 6) & 0x3f));
      $output .= chr(0x80 | ($ord & 0x3f));
      continue;
    }
  }
  return $output;
}

And to do this on a simple object or array
// Recursive sanitize_for_xml.
function recursive_sanitize_for_xml(&$input){
  if (is_null($input) || is_bool($input) || is_numeric($input)) {
    return;
  }
  if (!is_array($input) && !is_object($input)) {
    $input = sanitize_for_xml($input);
  }
  else {
    foreach ($input as &$value) {
      recursive_sanitize_for_xml($value);
    }
  }
}

Comment: This has been very helpful! though I have yet to find an input that triggers the 'long' version, do you have any examples for when its needed?
Comment: @mcfedr  preg_replace could be fixed in later versions of php. This was php 5.4 I believe
Answer: Certain Unicode characters must not appear in XML 1.0:

C0 control codes (U+0000 - U+001F) expect tab, CR and LF.
UTF-16 surrogates (U+D800 - U+DFFF). These are invalid in UTF-8 as well and indicate more serious problems when encountered.
U+FFFE and U+FFFF.

But in practice, you often have to handle XML which was carelessly produced from other sources containing such characters. If you want to handle this special case of invalid XML in an UTF-8 encoded string, I'd suggest:
$str = preg_replace(
    '/[\x00-\x08\x0B\x0C\x0E-\x1F]|\xED[\xA0-\xBF].|\xEF\xBF[\xBE\xBF]/',
    "\xEF\xBF\xBD",
    $str
);

This doesn't use the u Unicode regex modifier but works directly on UTF-8 encoded bytes for extra performance. The parts of the pattern are:

Invalid control chars: [\x00-\x08\x0B\x0C\x0E-\x1F]
UTF-16 surrogates: \xED[\xA0-\xBF].
Non-characters U+FFFE and U+FFFF: \xEF\xBF[\xBE\xBF]

Invalid characters are replaced with the replacement character U+FFFD (�) instead of simply stripping them. This makes it easier to diagnose invalid chars and can even prevent security issues.
Answer: If you have control over the data, ensure that it is encoded correctly (i.e. is in the encoding that you promised in the xml tag, e.g. if you have:
<?xml version="1.0" encoding="UTF-8"?>

then you'll need to ensure your data is in UTF-8.
If you don't have control over the data, yell at those who do.
You can use a tool like xmllint to check which part(s) of the data are not valid.
Comment: I try to find the error line  and paste its content as single xml file and it can work!! so I still cannot figure out what makes xml file parse fails.
Comment: In this case, this exactly reinforces what Dominic is saying.
Comment: Ok...I think some data is not UTF-8..acutually if I open XML at FF, there is a error msg to mean error char. IE...hm...it's big file..I just wait for long time but no response.
Comment: @DominicRodger Thank you! xmllint let me find the invalid characters and remove them.
Answer: My problem was "&" character (HEX 0x24), i changed to:
function stripInvalidXml($value)
{
    $ret = "";
    $current;
    if (empty($value))
    {
        return $ret;
    }

    $length = strlen($value);
    for ($i=0; $i < $length; $i++)
    {
        $current = ord($value{$i});
        if (($current == 0x9) ||
            ($current == 0xA) ||
            ($current == 0xD) ||

            (($current >= 0x28) && ($current <= 0xD7FF)) ||
            (($current >= 0xE000) && ($current <= 0xFFFD)) ||
            (($current >= 0x10000) && ($current <= 0x10FFFF)))
        {
            $ret .= chr($current);
        }
        else
        {
            $ret .= " ";
        }
    }
    return $ret;
}

Answer: Make sure your XML source is valid. See http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
Comment: XML is valid  what if encoding is UTF-8  but there is a Big5 char , I find the char "".
Answer: For a non-destructive method of loading this type of input into a SimpleXMLElement, see my answer on How to handle invalid unicode with simplexml
Answer: I used this to clean the string:
public static function Clean($inputName)
    {
        $strName=trim($inputName);

        if($strName!="")
        {
            $strName = iconv("UTF-8", "UTF-8//IGNORE", $strName); // drop all non utf-8 characters

            $strName=str_replace(array('\\','/',':','*','?','"','<','>','|'),'@',$strName);
            $string = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $string);

            // [\x00-\x1F]  control characters http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx

            // Invalid control chars: [\x00-\x08\x0B\x0C\x0E-\x1F]
            // UTF-16 surrogates: \xED[\xA0-\xBF].
            // Non-characters U+FFFE and U+FFFF: \xEF\xBF[\xBE\xBF]
            // Invalid characters are replaced with the replacement character U+FFFD

            $strName = preg_replace(
            '/[\x00-\x08\x0B\x0C\x0E-\x1F]|\xED[\xA0-\xBF].|\xEF\xBF[\xBE\xBF]/',
            "\xEF\xBF\xBD",
            $strName);

            // Reduce all multiple whitespace to a single space
            // $strName = preg_replace('/\s+/', ' ', $strName);

            if(trim($strName)=="")
            {
                $strName="@" . "empty-name";
            }
        }
        else
        {
            $strName=" ";
        }

        return $strName;
    }

Answer: Not a php solution but, it works:
Download Notepad++  https://notepad-plus-plus.org/
Open your .xml file in Notepad++
From Main Menu: Search -> Search Mode set this to: Extended
Then,
Replace -> Find what \x00; Replace with {leave empty}
Then, Replace_All
Rob


C++: subvector from a vector as an argument to a function

Question: I use a function from another library which takes any STL sequential container as an argument. Just for arguments sake, I'll keep it as std::vector.
do_something (std::vector<double>& k)
{
    ...
}

I have a whole vector of data (happens to be of type double) Is there a way to pass a sub vector preferably via reference and without copying and splitting vector before hand, to this function? It is straight forward via copying (by simply making a copy of subvector, returning the vector from function and putting the respective subvector back into vector). why?:

The reason I do not want to copy is entirely due to speed, I will be calling this function many (and I mean many) times and performance is utmost important.
The reason I don;t want to split vector before hand is the file IO operations. The vector being sequential allows fast file write particularly in binary mode

In other words, can I do something like this (in pseudocode exmaple below)?
std::vector<double> myVector{1.2, 5.6, 8.6, 2.2, 1.7, 9.1}; // myVeector of size 6

do_something (&myVector[ -- elementss 2,3,4--]);

Any help appreciated, even if it is not possible and if you know a way to copy back and forth efficiently
Note: If it's any help to SO programmers, my vector will be the same size with the same prelocated subvector which is not equal to from myVector.begin() or myVector.back(). Also this will never change for that one vector
Comment: Use iterators, or if you want slightly better syntax, use something like [boost::adaptors::sliced](http://www.boost.org/doc/libs/1_53_0/libs/range/doc/html/range/reference/adaptors/reference/sliced.html).
Answer: No, it can't be done. That's why standard algorithms accept two (or more) iterators as parameters, rather than a container.
You could also look at the Boost.Range library, which allows for range adaptors including slices.
Depending what's in this function template that you call, you might be able to pass a sliced range in place of the sequence, since the concrete ranges defined in Boost do have begin() and end() member functions. But since it takes a non-const reference to a container, there's a chance that it adds or removes elements, in which case you're out of luck.


How to put condition if the following criteria does not match and my form should not submit

Question: I have put conditon to my form that one capital one small and 8 characters simply if criteria does not match my form should not be submit but here my form is submitted even this criteria does not match and showing me the success message.
I dont know where is the problem.
My js/ajax code:
<code>        $('#password_change_form').submit(function(e) {
        e.preventDefault();
        var saveThis = $(this);

        $.ajax({
            type: "POST",
            url: "/changepassword",
            data: $(saveThis).serialize(),
            success: function(data) {
                $(".success-messages").text("Heslo bylo úspěšně změněno").fadeIn();
                setTimeout(function(){
                    $(".success-messages").fadeOut('slow');
                },4000);
                $('#password_change_form').trigger("reset");

            },
            error: function (data) {
                $(".error-messages").text("Zadali jste špatné heslo").fadeIn();
                setTimeout(function(){
                    $(".error-messages").fadeOut('slow');
                },4000);
                $('#password_change_form').trigger("reset");
            }

        });
    }),
</code>
and validation rules on my form:
<code>                      var FormValidation = function () {
        var e = function () {
            var e = $("#password_change_form"),r = $(".alert-danger", e), i = $(".alert-success", e);

            e.validate({
                errorElement: "span",
                errorClass: "help-block help-block-error",
                focusInvalid: !1,
                ignore: ":hidden",
                rules: {

                    new_password: { required: !0,password_validate:!0 },
                    password_confirmation: {
                        equalTo: "#new_password"
                    }

                },
                messages: {

                    new_password:{ required: "Zapomněli jste zadat nové heslo."},
                    password_confirmation:{ equalTo: "Hesla nesouhlasí."}

                },
                invalidHandler: function (e, t) {
                    i.hide(), r.show()
                },
                errorPlacement: function (e, r) {
                    r.is(":checkbox") ? e.insertAfter(r.closest(".md-checkbox-list,.checkbox-label, .md-checkbox-inline, .checkbox-list, .checkbox-inline"),r.closest(".checkbox").addClass("has-error")) : r.is(":radio") ? e.insertAfter(r.closest(".md-radio-list, .md-radio-inline, .radio-list,.radio-inline")) : e.insertAfter(r)
                },
                highlight: function (e) {
                    $('.help-block').html('');$(e).closest(".form-group").addClass("has-error")
                },
                unhighlight: function (e) {
                    $(e).closest(".form-group").removeClass("has-error")
                },
                success: function (e) {
                    e.closest(".form-group").removeClass("has-error")
                }
            })
        };
        return {
            init: function () {
                e();
            }
        }
    }();

    $(document).ready(function () {
        FormValidation.init();
        $.validator.addMethod("password_validate",function(value,element){
            return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
        },"Nové heslo musí obsahovat minimálnÄ› 8 znaků, jedno velké a malé písmeno a Äíslo. Prosím zkontrolujte, že vámi zadané heslo splňuje tyto podmínky.");
    });
</code>
I dont know where is the problem my form should not be submit if the criteria does not match but here its submitting the form.
Guys really needs your help here.
Answer: I suggest using Laravel validation for your form. https://laravel.com/docs/5.7/validation
This might also be useful: Laravel password validation rule


Installed Kali Tools with kaltoolin3 on Ubuntu 20.04 and now Ubuntu will only boot to command line

Question: Installed Kali Tools with kaltoolin3 on Ubuntu 20.04 and now Ubuntu will only boot to the command line.
Ctrl + Alt + F7 doesn't do anything.
I've tried sudo apt-get install --reinstall ubuntu-desktop
but I get the error:

The following packages have unmet dependencies:
ubuntu-desktop : Depends: gdm3 but it is not going to be installed
...........................Depends: gnome-control-center but it is not going to be installed
...........................Depends: gnome-settings-daemon but it is not going to be installed
...........................Depends: gnome-shell but it is not going to be installed
...........................Depends: gnome-shell-extension-appindicator but it is not going to be installed
...........................Depends: gnome-shell-extension-desktop-icons but it is not going to be installed
...........................Depends: gnome-shell-extension-ubuntu-dock but it is not going to be installed
...........................Depends: ubuntu-desktop-minimal but it is not going to be installed
...........................Depends: ubuntu-session but it is not going to be installed
...........................Recommends: gnome-initial-setup but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I get the same type of errors when I try to install each of those packages individually.
I've also tried sudo systemctl set-default graphical.target and rebooting, but it goes back to command line.
sudo startx fails as well, giving the error:

xauth error

I've tried following the comments on [this page][2] to no avail.
Tried these commands with similar errors as above:
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get install gnome-shell gnome-shell-extensions

... basically same issues as here.
 I tried the answer on this page, again, no luck.
 Same here too.
Comment: If installing katoolin breaks your system by requiring wrong-version packages, then consider uninstalling it. A and B, from your output, clearly seem to be incompatible.
Comment: I should mention that I want to get back to the GUI.
Comment: The Katoolin set of tools has been known to be difficult.  Moreso if you have done any upgrade since adding the sources for Katoolin.  [https://askubuntu.com/q/772495/283721](https://askubuntu.com/q/772495/283721)
Comment: What can I do to reverse this? There's nothing at /usr/bin/katoolin. I installed this from the /Downloads folder. I ran it again, and uninstalled all the Kali tools, sudo reboot took me back to the command line. Still no GUI.
Answer: You have apparently broken your system, as referred to in the github page for katoolin3:

Warning for Ubuntu users
Installing programs from repositories for different operating systems
is generally considered dangerous! Some packages might (and probably
will) break your system. Be careful when installing the tools and
don't blame katoolin3 for any inconveniences. The optimal solution is
to install specific tools from tools.kali.org. It is not recommended
to install all tools.

You could check this by asking what OS you are running (uname -a) but it is likely that your system is now a mix of Ubuntu and Kali, and unfortunately that don't always work in the way that either OS intends.
It is possible that with a some effort, you could get back to a stable Ubuntu 20.04 but the consensus of a search on this site for "remove katoolin tools" generally devolves into "reinstall Ubuntu"
Comment: :( I will be sure to use snapshots next time. I got a bit too cocky with the tool installs...


Div created table appears to break in Chrome

Question: It works in IE and Safari but breaks in Chrome.  You can view the page here http://www.archemarks.com.
It only breaks at a middle zoom point so you have to zoom in and zoom out and at this middle point the table breaks.
This made me think it was something minor that as the browser re-drew the page..the changing pixels available caused it to make something bigger than normal...or smaller and broke the layout.
Chrome has development tools which should make all of the CSS and HTML available.
I tried fiddling witht the size of the text in put box and the containing column and row..but this did not help as I was only guessing.
Any non-guessing advice.
I can repost the code but it might be easier to just view the site using Chrome Development Tools
Comment: It only happens for me when I *zoom out* a couple of times. Actual users almost never zoom *out*, so I don't think you should worry about it.
Comment: @thirtydot I was thinking the same thing, but this is the second question today about "when I zoom out it..." O_o
Answer: It's the width of your .t2_c1 rule.  At only 100px, it isn't wide enough for the Email Again text.  this is undoubtedly because of the font size conversion being just slightly off as the browser compensates for the zoom.  Changing the .t2_c1 rule width to 110px and then the .t2_c2 width to 250px fixes this issue.
Comment: you are a godly....that particular solution...breaks the table...I just widened the entire table by 10px .t1...and..widened t2.c1 by 10Px per your suggestion....than I had to relative position the file upload row by 10px...pretty much what you said...b.c. file upload was odd ball out...I thought that was the cause..but i was wrong..


.Net Core 3.1 Worker as Window Service Error [SC] StartService FAILED 1053:

Question: Unable to install .Net Core Worker as Window Service
Error:
<code>[SC] StartService FAILED 1053:
The service did not respond to the start or control request in a timely fashion.
</code>
Program class:
<code>public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .UseWindowsService()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            });
}
</code>
Command used to install exe:
<code>>sc.exe create MyService binpath="C:\MyService.exe" displayname="MyPostWS" start= auto

>sc.exe start DMSBatchService
</code>
Comment: You create "MyService", but then start "DMSBatchService"?
Answer: By looking at the given information, you could try a few things to check the issue.
First, check the logs in the event viewer.
Check the service is located at the specified path C:\MyService.exe.
Check whether your service has the necessary permissions like if it is running under a service account.
and last but not the least check your code by putting some logs


After 16.04 to 18.04 to 20.04 Release-Upgrade /usr/share/modules/init/sh No such file or directory

Question: Today I upgraded from Ubuntu 16.04 to 18.04 to 20.04
After Login I get the error

Error found when loading /etc/profile:

/etc/profile.d/modules.sh: line 6: usr/share/modules/init/sh: no such file or dicrectory

As a result the session will not be configured correctly.
You should fix the problem as soon as feasible

The code in etc/profile.d/modules.sh is:
shell=$(/usr/bin/basename $(/bin/ps -p $$ -ocomm=))

if [ -f /usr/share/modules/init/$shell ]; then
   . /usr/share/modules/init/$shell
else
   . /usr/share/modules/init/sh
fi

But
The path /usr/share/modules does not exist
How to adapt the script?
Answer: I did a fresh install of ubuntu 20.04 on VirtualBox and noticed that the file etc/profile.d/modules.sh does not exist in a fresh installation.
So I renamed the file etc/profile.d/modules.sh to etc/profile.d/modules.sh.ubuntu16.04 in order not to be executed
(pattern /etc/profile.d/*.sh within the /etc/profile does not match any more)
After that the error message does not appear any more.
Answer: Delete it
The /etc/profile.d/modules.sh script is a remnant of previous Ubuntu LTS releases. It may safely be deleted.
$ sudo rm /etc/profile.d/modules.sh

After doing so, the error message will no longer appear.
Answer: On my system, using
dpkg -S /etc/profile.d/modules.sh

showed that file /etc/profile.d/modules.sh belongs to apt package environment-modules.
Using commands to show dependencies on environment-modules, such as
apt-cache rdepends --installed environment-modules
apt -s remove environment-modules
aptitude why environment-modules

showed that environment-modules was actually neither needed by other packages nor even (fully) installed on my system.
Using commands to show historical apt package log data, such as
ls -rt /var/log/dpkg.log* | xargs zgrep install | less
ls -rt /var/log/dpkg.log* | xargs zgrep install | grep environment-modules

showed that, from all log entries mentioning environment-modules, most recently, environment-modules was only "half-installed".
And indeed, using dpkg -l | grep ^rc (see 1, 2) showed that environment-modules was apt-removed but not yet completely apt-purged.
I therefore concluded that it is safe to remove and purge the environment-modules package using
apt remove environment-modules
apt purge environment-modules

This purge did indeed remove file /etc/profile.d/modules.sh from my system. Since then, I got rid of aforementioned error message.