Question: I'm new to 3D printing and I was wondering about the risks of leaving my printer to print overnight? I'm aware that if something goes wrong I'll wake up to spaghetti for breakfast but what are the other things like having the nozzle and bed heated that long? And, when it's done it just sits there on so what could that do to the screen? What if the printer runs into some physical problem and damages itself and/or the print? I'm not looking for answers to these questions specifically just feedback on what I should do when printing overnight.

Answer:
Presuming that you're talking about an 8 hour period, your printer should be designed to run for 8 hours continuous anyway, so nothing will happen regarding the bed or screen that wouldn't happen with a normal print.
If the first few layers stick to the bed, it's likely that you're print will at least be partially completed. So even over night it won't be a full 8 hours of printing while failed. Maybe half that period.
If the problem is bed adhesion, or anything that doesn't effect the filament being supplied to the nozzle, then your only problem will be wasted filament and disposing of the spaghetti. No harm will come to your printer.
If the problem is a break in the filament or filament runout, or a blocked nozzle then you could have damage to the head of the nozzle from printing dry. If you're printing with PLA this isn't really something that you need to worry about too much as you can run a printer dry for several hours without any problems.
If you're printing with ABS or something that needs a hotter head then you could cause damage to it if it's allowed to run dry for an entire night. But again this isn't really something that you need to worry about unless it's running dry for 4 or 6 hours.
Simply checking in on it once in the night should be enough to prevent any problems.


Question: I'm having a lot of issues leveling my printer and one failed print came out like this. Is there something wrong with the surface that I need a new bed? This happens to me quite often and I literally can't get it off.

Answer:
Presuming that you're talking about an 8 hour period, your printer should be designed to run for 8 hours continuous anyway, so nothing will happen regarding the bed or screen that wouldn't happen with a normal print.
If the first few layers stick to the bed, it's likely that you're print will at least be partially completed. So even over night it won't be a full 8 hours of printing while failed. Maybe half that period.
If the problem is bed adhesion, or anything that doesn't effect the filament being supplied to the nozzle, then your only problem will be wasted filament and disposing of the spaghetti. No harm will come to your printer.
If the problem is a break in the filament or filament runout, or a blocked nozzle then you could have damage to the head of the nozzle from printing dry. If you're printing with PLA this isn't really something that you need to worry about too much as you can run a printer dry for several hours without any problems.
If you're printing with ABS or something that needs a hotter head then you could cause damage to it if it's allowed to run dry for an entire night. But again this isn't really something that you need to worry about unless it's running dry for 4 or 6 hours.
Simply checking in on it once in the night should be enough to prevent any problems.


Question:
I recently burnt out one of the MOSFETS on my RAMPS 1.4 board on my Sintron Kossel clone so have upgraded it to a RAMPS 1.6.
Now my printer seems to only print 50 % of the intended size.

After the machine homes it only comes down about 50 % of the distance and so starts printing in mid air.

I thought it might have been the driver steps? The DRV 8825 drivers are 32 steps instead of 16. I changed this value in the firmware but it didn't make any difference.

Any suggestions?

Answer:
Data from Firmware is not written into EEPROM on its own after updating your firmware. You need to send a
```
M502
```
to "seed" the firmware numbers as that is restoring the "default" settings in it. If you are unsure what is currently the EEPROM setting, use
```
M503
```
first.


Question:
I printed a G1/8 thread in PLA where I can connect a compressor to have a small pressure container. Even though all measurements are correct and it screws in fine, it still leaks air.

Is there a way to make 3D prints airtight?

Answer:
Yes.
The issue is, that there are small gaps between the layers. But you can coat the print in an airtight material. While epoxy and similar materials work very well, they are somewhat too viscous and take a long time to cure.
My special recipe for coating PLA prints with a fast-curing airtight thin layer is:
Dissolve 1 g Paraloid B-72 in 20 ml acetone.
Dip or otherwise evenly coat the print and dry at room temperature for 10-20 minutes.


Question:
I'm a beginner in 3d printing, so please bear with me.

I downloaded a zip with about 100 STL files. I now want to pick one or two to print. The names of the stl files are not very helpful so I need to look at them to find the ones I want. I can open all of them one by one using Cura, or Tinkercad, but that is a very slow and long process with so many files. Ideally I would like to have an overview of all the files in little previews so that I can get an idea what they are to narrow down which files I need to open to inspect the details.

Is there a program with which I can do something like that? I'm on Linux, but tips about Windows/Mac software would also help since I can use it to search for Linux alternatives to that software. All tips are welcome!

Answer:
Cura's probably your best bet.  You can select several STL files and it will open them all, (memory allowing) then try to place them for printing.  If they can't fit on your print bed the items get placed off to the side.  Clicking on the object will show its name in the lower-left, so you can go rename the file to be more representative.
Tinkercad can only import one item at a time, and tops out at 25 Mbytes.


Question:
I am new to 3D printing. I own jewelry stores and want to 3D print my jewelry packaging for rings, necklaces, and bangles as in the picture below:

I have two main problems:

Is 3D printing capable of building this package?

I know I can build boxes for jewelry with the outside being made of plastic. But I want the inside to be like a sponge. Is there a filament or a way to print a filament to make it look like cloth or a sponge?

Are there printers on the market which are able to print several copies without the need to set up each time it finishes a single box?

Answer:
With the right materials
With the right material, you can get flexible surfaces and prints. Just two random examples:
TPU is a flexible material, which can be used to print something like "Lips" that flex and take the jewelry or even strings that suspend the piece in the center.
Foaming TPU is a variant of normal TPU that expands during printing. This makes it somewhat spongey.
However, those have downsides: they don't make good rigid shells, so you will need two different materials: one hard for the shell, and something flexible for the holder.
Luckily, any direct drive filament printer can work with flexible filaments, and there are some flexible filaments that work with a Bowden setup. Due to dissimilar materials though, you need to either assemble the part or buy a somewhat specialized printer: one with two nozzles. These are available but are way out of hobby-grade pricing.
Also, you will never get the "smooth" silky look of a fabric insert cover, but always a clearly industrial printed surface.


Question:
I'm quite new to 3D CAD and printing.
I own a Dremel 3D45 and I use FreeCad / Ultimaker Cura as softwares.

My question is pretty simple.
Say you have to make one object with a pin and another with a hole. They should be coupled together. Of course if you set the diameters of the pin and the hole equal the won't fit!

Right now I'm setting the hole larger of 0.2 mm and the pin smaller of 0.2 mm. This allow a quite good coupling (not so hard but with some resistance).

I guess this tolerance (0.4 mm in my example) depends on a lot of variables: 3D printer settings, material, etc... so it may change using different setup.

How to correctly handle this?

Should I add a variable in my CAD spreadsheet and use it to change the nominal diameter of the coupling items?

I don't think so, but anyway: is there a settings in Ultimaker Cura that allow to compensate an hole or a pin by a specified amount?

Any other suggestion is gladly accepted.

Answer:
I guess this tolerance (0.4 mm in my example) depends on a lot of variables: 3D printer settings, material, etc... so it may change using different setup.
Tolerances required
depend on the geometry you're printing
. A hole that is horizontal, vertical, or diagonal will need different tolerance (as I found out in a project that used the same steel dowel pins in three different orientations). And, vertical holes and pins are different from flat-sided shapes: the plastic will be pulled toward the center of a curve, so diameters come out small (and more so for holes since there's no material further inward to resist the movement).
That said, I think you can expect that the distortions of printing are fairly consistent, if your printer is functioning well. I have a Prusa i3 MK3S, and I have printed many parts other people have designed, and
when
those parts have been designed carefully, I almost always get very good fits between parts. So, my experience suggests that models do not necessarily need tuning for specific printers.
Should I add a variable in my CAD spreadsheet and use it to change the nominal diameter of the coupling items?
Yes. If nothing else, this allows you to define how the two parts
should
fit together separately for the printing error. Use separate numbers for different shapes/fits, so that you can adjust one without messing up another.


Question:
What slicers have support for belt printers like the CR-30?  Or what slicers can have an add-on, plugin, or extension added to them to support it (from a user level, not a dev level).

I found more total slicers than I expected, since I was only expecting 3 (Cura, PrusaSlicer, Simplify3d).  Surely that means I'm missing out on more, if there are already so many different slicers.

Creality Slicer - Comes from the OEM of the printer

Blackbelt Cura - Everyone who mentions it says don't use it because it's old

Raise3d Ideamaker - Seems to be based on Flashforge's slicer, has some interesting features too.  Not as configurable as Slic3r or PrusaSlicer though.

Answer:
I think most slicers don't distinguish printers based on if they have belts or delta configuration, etc.  The slicer generates gcode, and the firmware on the printer translates the gcode into actuator motions specific to that printer to perform the gcode.
The difference slicers generally care about is if it is a FFF printer that extrudes a bead or a resin printer that solidifies liquid.   Many other 3d printing methods exist, but those to are the most common ones supported by most of the open slicers.


Question:
I'm printing a ring that's a replacement for the non-slip base of a mixing bowl. The ring is about 130mm in diameter, with a rectangular cross section, like this:

I'm using Cura as the slicer, and I've set the infill to 100% and concentric, but after slicing it looks like Cura used lines instead; the ring is filled with parallel straight lines:

Is this a problem with Cura? Is there something I can do to encourage it to use concentric infill? I don't really care what the infill pattern is, but I think concentric would print a lot faster since the head wouldn't have to switch directions all the time.

Answer:
Is this a problem with Cura?
I don't know if the good folks at Ultimaker consider this a bug or a feature, but it appears that Cura uses the
```
Lines
```
option regardless of the
Infill Pattern
setting when
Infill Density
is set to
```
100%
```
. There may well be some reason for that; for example, the fact that the
```
Lines
```
option alternates the direction of the lines from one layer to the next probably makes for stronger parts.
Is there something I can do to encourage it to use concentric infill?
Yes!
It turns out that setting
Infill Density
to anything less than
```
100%
```
gives the expected concentric infill (provided
Infill Pattern
is set to
```
Concentric
```
, of course). When I changed the setting to
```
99.99%
```
and re-sliced, I got concentric infill in the Preview panel. I haven't tried printing yet, but I have no doubt that I'll get the same thing in the actual print.
I don't really care what the infill pattern is, but I think concentric would print a lot faster
With
Infill Density
set to
```
99.99%
```
and
Infill Pattern
set to
```
Concentric
```
, the estimated time to print my part drops from 4 hours 50 minutes to 2 hours 44 minutes,
a 44% time savings compared to 100% infill
. That's probably a lot more savings than you'd get on a part that wasn't so narrow, but it's worth knowing that at least some parts can print much faster with concentric infill.


Question:
On my Ender 3 v2 printer I recently and consistently get some knocking.
This happens in only two scenarios.

First, it now occurs all the time when printing the initial test strip gets near the top (high Y value), and knocks several times.

Secondly, it occurs if the model (sliced with Cura) has a high Y value (eg: if the model occupies most of the bed).
(If there is room and I move the model - in Cura - closer to the front there is no knocking.)
On the first 10 (or so) layers the printer sometimes knocks when a high Y value is reached and the entire model is thereafter shifted to the front by a few millimeters.

There is a third scenario. At the end of a print the print head is in the middle of the bed and moves up 20 mm then travels directly to the top left corner. At this corner there are 4 or 5 "knocks" (and the nozzle is 20 mm above the bed).

Any suggestions to diagnose/fix this problem will be much appreciated.

Answer:
Your bed has become unleveled or skewed in Y direction.
When the nozzle is closer to the bed the extruder has to push harder to get the same filament flow through a smaller space, the stresses the extruder to a point that the stepper skips or grinds the filament. This is generally described as a knocking sound.
You need to find out why the bed is higher at the upper end of the Y range and fix this. Otherwise your bed has become warped and may need to be replaced. There are alternatives in using a sensor (e.g. a BLTouch) to sense the shape of the print surface, it will then automatically adjust for the shape during the first 10 mm (default value) of your print product. Installing a sensor requires new or alternative firmware.


Question:
I'm using an Ender 5 with standard PLA and Creality slicer 4.8.2.

How can I deliberately maximise stringing, and if possible get it to be as consistent as possible.

My aim is to have "thousands of hair like threads strung between two rocky pillars".

If possible I'd like to do this in the slicer with PLA, rather than using cotton or some other material after the model has printed.

Answer:
Slicers will perform a retraction when moving from one solid to another, the value of which is part of the settings. I've not researched if a specific slicer will allow a negative retraction, but if it's possible, it's likely to create adjustable stringing.
If negative retraction is not possible, one can identify the retraction segments in g-code of the print and find/replace those values with extrude rather than retract. My slicer, Simplify3D does not support reversed retraction, but the code is clear when examined with a text editor:
```
```
G1 E-4.0000 F2400
G1 Z0.300 F1200
G1 X118.760 Y117.415 F12000
G1 Z0.250 F1200
G1 E0.0000 F2400
G92 E0.0000
G1 X122.415 Y113.760 E0.0972 F900
build g-code removed for clarity
G1 X118.760 Y117.415 E1.5303
G92 E0.0000
G1 E-4.0000 F2400
G1 Z0.300 F1200
G1 X158.280 Y117.216 F12000
G1 Z0.250 F1200
G1 E0.0000 F2400
G92 E0.0000
G1 X162.216 Y113.280 E0.1047 F900
build g-code removed for clarity
G1 X158.280 Y117.216 E1.5902
G92 E0.0000
G1 E-4.0000 F2400
build g-code removed for clarity
G1 E0.0000 F2400
G92 E0.0000
G1 X162.415 Y113.760 E0.0972 F900
build g-code removed for clarity
G1 X158.760 Y117.415 E1.5303
G92 E0.0000
G1 E-4.0000 F2400
```
```
All entries beginning with G1 E-4.0000 represent the 4 mm retraction called by the slicer. One could search for just that code and replace it with a positive value. Some experimentation is indicated to accomplish the desired result. The F value is feed rate and presents another value to adjust.
Pursuant to Oscar's comment, I overlooked the lack of movement as a factor. He is correct, such a modification is likely to create a blob. As a possible compensation, a better modification would be to create a custom extrusion code with a reduced flow rate, using the existing code as a reference.
This starts to complicate the process substantially, requiring far more calculations and edits. I suggest that it could yet be accomplished, but would be more easily done so with post processing of the code via Python or similar, with which I am not qualified to address.


Question:
I have 12 parts for a model I want to print but I would like to know if I can put all of them in a single G-code file and print that on its own. Would this affect the model in any way?

I’m using PLA on my Ender 3 Pro

Answer:
This answer assumes FDM printing -- for resin printers, as I understand it, as long as there's flow space between parts, if they fit on the build plate, they'll print.
For FDM, generally, you'll get better print quality printing a single part, because layers don't cool while you print the same layer for each of the other parts (meaning layer adhesion will be better).  That said, if the parts are very small, this additional cooling may be an improvement vs. having to set your slicer to provide a pause between layers to avoid slumps and layer spreading.
A compromise, if the parts are low enough, is that most slicers can be instructed to print the parts sequentially -- that is, print all of part A, then all of part B, and so forth.  This has some limitation in that all parts already printed must clear parts of the machine, and may also require larger clearance between parts for items like fan shrouds.
But printing a bunch of parts at one time does work, if the compromises in layer adhesion and other quality issues related to traveling between parts are acceptable.  The only way to be sure is to print the whole lot (perhaps with a large nozzle and thick layers, low infill, etc. to minimize filament consumption and print time) and see if they're good enough.


Question: I'm attaching a picture to show my issue. I'm hoping might be an easy settings fix, or at least maybe someone has a couple suggestions I can try. I'm using an Ender 3, and the program Cura. The print on the left was printed with the opening facing up. The print on the right with the hole facing down. The support leaves a rough surface. Any suggestions for support settings would be appreciated.

Answer:
There's only so much you can do about this without a multi-material printer that can utilize dissolvable material or material that doesn't bond to the print material, and print the supports at zero distance from the model. So expect it to be ugly. But not quite that ugly.
Slicers, including Cura, have options to control the Z distance between the support material and your model, among other things. Reducing this will make it harder to remove the supports, but will give a better bottom surface. It only really works on whole-layer granularity in Cura (while some other slicers let you do arbitrary distances), and really should always be equal to one layer. A distance of two or more layers will give really bad results, which might be what you're seeing.
Also, Cura has an option called "support interface", which you want on. This prints a flat top surface on top of the support, below your print, so that all the lines of the print have something they're resting on. Without this, the bottom surface over the support will sag down between the lines of the support and look very bad - or, if it's a small detail, it might sink entirely between lines of the support and effectively not be supported at all!
Finally, one hack you can try if you don't have a multi-material printer but want to try printing supports at zero distance from your model: set support Z distance to zero and use a slicer plugin to pause-at-height just past the top surface of the support. Then, when the printer pauses, paint a release agent that won't bond to the print material on top of the support. Reportedly Sharpie permanent markers work as such a release agent, but I haven't tried this, and there are probably better choices.


Question:
I am trying to create a couple of holders for my ultrasonic cleaners. They are supposed to be used for parts that don't fit in the holder that came with the cleaners. I was wondering what material is best to use for this.

My initial thoughts are:

Material should hold up to the cleaning solution, I have a wide range of them from degreaser, deruster, and so on. I would say PETG or PLA should be a safe bet as it reacts with almost nothing

Material should not have issues with warm (not hot) water, I'd say something along the lines of 60-80 °C. This already eliminates PLA, but I think PETG should still be OK-ish (I am aiming more towards 60 °C than 80 °C).

Is there something I am missing? Does anyone have any input? I am anyway just going to do a few tests, but I assume starting with PETG is a good start.

Answer:
This is going to be hard. Even holding a vacuum is hard (I've tried it and not succeeded). I'm not sure what the mechanism of air molecules getting thru the print is - whether it's defects in inter-layer bonding, defects at seams, imperfect mating with the fitting, or even permeability of the plastic itself. It might not actually be existing flaws in the print, but rather the high pressure being a stronger force than the bonded layers can withstand, essentially ripping the layers apart from the weakest point until the pressure can discharge through the opening produced.
If using ABS, you might try an acetone bath followed by a long period of trying or use of vacuum chamber to quickly remove the solvent, if you can stand some possible part deformation. This would tend to fill any gaps. Coating with low-viscosity CA glue (Loctite 420 or equivalent) might be a better version of this approach, as the solvent will both attack the ABS and deliver fill material.
In principle PET (maybe also PETG, but PET is preferable anyway if you can get it) should be a suitable material for pressure vessels, as it's what's used for soda bottles at comparable pressure, but those are blown from a single piece, not fused together with seams.
At some point I will attempt this again, and will update my answer if I have any findings that contribute to your question.


Question:
It is difficult to describe with words what's happening, so take a look at the picture. Somehow PrusaSlicer decides to move and print in the air (blue line), where instead it can continue going from outwards to inward. I understand it wants to print first the outer layer but in this case it is obvious it will not hold that layer.

The final position is shown in the second image.

The final step of that layer:

Any idea how to configure PrusaSlicer to avoid this situation?

Answer:
You'll want to turn on supports, which will create a series of low density pillars in the "floating" area and provide a foundation for the layer that is printing mid-air in your second image.
Another option is to create a hollow support cylinder perhaps a half millimeter larger diameter than the hole in the floating layer. This creates the support for the inner diameter and allows the printer to create bridges.
The former method will use more filament and take longer to print but provide a better under-surface than the latter method.


Question:
I'm struggling to find out an enclosed 3D printer that allow to load the common 1 kg filament bobbins. Most of the enclosed ones accept only proprietary bobbins (like Dremel or Flashforge).

Do these bobbins ( = 1 kg) rely on a specific standard I can search for?
How to filter out the printers that match my request when making a Google search?

I'm aware I can "easily" put them out of the machine using a custom support (or even directly in a dryer as I do for my Dremel) but this partially nullifies the advantage of the enclosure.

Answer:
QIDI Tech makes a series of enclosed printers, which would narrow your search a bit. I own an X-Max model which has an internal spool spindle as standard equipment, along with an "ordinary" external mount. The internal spindle will take a standard one kilogram spool. It's considered good practice when printing moisture sensitive filament such as nylon to have such an environment.
With respect to search terms, it's fairly difficult to identify a phrase that would collect the information you require.


Question:
I'm new in the 3D priting and I bought a BIQU B1 printer :-)

I printed the Pokemon with the white filament that come as a sample with the printer (PLA) and after that I bought the Inland PLA+ and PETG+ from Microcenter.
The first thing that my son asked me to print is the toaster.
Well, I tried to print three times with the PETG+ filament and always I end up after one or two layers with oozie everywhere and I had to stop printing.
I replaced the filament with the PLA+ and now it's printing correctly (It's 91% complete right now :-) )

So, I set the correct temperator for both filaments:

PLA+ 205/60

PETG+ 230/70

I'm thinking that for this type of object (torture toaster) it doesn't work with PETG because of the complexity.

Is that correct? If not, what I could be doing wrong with PETG+ filament?

Answer:
You are getting warping. It's unusual in this case, as your overall model is relatively low profile. It's the taller stuff that likes to warp.
Consider to edit your post to include the layer heights and also the filament type and filament and bed temperatures. My first instinct is that your bed temperature is too low. There's little harm to be had by raising the temperature by ten degrees or so. Also if your slicer arbitrarily reduces the bed temperature after the first layers, disable that feature. There's no sense to set a good adhesion temperature on a print and later reduce it, yet I've seen slicer results that do just that.
Too cold filament by a substantial amount can also reduce the adhesion in combination with a too low bed temperature.
If you still run into adhesion problems, the Elmer's Purple Glue Stick works wonders.
With the new information comes new responses:
For ABS, 80 °C is on the low end for the bed, but may work. The extruder temp is really low for ABS. I run 250 °C for ABS. Also ensure some form of enclosure, even a cardboard box will help. I've accidentally fed ABS into a PLA profile. The results were surprisingly good, although warping was prevalent and some underextrusion was evident.
If you have a glass bed, you will very much want to use glue stick, as a release agent, not as an adhesive. ABS sticks really well to clean glass, well enough that it will pull fragments of glass from the surface!


Question:
I just purchased this Ender 3 Pro about 1 week ago and since then I've been having nightmares with leveling/tramming the printer bed. From having to tram it again after every print to not being able to level it at all.
Since then I've been reading and watching a lot of problem-related content to try and find a solution.

The two most recommended upgrades were a glass bed and stiffer springs for the bed so that's what I bought. I purchased the original Creality glass bed and the yellow springs and for a day or so I got it to work in an acceptable way but I still had to tram the bed every couple of prints.
Today for some unknown reason, I woke up and I can't seem to get my bed leveled in the middle. I've tried every possible solution that crossed my mind but the middle of the bed is still too far from the nozzle and the filament won't stick.

Answer:
Not exactly the type of answer you probably want, but this hotend does not look servicable. The nozzle is usually considered a consumable part unless it's made of something like tungsten carbide, or at least steel. The nozzle is almost surely long past its useful life unless the printer was barely used, and the entire hotend has lots of design flaws like very small thermal mass and heat sink butting up against the heater block, which defeats the purpose of having a heat sink.
The right solution here is to figure out what kind of attachment it's supposed to use (dimensions of that groove mount) and buy or put together a replacement hotend.


Question:
In a review for a certain filament I read that somebody recommended "a feeding rate of 105%".

What does he mean, and how could I set this in Cura?

When I search for "feed" in the print settings properties of Cura, nothing is found, so I suspect he means "speed".

When I search for speed, multiple speed settings turn up, not only one.

How could I do what he recommended?

Thank you!

Answer:
[Extruder] feed rate [modifier] is used synonymous to extrusion multiplier
The feed rate of the extruder is the rate at which filament is pushed (fed) into the hotend. An overwrite value that modifies that rate from the normal rate is in most slicers called "extrusion multiplier".
It is a
quickfix
to manipulate print behavior, especially addressing under extrusion due to various problems, such as mis-sized filament or to compensate for deformability of it compared to the filament the extruder is calibrated for.
It is however not a permanent fix. See also
here
,
here
and
here.


Question:
I am new to 3D printing. I have a Longer LK5 Pro. I was making a part that has raised letters, and wanted to have white letters on the black part. I used a Post Processing script on the Cura program called "change filament", which is supposed to stop printing, retract the head, and allow you to change the filament. Mine just keeps on printing. I've tried "pause" and done the filament change, but unsuccessfully so far because of blobs deposited on the letters.

Any suggestions?

Answer:
I've done it a few ways depending on the desired effect I'm after.
Manually pausing the machine is what seems to come out best. If you design for it, you can sometimes have it pause while it's over infill and therefore has no blobs to worry about. I haven't looked into doing it automatically, but perhaps it's possible to pause partway through a layer.
If the design doesn't have to be flat, then I'll do a solid colour and the last top layers another colour with the design cut out. This is to my mind optimal as you get a bit of texture with the design inset as well as different colour and makes for a nice clean method.
The other way was z-hopping which is an idea I got from a Youtube video. Cura has a setting for this. Basically you can make the nozzle lift when it moves. You split the colours into two separate objects and you print in one colour. Then you change filament and print another colour as a separate print right over the top of it and the nozzle hops over the original print.


Question:
Can someone shed some light in why FDM (Fuse Deposition Modelling) is not possible with metals?

Has anyone attempted any experiments with it?

Answer: For many metals you would need to run the hotend around 1000 °C.  Aluminum melts at a lower temperature but needs to be in an inert atmosphere, such as argon.  Solder melts at the right temperature, but tends to stick to most metal nozzles.  It would start dissolving a brass nozzle thus enlarging the nozzle opening.  Lockheed has a titanium alloy printer that melts powder with a laser.  I would assume they need an inert atmosphere since titanium reacts with nitrogen as well as oxygen.


Question:
This is a follow up question for What are viable substitutes for Raspberry Pi to run Octoprint or similar software for Prusa i3 MK3S+?

I was able to grab Raspberry Pi 400 for around $70, so at MSRP, and about half of the current pi 4b prices nowadays. Good deal given shortages, so I ordered it when it was available, and only now I started to think if I can really use it.

Thus, are there any special challenges to using Raspberry Pi 400 as OctoPrint server, and does it have any benefits over regular Pi 4B? Is there any ready-made manual about it I could use?

Answer:
The recommended hardware for OctoPi is
listed
as:
Recommended hardware: Raspberry Pi 3B, 3B+, 4B or Zero 2. Expect print artifacts and long loading times with other options, especially when adding a webcam or installing third-party plugins.
Now if we compare the specification of the two Pi units:
Raspberry Pi
Processor
RAM
400
BCM2711 quad-core Cortex-A72 @ 1.8GHz
4GB LPDDR4-3200
4B
BCM2711 quad-core Cortex-A72 @ 1.5GHz
1GB, 2GB, 4GB, 8GB LPDDR4-3200
So they are very close in capabilities. The 4B has a slightly slower processor but does have the ability to have more RAM. The 400 does come with a keyboard but its feasibility would depend on your usage (probably not much for OctoPi).
Given the slight disparity in specs, the Raspberry Pi 400 should work fine for OctoPi.


Question:
I want to assign the decimal variable "trans" to the double variable "this.Opacity".

decimal trans = trackBar1.Value / 5000;
this.Opacity = trans;

When I build the app it gives the following error:

Cannot implicitly convert type decimal to double

Answer:
An explicit cast to
```
double
```
like this isn't necessary:
```
```
double trans = (double) trackBar1.Value / 5000.0;
```
```
Identifying the constant as
```
5000.0
```
(or as
```
5000d
```
) is sufficient:
```
```
double trans = trackBar1.Value / 5000.0;
double trans = trackBar1.Value / 5000d;
```
```


Question:
I have an absolutely positioned div containing several children, one of which is a relatively positioned div. When I use a percentage-based width on the child div, it collapses to 0 width on IE7, but not on Firefox or Safari.

If I use pixel width, it works. If the parent is relatively positioned, the percentage width on the child works.

Is there something I'm missing here?

Is there an easy fix for this besides the pixel-based width on the child?

Is there an area of the CSS specification that covers this?

Answer:
The parent
```
div
```
needs to have a defined
```
width
```
, either in pixels or as a percentage. In Internet Explorer 7, the parent
```
div
```
needs a defined
```
width
```
for child percentage
```
div
```
s to work correctly.


Question: Given a DateTime representing a person's birthday, how do I calculate their age in years?

Answer:
The best way that I know of because of leap years and everything is:
```
```
DateTime birthDate = new DateTime(2000,3,1);
int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);
```
```


Question:
Given a specific DateTime value, how do I display relative time, like:

2 hours ago

3 days ago

a month ago

Answer:
Here's how I do it
```
```
var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
double delta = Math.Abs(ts.TotalSeconds);

if (delta < 60)
{
  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 60 * 2)
{
  return "a minute ago";
}
if (delta < 45 * 60)
{
  return ts.Minutes + " minutes ago";
}
if (delta < 90 * 60)
{
  return "an hour ago";
}
if (delta < 24 * 60 * 60)
{
  return ts.Hours + " hours ago";
}
if (delta < 48 * 60 * 60)
{
  return "yesterday";
}
if (delta < 30 * 24 * 60 * 60)
{
  return ts.Days + " days ago";
}
if (delta < 12 * 30 * 24 * 60 * 60)
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  return months <= 1 ? "one month ago" : months + " months ago";
}
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
```
```
Suggestions? Comments? Ways to improve this algorithm?


Question: What is the difference between Math.Floor() and Math.Truncate() in .NET?

Answer:
```
Math.Floor
```
rounds down,
```
Math.Ceiling
```
rounds up, and
```
Math.Truncate
```
rounds towards zero. Thus,
```
Math.Truncate
```
is like
```
Math.Floor
```
for positive numbers, and like
```
Math.Ceiling
```
for negative numbers. Here's the
reference
.
For completeness,
```
Math.Round
```
rounds to the nearest integer. If the number is exactly midway between two integers, then it rounds towards the even one.
Reference.
See also:
Pax Diablo's answer
. Highly recommended!


Question: How do I store binary data in MySQL?

Answer:
For a table like this:
```
```
CREATE TABLE binary_data (
    id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    description CHAR(50),
    bin_data LONGBLOB,
    filename CHAR(50),
    filesize CHAR(50),
    filetype CHAR(50)
);
```
```
Here is a PHP example:
```
```
<?php
    // store.php3 - by Florian Dittmer <dittmer@gmx.net>
    // Example php script to demonstrate the storing of binary files into
    // an sql database. More information can be found at http://www.phpbuilder.com/
?>

    <title>Store binary data into SQL Database</title>

        <?php
            // Code that will be executed if the form has been submitted:

            if ($submit) {
                // Connect to the database (you may have to adjust
                // the hostname, username or password).

                mysql_connect("localhost", "root", "password");
                mysql_select_db("binary_data");

                $data = mysql_real_escape_string(fread(fopen($form_data, "r"), filesize($form_data)));

                $result = mysql_query("INSERT INTO binary_data (description, bin_data, filename, filesize, filetype) ".
                                    "VALUES ('$form_description', '$data', '$form_data_name', '$form_data_size', '$form_data_type')");

                $id= mysql_insert_id();
                print "
This file has the following Database ID: $id";

                mysql_close();
            } else {

                // else show the form to submit new data:
        ?>
        <form method="post" action="<?php echo $PHP_SELF; ?>" enctype="multipart/form-data">
            File Description:

            <input type="text" name="form_description"  size="40">
            <input type="hidden" name="MAX_FILE_SIZE" value="1000000">

File to upload/store in database:

            <input type="file" name="form_data"  size="40">

<input type="submit" name="submit" value="submit">
        </form>

        <?php
            }
        ?>

```
```


Question: If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?

Answer:
Here is one hack
that may work. It isn't clean, but it looks like it might work:
Essentially, you just try to update a column that doesn't exist.


Question:
How do I forcefully unload a ByteArray from memory using ActionScript 3?

I have tried the following:

// First non-working solution
byteArray.length = 0;
byteArray = new ByteArray();

// Second non-working solution
for ( var i:int=0; i < byteArray.length; i++ ) {
    byteArray[i] = null;
}

Answer:
Have a look at this article
http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html
IANA actionscript programmer, however the feeling I'm getting is that, because the garbage collector might not run when you want it to.
Hence
http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/
So I'd recommend trying out their collection code and see if it helps
```
```
private var gcCount:int;
private function startGCCycle():void{
    gcCount = 0;
    addEventListener(Event.ENTER_FRAME, doGC);
}
private function doGC(evt:Event):void{
    flash.system.System.gc();
    if(++gcCount > 1){
        removeEventListener(Event.ENTER_FRAME, doGC);
        setTimeout(lastGC, 40);
    }
}
private function lastGC():void{
    flash.system.System.gc();
}
```
```


Question:
I am aware that in .NET there are three timer types (see Comparing the Timer Classes in the .NET Framework Class Library). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable.

The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy.

The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything to the application closes.

I tried adding a while true loop, but then the main thread is too busy when the timer does go off.

Answer:
Consider using a
ManualResetEvent
to block the main thread at the end of its processing, and call
```
Reset()
```
on it once the timer's processing has finished.  If this is something that needs to run continuously, consider moving this into a service process instead of a console app.


Question:
I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface.

How does one go about writing 'hooks' into their code so that plugins can attach to specific events?

Answer:
I believe the easiest way would be to follow Jeff's own advice and have a look around the existing code. Try looking at WordPress, Drupal, Joomla, and other well-known PHP-based CMS to see how their API hooks look and feel. This way you can even get ideas you may have not thought of previously to make things a little more robust.
A more direct answer would be to write general files that they would "include_once" into their file that would provide the usability they would need. This would be broken up into categories and NOT provided in one MASSIVE "hooks.php" file. Be careful though, because what ends up happening is that files that they include end up having more and more dependencies and functionality improves. Try to keep API dependencies low. I.E fewer files for them to include.


Question:
I have a DataTable with a Name column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the order by clause.

var names =
    (from DataRow dr in dataTable.Rows
    orderby (string)dr["Name"]
    select (string)dr["Name"]).Distinct();

Why does the orderby not get enforced?

Answer:
The problem is that the Distinct
 operator does not grant that it will
 maintain the original order of
 values.
So your query will need to work like this
```
```
var names = (from DataRow dr in dataTable.Rows
             select (string)dr["Name"]).Distinct().OrderBy( name => name );
```
```


Question: How do you page through a collection in LINQ given that you have a startIndex and a count?

Answer:
It is very simple with the
```
Skip
```
and
```
Take
```
extension methods.
```
```
var query = from i in ideas
            select i;

var paggedCollection = query.Skip(startIndex).Take(count);
```
```


Question:
I want to format my existing comments as 'RDoc comments' so they can be viewed using ri.

What are some recommended resources for starting out using RDoc?

Answer: RDoc uses SimpleMarkup so it's fairly simple to create lists, etc. using *, - or a number. It also treats lines that are indented at the same column number as part of the same paragraph until there is an empty line which signifies a new paragraph. Do you have a few examples of comments you want RDoc'ed so we could show you how to do them and then you could extrapolate that for the rest of your comments?


Question:
What are the best practices around creating flat file database structures in PHP?

A lot of more matured PHP flat file frameworks out there which I attempt to implement SQL-like query syntax which is over the top for my purposes in most cases. (I would just use a database at that point).

Are there any elegant tricks out there to get good performance and features with a small code overhead?

Answer:
One framework I'm considering would be for a blogging platform. Since just about any possible view of data you would want would be sorted by date, I was thinking about this structure:
One directory per content node:
```
```
./content/YYYYMMDDHHMMSS/
```
```
Subdirectories of each node including
```
```
/tags
/authors
/comments
```
```
As well as simple text files in the node directory for pre- and post-rendered content and the like.
This would allow a simple PHP
```
glob()
```
call (and probably a reversal of the result array) to query on just about anything within the content structure:
```
```
glob("content/*/tags/funny");
```
```
Would return paths including all articles tagged "funny".


Question:
Is there an existing application or library in Java which will allow me to convert a CSV data file to XML file?

The XML tags would be provided through possibly the first row containing column headings.

Answer:
This may be too basic or limited of a solution, but couldn't you do a
```
String.split()
```
on each line of the file, remembering the result array of the first line to generate the XML, and just spit each line's array data out with the proper XML elements padding each iteration of a loop?


Question: Does anyone know of a good way to compress or decompress files and folders in C# quickly? Handling large files might be necessary.

Answer:
As of .Net 1.1 the only available method is reaching into the java libraries.
Using the Zip Classes in the J# Class Libraries to Compress Files and Data with C#
Not sure if this has changed in recent versions.


Question:
Stack Overflow has a subversion version number at the bottom:

svn revision: 679

I want to use such automatic versioning with my .NET Web Site/Application, Windows Forms, WPD projects/solutions.

How do I implement this?

Answer:
You can do it by adding the following anywhere in your code
```
```
$Id:$
```
```
So for example @Jeff did:
```
```

svn revision: $Id:$

```
```
and when checked in the server replaced $Id:$ with the current revision number.  I also
found this reference
.
There is also
$Date:$
,
$Rev:$
,
$Revision:$


Question:
I want to get my databases under version control.

I'll always want to have at least some data in there (as alumb mentions: user types and administrators). I'll also often want a large collection of generated test data for performance measurements.

How would I apply version control to my database?

Answer:
This is one of the "hard problems" surrounding development. As far as I know there are no perfect solutions.
If you only need to store the database structure and not the data you can export the database as SQL queries. (in Enterprise Manager: Right click on database -> Generate SQL script. I recommend setting the "create one file per object" on the options tab) You can then commit these text files to svn and make use of svn's diff and logging functions.
I have this tied together with a Batch script that takes a couple parameters and sets up the database. I also added some additional queries that enter default data like user types and the admin user. (If you want more info on this, post something and I can put the script somewhere accessible)
If you need to keep all of the data as well, I recommend keeping a back up of the database and using Redgate (
http://www.red-gate.com/
) products to do the comparisons. They don't come cheap, but they are worth every penny.


Question:
I want to be able to display a normal YouTube video with overlaid annotations, consisting of coloured rectangles for each frame. The only requirement is that this should be done programmatically.

YouTube has annotations now, but require you to use their front end to create them by hand. I want to be able to generate them. What's the best way of doing this?

Some ideas:

Build your own Flash player (ew?)

Somehow draw over the YouTube Flash player. Will this work?

Reverse engineer & hijack YouTube's annotation system. Either messing with the local files or redirecting its attempt to download
  the annotations. (using Greasemonkey? Firefox plugin?)

Idea that doesn't count:

download the video

Answer:
The player itself has a
Javascript API
that might be useful for syncing the video if you choose to make your own
```
annotation-thingamajig
```
.


Question:
This is something I've pseudo-solved many times and have never quite found a solution for.

The problem is to come up with a way to generate N colors, that are as distinguishable as possible where N is a parameter.

Answer:
I've read somewhere the human eye can't distinguish between less than 4 values apart. so This is something to keep in mind. The following algorithm does not compensate for this.
I'm not sure this is exactly what you want, but this is one way to randomly generate non-repeating color values:
(beware, inconsistent pseudo-code ahead)
```
```
//colors entered as 0-255 [R, G, B]
colors = []; //holds final colors to be used
rand = new Random();

//assumes n is less than 16,777,216
randomGen(int n){
   while (len(colors) < n){
      //generate a random number between 0,255 for each color
      newRed = rand.next(256);
      newGreen = rand.next(256);
      newBlue = rand.next(256);
      temp = [newRed, newGreen, newBlue];
      //only adds new colors to the array
      if temp not in colors {
         colors.append(temp);
      }
   }
}
```
```
One way you could optimize this for better visibility would be to compare the distance between each new color and all the colors in the array:
```
```
for item in color{
   itemSq = (item[0]^2 + item[1]^2 + item[2]^2])^(.5);
   tempSq = (temp[0]^2 + temp[1]^2 + temp[2]^2])^(.5);
   dist = itemSq - tempSq;
   dist = abs(dist);
}
//NUMBER can be your chosen distance apart.
if dist < NUMBER and temp not in colors {
   colors.append(temp);
}
```
```
But this approach would significantly slow down your algorithm.
Another way would be to scrap the randomness and systematically go through every 4 values and add a color to an array in the above example.


Question:
I have the following arrays:

$artist = array("the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE");
$count = array(5, 3, 9, 1, 1, 3);

I want to generate a tag cloud that will have artists with a higher number in $count enclosed in h6 tags and the lowest enclosed h1 tags.

Answer:
Off the top of my head...
```
```
$artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE");
$count = array(5,3,9,1,1,3);
$highest = max($count);
for (int $x = 0; $x < count($artist); $x++)
{
    $normalized = $count[$x] / $highest;
    $heading = ceil($normalized * 6); // 6 heading types
    echo "<h".$heading.">".$artist[$x]."</h".$heading.">";
}
```
```


Question:
How do I make it so mailto: links will be registered with my program?

How would I then handle that event in my program?

Most of the solutions I found from a quick Google search are how to do this manually, but I need to do this automatically for users of my program if they click a button, such as "set as default email client".

#Edit:
Removed reference to Delphi, because the answer is independent of your language.

Answer:
From what I've seen, there are a few registry keys that set the default mail client. One of them is:
System Key:
```
[HKEY_CLASSES_ROOT\mailto\shell\open\command]
```
Value Name:
```
(Default)
```
Data Type:
```
REG_SZ
```
(String Value)
Value Data:
```
Mail program command-line
```
.
I'm not familiar  with
```
Delphi 7
```
, but I'm sure there are some
registry editing libraries
there that you could use to modify this value.
Some places list more than this
key
, others just this key, so you may need to test a little bit to find the proper one(s).


Question:
MySQL has this incredibly useful yet proprietary REPLACE INTO SQL Command.

Can this easily be emulated in SQL Server 2005?

Starting a new Transaction, doing a Select() and then either UPDATE or INSERT and COMMIT is always a little bit of a pain, especially when doing it in the application and therefore always keeping 2 versions of the statement.

I wonder if there is an easy and universal way to implement such a function into SQL Server 2005?

Answer:
The functionality you're looking for is traditionally called an UPSERT. Atleast knowing what it's called might help you find what you're looking for.
I don't think SQL Server 2005 has any great ways of doing this. 2008 introduces the MERGE statement that can be used to accomplish this as shown in:
http://www.databasejournal.com/features/mssql/article.php/3739131
or
http://blogs.conchango.com/davidportas/archive/2007/11/14/SQL-Server-2008-MERGE.aspx
Merge was available in the beta of 2005, but they removed it out in the final release.


Question:
What are the best practices for checking in BIN directories in a collaborative development environment using SVN?  Should project level references be excluded from checkin?  Is it easier to just add all bin directories?

I develop a lot of DotNetNuke sites and it seems that in a multi-developer environment, it's always a huge task to get the environment setup correctly.

The ultimate goal (of course) is to have a new developer checkout the trunk from SVN, restore the DNN database and have it all just 'work'...

Answer:
Any assemblies that are expected to be in the GAC should stay in the GAC. This includes System.web.dll or any other 3rd party dll that you'll deploy to the GAC in production. This means a new developer would have to install these assemblies.
All other 3rd party assemblies should be references through a relative path. My typical structure is:
```
```
-Project
--Project.sln
--References
---StructureMap.dll
---NUnit.dll
---System.Web.Mvc.dll
--Project.Web
---Project.Web.Proj
---Project.Web.Proj files
--Project
---Project.Proj
---Project.Proj files
```
```
Project.Web and Project reference the assemblies in the root/References folder relatively. These .dlls are checked into subversion.
Aside from that, */bin  */bin/* obj  should be in your global ignore path.
With this setup, all references to assemblies are either through the GAC (so should work across all computers), or relative to each project within your solution.


Question:
I often have to sort a dictionary (consisting of keys & values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency.

There is a SortedList which is good for a single value (say frequency), that I want to map back to the word.

SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way?

Answer:
Looking around, and using some C# 3.0 features we can do this:
```
```
foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))
{
    // do something with item.Key and item.Value
}
```
```
This is the cleanest way I've seen and is similar to the Ruby way of handling hashes.


Question:
When is it appropriate to use an unsigned variable over a signed one? What about in a for loop?

I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus.

for (unsigned int i = 0; i < someThing.length(); i++) {
    SomeThing var = someThing.at(i);
    // You get the idea.
}

I know Java doesn't have unsigned values, and that must have been a concious decision on Sun Microsystems' part.

Answer:
I was glad to find
a good conversation
on this subject, as I hadn't really given it much thought before.
In summary, signed is a good general choice - even when you're dead sure all the numbers are positive - if you're going to do arithmetic on the variable (like in a typical for loop case).
unsigned starts to make more sense when:
You're going to do
bitwise things
like masks, or
You're
desperate
to to take advantage of the sign bit
for that extra positive range
.
Personally, I like signed because I don't trust myself to stay consistent and avoid mixing the two types (like the article warns against).


Question:
I am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it.

Unfortunately, whilst I know the XML model fairly well in .NET, I'm uncertain what the pros and cons are of the XML models in Python.

Anyone have experience doing XML processing in Python? Where would you suggest I start? The XML files I'll be building will be fairly simple.

Answer:
Personally, I've played with several of the built-in options on an XML-heavy project and have settled on
pulldom
as the best choice for less complex documents.
Especially for small simple stuff, I like the event-driven theory of parsing rather than setting up a whole slew of callbacks for a relatively simple structure.
Here is a good quick discussion of how to use the API
.
What I like: you can handle the parsing in a
```
for
```
loop rather than using callbacks.  You also delay full parsing (the "pull" part) and only get additional detail when you call
```
expandNode()
```
.  This satisfies my general requirement for "responsible" efficiency without sacrificing ease of use and simplicity.


Question:
How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.

Any language would work, but it should be portable.

Answer:
There are several ways to do this. Common methods use recursion, memoization, or dynamic programming. The basic idea is that you produce a list of all strings of length 1, then in each iteration, for all strings produced in the last iteration, add that string concatenated with each character in the string individually. (the variable index in the code below keeps track of the start of the last and the next iteration)
Some pseudocode:
```
```
list = originalString.split('')
index = (0,0)
list = [""]
for iteration n in 1 to y:
  index = (index[1], len(list))
  for string s in list.subset(index[0] to end):
    for character c in originalString:
      list.add(s + c)
```
```
you'd then need to remove all strings less than x in length, they'll be the first (x-1) * len(originalString) entries in the list.


Question:
This is a tricky one and I've always relied on techniques, such as permission-based emails (i.e. only sending to people you have permission to send to) and not using blatantly spamish terminology.

Of late, some of the emails I send out programmatically have started being shuffled into people's spam folder automatically and I'm wondering what I can do about it.

This is despite the fact that these particular emails are not ones that humans would mark as spam, specifically, they are emails that contain license keys that people have paid good money for, so I don't think they're going to consider them spam

I figure this is a big topic in which I am essentially an ignorant simpleton.

Answer:
You can tell your users to add your From address to their contacts when they complete their order, which, if they do so, will help a lot.
Otherwise, I would try to get a log from some of your users. Sometimes they have details about why it was flagged as spam in the headers of the message, which you could use to tweak the text.
Other things you can try:
Put your site name or address in the subject
Keep all links in the message pointing to your domain (and not email.com)
Put an address or other contact information in the email


Question:
In Lucene if you had multiple indexes that covered only one partition each. Why does the same search on different indexes return results with different scores? The results from different servers match exactly.

i.e. if I searched for :

Name - John Smith

DOB - 11/11/1934

Partition 0 would return a score of 0.345

Partition 1 would return a score of 0.337

Both match exactly on name and DOB.

Answer:
The
scoring
contains the Inverse Document Frequency(IDF). If the term "John Smith" is in one partition, 0, 100 times and in partition 1, once. The score for searching for John Smith would be higher search in partition 1 as the term is more scarce.
To get round this you would wither have to have your index being over all partitions, or you would need to override the IDF.


Question:
Please note that this question is from 2008 and now is of only historic interest.

What's the best way to create an iPhone application that runs in landscape mode from the start, regardless of the position of the device?

Both programmatically and using the Interface Builder.

Answer:
From the Apple Dev Site:
To start your application in landscape
  mode so that the status bar is in the
  appropriate position immediately, edit
  your Info.plist file to add the
  UIInterfaceOrientation key with the
  appropriate value
  (UIInterfaceOrientationLandscapeRight
  or
  UIInterfaceOrientationLandscapeLeft),
  as shown in Listing 2.
Listing 2: Starting your application
  in landscape mode
```
```
<key>UIInterfaceOrientation</key>
<string>UIInterfaceOrientationLandscapeRight</string>
```
```


Question:
I am using the Photoshop's javascript API to find the fonts in a given PSD.

Given a font name returned by the API, I want to find the actual physical font file that font name corresponds to on the disc.

This is all happening in a python program running on OSX so I guess I'm looking for one of:

Some Photoshop javascript

A Python function

An OSX API that I can call from python

Answer:
open up a terminal (Applications->Utilities->Terminal) and type this in:
```
```
locate InsertFontHere
```
```
This will spit out every file that has the name you want.
Warning: there may be alot to wade through.


Question:
Assume you are doing something like the following

List<string> myitems = new List<string>
{
    "Item 1",
    "Item 2",
    "Item 3"
};

ComboBox box = new ComboBox();
box.DataSource = myitems;

ComboBox box2 = new ComboBox();
box2.DataSource = myitems

So now we have 2 combo boxes bound to that array, and everything works fine. But when you change the value of one combo box, it changes BOTH combo boxes to the one you just selected.

Now, I know that Arrays are always passed by reference (learned that when i learned C :D), but why on earth would the combo boxes change together? I don't believe the combo box control is modifying the collection at all.

As a workaround, don't this would achieve the functionality that is expected/desired

ComboBox box = new ComboBox();
box.DataSource = myitems.ToArray();

Answer:
This has to do with how data bindings are set up in the dotnet framework, especially the
```
BindingContext
```
. On a high level it means that if you haven't specified otherwise each form and all the controls of the form share the same
```
BindingContext
```
. When you are setting the
```
DataSource
```
property the
```
ComboBox
```
will use the
```
BindingContext
```
to get a
```
ConcurrenyMangager
```
that wraps the list. The
```
ConcurrenyManager
```
keeps track of such things as the current selected position in the list.
When you set the
```
DataSource
```
of the second
```
ComboBox
```
it will use the same
```
BindingContext
```
(the forms) which will yield a reference to the same
```
ConcurrencyManager
```
as above used to set up the data bindings.
To get a more detailed explanation see
BindingContext
.


Question:
I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.

On the Mac I am spawning sips.  Is there something similarly simple I can do on Windows?

Answer:
You can use ImageMagick's convert utility for this, see some examples in
http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html
:
```
```
Convert taxes.pdf taxes.jpg
```
```
Will convert a two page PDF file into [2] jpeg files: taxes.jpg.0,
  taxes.jpg.1
I can also convert these JPEGS to a thumbnail as follows:
```
```
convert -size 120x120 taxes.jpg.0 -geometry 120x120 +profile '*' thumbnail.jpg
```
```
I can even convert the PDF directly to a jpeg thumbnail as follows:
```
```
convert -size 120x120 taxes.pdf -geometry 120x120 +profile '*' thumbnail.jpg
```
```
This will result in a thumbnail.jpg.0 and thumbnail.jpg.1 for the two
  pages.


Question:
I would like to test a function with a tuple from a set of fringe cases and normal values. For example, while testing a function which returns true whenever given three lengths that form a valid triangle, I would have specific cases, negative / small / large numbers, values close-to being overflowed, etc.; what is more, main aim is to generate combinations of these values, with or without repetition, in order to get a set of test data.

(inf,0,-1), (5,10,1000), (10,5,5), (0,-1,5), (1000,inf,inf),
...

As a note: I actually know the answer to this, but it might be helpful for others, and a challenge for people here! --will post my answer later on.

Answer:
Interesting question!
I would do this by picking combinations, something like the following in python.  The hardest part is probably first pass verification, i.e.
```
if f(1,2,3) returns true
```
, is that a correct result?  Once you have verified that, then this is a good basis for regression testing.
Probably it's a good idea to make a set of test cases that you know will be all true (e.g. 3,4,5 for this triangle case), and a set of test cases that you know will be all false (e.g. 0,1,inf).  Then you can more easily verify the tests are correct.
```
# xpermutations from http://code.activestate.com/recipes/190465
from xpermutations import *

lengths=[-1,0,1,5,10,0,1000,'inf']
for c in xselections(lengths,3):        # or xuniqueselections
    print c
```
```
(-1,-1,-1);
(-1,-1,0);
(-1,-1,1);
(-1,-1,5);
(-1,-1,10);
(-1,-1,0);
(-1,-1,1000);
(-1,-1,inf);
(-1,0,-1);
(-1,0,0);
...
```


Question:
I was reading More Joel on Software when I came across Joel Spolsky saying something about a particular type of programmer knowing the difference between an int and an Integer in Java/C# (Object-Oriented Programming Languages).

So, what is the difference?

Answer:
In Java,
the 'int' type is a primitive, whereas the 'Integer' type is an object.
In C#,
the 'int' type is the same as
```
System.Int32
```
and is
a value type
(ie more like the java 'int'). An integer (just like any other value types) can be
boxed
("wrapped") into an object.
The differences between objects and primitives are somewhat beyond the scope of this question, but to summarize:
Objects
provide facilities for polymorphism, are passed by reference (or more accurately have references passed by value), and are allocated from the
heap
. Conversely,
primitives
are immutable types that are passed by value and are often allocated from the
stack
.


Question: There are several ways to iterate over a result set. What are the tradeoff of each?

Answer:
The canonical way is to use the built-in cursor iterator.
```
```
curs.execute('select * from people')
for row in curs:
    print row
```
```
You can use
```
fetchall()
```
to get all rows at once.
```
```
for row in curs.fetchall():
    print row
```
```
It can be convenient to use this to create a Python list containing the values returned:
```
```
curs.execute('select first_name from people')
names = [row[0] for row in curs.fetchall()]
```
```
This can be useful for smaller result sets, but can have bad side effects if the result set is large.
You have to wait for the entire result set to be returned to
your client process.
You may eat up a lot of memory in your client to hold
the built-up list.
It may take a while for Python to construct and deconstruct the
list which you are going to immediately discard anyways.
If you know there's a single row being returned in the result set you can call
```
fetchone()
```
to get the single row.
```
```
curs.execute('select max(x) from t')
maxValue = curs.fetchone()[0]
```
```
Finally, you can loop over the result set fetching one row at a time.  In general, there's no particular advantage in doing this over using the iterator.
```
```
row = curs.fetchone()
while row:
    print row
    row = curs.fetchone()
```
```


Question:
I'm looking for a performant, reasonably robust RNG using no special hardware. It can use mathematical methods (Mersenne Twister, etc), it can "collect entropy" from the machine, whatever. On Linux/etc we have a drand48() which generates 48 random bits. I'd like a similar function/class for C++ or C# which can generate more than 32 bits of randomness and which low-order bits are equally as random as high-order bits.

It doesn't have to be cryptographically secure but it must not use or be based on the C-language rand() or .NET System.Random.

Any source code, links to source, etc. would be appreciated! Failing that, what TYPE of RNG should I be looking for?

Answer:
For C++,
Boost.Random
is probably what you're looking for. It has support for MT (among many other algorithms), and can collect entropy via the
```
nondet_random
```
class. Check it out! :-)


Question:
In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and Proc.new on the other.

What are those differences?

Can you give guidelines on how to decide which one to choose?

In Ruby 1.9, proc and lambda are different. What's the deal?

Answer:
I found
this page
which shows what the difference between
```
Proc.new
```
and
```
lambda
```
are.  According to the page, the only difference is that a lambda is strict about the number of arguments it accepts, whereas
```
Proc.new
```
converts missing arguments to
```
nil
```
.  Here is an example IRB session illustrating the difference:
```
irb(main):001:0> l = lambda { |x, y| x + y }
=> #<Proc:0x00007fc605ec0748@(irb):1>
irb(main):002:0> p = Proc.new { |x, y| x + y }
=> #<Proc:0x00007fc605ea8698@(irb):2>
irb(main):003:0> l.call "hello", "world"
=> "helloworld"
irb(main):004:0> p.call "hello", "world"
=> "helloworld"
irb(main):005:0> l.call "hello"
ArgumentError: wrong number of arguments (1 for 2)
    from (irb):1
    from (irb):5:in `call'
    from (irb):5
    from :0
irb(main):006:0> p.call "hello"
TypeError: can't convert nil into String
    from (irb):2:in `+'
    from (irb):2
    from (irb):6:in `call'
    from (irb):6
    from :0
```
The page also recommends using lambda unless you specifically want the error tolerant behavior.  I agree with this sentiment.  Using a lambda seems a tad more concise, and with such an insignificant difference, it seems the better choice in the average situation.
As for Ruby 1.9, sorry, I haven't looked into 1.9 yet, but I don't imagine they would change it all that much (don't take my word for it though, it seems you have heard of some changes, so I am probably wrong there).


Question:
I would like the version property of my application to be incremented for each build but I'm not sure on how to enable this functionality in Visual Studio (2005/2008). I have tried to specify the AssemblyVersion as 1.0.* but it doesn't get me exactly what I want.

I'm also using a settings file and in earlier attempts when the assembly version changed my settings got reset to the default since the application looked for the settings file in another directory.

I would like to be able to display a version number in the form of 1.1.38 so when a user finds a problem I can log the version they are using as well as tell them to upgrade if they have an old release.

A short explanation of how the versioning works would also be appreciated. When does the build and revision number get incremented?

Answer:
With the "Built in" stuff, you can't, as using 1.0.* or 1.0.0.* will replace the revision and build numbers with a coded date/timestamp, which is usually also a good way.
For more info, see the
Assembly Linker
Documentation in the /v tag.
As for automatically incrementing numbers, use the AssemblyInfo Task:
AssemblyInfo Task
This can be configured to automatically increment the build number.
There are 2 Gotchas:
Each of the 4 numbers in the Version string is limited to 65535. This is a Windows Limitation and unlikely to get fixed.
Why are build numbers limited to 65535?
Using with with Subversion requires a small change:
Using MSBuild to generate assembly version info at build time (including SubVersion fix)
Retrieving the Version number is then quite easy:
```
```
Version v = Assembly.GetExecutingAssembly().GetName().Version;
string About = string.Format(CultureInfo.InvariantCulture, @"YourApp Version {0}.{1}.{2} (r{3})", v.Major, v.Minor, v.Build, v.Revision);
```
```
And, to clarify: In .net or at least in C#, the build is actually the THIRD number, not the fourth one as some people (for example Delphi Developers who are used to Major.Minor.Release.Build) might expect.
In .net, it's Major.Minor.Build.Revision.


Question:
What is the fastest, yet secure way to encrypt passwords (in PHP preferably), and for whichever method you choose, is it portable?

In other words, if I later migrate my website to a different server, will my passwords continue to work?

The method I am using now, as I was told, is dependent on the exact versions of the libraries installed on the server.

Answer:
If you are choosing an encryption method for your login system then speed is not your friend, Jeff had a to-and-frow with Thomas Ptacek about passwords and the
conclusion
was that you should use the slowest, most secure encryption method you can afford to.
From Thomas Ptacek's blog:
Speed is exactly what you don’t want in a password hash function.
Modern password schemes are attacked with incremental password crackers.
Incremental crackers don’t precalculate all possible cracked passwords. They consider each password hash individually, and they feed their dictionary through the password hash function the same way your PHP login page would. Rainbow table crackers like Ophcrack use space to attack passwords; incremental crackers like John the Ripper, Crack, and LC5 work with time: statistics and compute.
The password attack game is scored in time taken to crack password X. With rainbow tables, that time depends on how big your table needs to be and how fast you can search it. With incremental crackers, the time depends on how fast you can make the password hash function run.
The better you can optimize your password hash function, the faster your password hash function gets, the weaker your scheme is. MD5 and SHA1, even conventional block ciphers like DES, are designed to be fast. MD5, SHA1, and DES are weak password hashes. On modern CPUs, raw crypto building blocks like DES and MD5 can be bitsliced, vectorized, and parallelized to make password searches lightning fast. Game-over FPGA implementations cost only hundreds of dollars.


Question:
I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,

foo in iter_attr(array of python objects, attribute name)

I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers

Answer:
No, you were not dreaming.  Python has a pretty excellent list comprehension system that lets you manipulate lists pretty elegantly, and depending on exactly what you want to accomplish, this can be done a couple of ways.  In essence, what you're doing is saying "For item in list if criteria.matches", and from that you can just iterate through the results or dump the results into a new list.
I'm going to crib an example from
Dive Into Python
here, because it's pretty elegant and they're smarter than I am.  Here they're getting a list of files in a directory, then filtering the list for all files that match a regular expression criteria.
```
```
files = os.listdir(path)
    test = re.compile("test\.py$", re.IGNORECASE)
    files = [f for f in files if test.search(f)]
```
```
You could do this without regular expressions, for your example, for anything where your expression at the end returns true for a match.  There are other options like using the filter() function, but if I were going to choose, I'd go with this.
Eric Sipple


Question: I wrote a windows service using VB that read some legacy data from Visual Foxpro Databases to be inserted in SQL 2005. The problem is this use to run fine in Windows server 2003 32-Bits, but the client recently moved to Windows 2003 64-Bits and now the service won't work. I'm getting a message the the VFP .NET OLEdb provider is not found. I researched and everything seems to point out that there is no solution. Any Help, please...

Answer:
Have you tried changing the target CPU to
```
x86
```
instead of
```
"Any CPU"
```
in the advanced compiler options? I know that this solves some problems with other
```
OLEDB
```
providers by forcing the use of the 32-bit version.


Question: How do I format a string to title case?

Answer:
Here is a simple static method to do this in C#:
```
```
public static string ToTitleCaseInvariant(string targetString)
{
    return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(targetString);
}
```
```


Question:
One may not always know the Type of an object at compile-time, but may need to create an instance of the Type.

How do you get a new object instance from a Type?

Answer:
The
```
Activator
```
class within the root
```
System
```
namespace is pretty powerful.
There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at:
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
or (new path)
https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance
Here are some simple examples:
```
```
ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");
```
```


Question:
What is the best way to localise a date format descriptor?

As anyone from a culture which does not use the mm/dd/yyyy format knows, it is annoying to have to enter dates in this format. The .NET framework provides some very good localisation support, so it's trivial to parse dates according to the users culture, but you often want to also display a helpful hint as to the format required (especially to distinguish between yy and yyyy which is interchangeable in most cultures).

What is the best way to do this in a way that make sense to most users (e.g. dd/M/yyy is confusing because of the change in case and the switching between one and two letters).

Answer:
Here is my current method. Any suggestions?
```
```
Regex singleMToDoubleRegex = new Regex("(?<!m)m(?!m)");
Regex singleDToDoubleRegex = new Regex("(?<!d)d(?!d)");
CultureInfo currentCulture = CultureInfo.CurrentUICulture;

// If the culture is netural there is no date pattern to use, so use the default.
if (currentCulture.IsNeutralCulture)
{
    currentCulture = CultureInfo.InvariantCulture;
}

// Massage the format into a more general user friendly form.
string shortDatePattern = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.ToLower();
shortDatePattern = singleMToDoubleRegex.Replace(shortDatePattern, "mm");
shortDatePattern = singleDToDoubleRegex.Replace(shortDatePattern, "dd");
```
```


Question:
I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.

I found bpgsql really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?

Answer:
I don't have any experience with
http://www.SiteGround.com
as a web host personally.
This is just a guess, but it's common for a shared host to support Python and MySQL with the MySQLdb module (e.g., GoDaddy does this).  Try the following CGI script to see if MySQLdb is installed.
```
```
#!/usr/bin/python

module_name = 'MySQLdb'
head = '''Content-Type: text/html

%s is ''' % module_name

try:
    __import__(module_name)
    print head + 'installed'
except ImportError:
    print head + 'not installed'
```
```


Question:
I need to programmatically solve a system of linear equations in C, Objective C, or (if needed) C++.

Here's an example of the equations:

-44.3940 = a * 50.0 + b * 37.0 + tx
-45.3049 = a * 43.0 + b * 39.0 + tx
-44.9594 = a * 52.0 + b * 41.0 + tx

From this, I'd like to get the best approximation for a, b, and tx.

Answer:
Are you looking for a software package that'll do the work or actually doing the matrix operations and such and do each step?
The the first, a coworker of mine just used
Ocaml GLPK
. It is just a wrapper for the
GLPK
, but it removes a lot of the steps of setting things up. It looks like you're going to have to stick with the GLPK, in C, though. For the latter, thanks to delicious for saving an old article I used to learn LP awhile back,
PDF
. If you need specific help setting up further, let us know and I'm sure, me or someone will wander back in and help, but, I think it's fairly straight forward from here. Good Luck!


Question:
I haven't been able to find an understandable explanation of how to actually use Python's itertools.groupby() function.  What I'm trying to do is this:

Take a list - in this case, the children of an objectified lxml element

Divide it into groups based on some criteria

Then later iterate over each of these groups separately.

I've reviewed the documentation, but I've had trouble trying to apply them beyond a simple list of numbers.

So, how do I use of itertools.groupby()?  Is there another technique I should be using?  Pointers to good "prerequisite" reading would also be appreciated.

Answer:
The example on the Python docs is quite straightforward:
```
```
groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
    groups.append(list(g))      # Store group iterator as a list
    uniquekeys.append(k)
```
```
So in your case, data is a list of nodes,
```
keyfunc
```
is where the logic of your criteria function goes and then
```
groupby()
```
groups the data.
You must be careful to
sort the data
by the criteria before you call
```
groupby
```
or it won't work.
```
groupby
```
method actually just iterates through a list and whenever the key changes it creates a new group.


Question:
SQL:

SELECT
   u.id,
   u.name,
   isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault
FROM universe u
LEFT JOIN history h
   ON u.id=h.id
   AND h.dateCol<GETDATE()-1
GROUP BY u.Id, u.name

Answer:
A solution, albeit one that defers handling of the null value to the code, could be:
DateTime yesterday = DateTime.Now.Date.AddDays(-1);
```
```
var collection=
    from u in db.Universe
    select new
    {
        u.id,
        u.name,
        MaxDate =(DateTime?)
       (
           from h in db.History
           where u.Id == h.Id
           && h.dateCol < yesterday
           select h.dateCol
       ).Max()
    };
```
```
This does not produce exactly the same SQL, but does provide the same logical result. Translating "complex" SQL queries to LINQ is not always straightforward.


Question:
I'm trying to setup CruiseControl.net at the moment. So far it works nice, but I have a Problem with the MSBuild Task.

According to the Documentation, it passes CCNetArtifactDirectory to MSBuild. But how do I use it?

I tried this:

<buildArgs>
   /noconsolelogger /p:OutputPath=$(CCNetArtifactDirectory)\test
</buildArgs>

But that does not work. In fact, it kills the service with this error:

ThoughtWorks.CruiseControl.Core.Config.Preprocessor.EvaluationException: Reference to unknown symbol CCNetArtifactDirectory

Documentation is rather sparse, and google und mainly offers modifying the .sln Project file, which is what I want to avoid in order to be able to manually build this project later - I would really prefer /p:OutputPath.

Answer:
The CCNetArtifactDirectory is passed to the MSBuild by default, so you dont need to worry about it. MSBuild will place the build output in the "bin location" relevant to the working directory that you have specified.
```
```
<executable>c:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable>
<workingDirectory>C:\data\projects\FooSolution\</workingDirectory>
<projectFile>FooSolution.sln</projectFile>
<buildArgs>/noconsolelogger /p:Configuration=Debug </buildArgs>
```
```
So in the above example your build output will be put in C:\data\projects\FooSolution[ProjectName]\bin\Debug. Should you want to output to a different location you may want to look at of the  tag in CCNET.
```
```
<publishers>
  <xmllogger />
  <buildpublisher>
    <sourceDir>C:\data\projects\FooSolution\FooProject\bin\Debug</sourceDir>
    <publishDir>C:\published\FooSolution\</publishDir>
    <useLabelSubDirectory>false</useLabelSubDirectory>
  </buildpublisher>
</publishers>
```
```
This will allow you to publish your output to a different location.


Question:
Suppose I have the following CSS rule in my page:

body {
    font-family: Calibri, Trebuchet MS, Helvetica, sans-serif;
}

How could I detect which one of the defined fonts were used in the user's browser?

For people wondering why I want to do this is because the font I'm detecting contains glyphs that are not available in other fonts. If the user does not have the font, then I want it to display a link asking the user to download that font (so they can use my web application with the correct font).

Currently, I am displaying the download font link for all users. I want to only display this for people who do not have the correct font installed.

Answer:
I've seen it done in a kind of iffy, but pretty reliable way. Basically, an element is set to use a specific font and a string is set to that element.  If the font set for the element does not exist, it takes the font of the parent element.  So, what they do is measure the width of the rendered string.  If it matches what they expected for the desired font as opposed to the derived font, it's present. This won't work for monospaced fonts.
Here's where it came from:
Javascript/CSS Font Detector (ajaxian.com; 12 Mar 2007)


Question:
How do you debug PHP scripts?

I am aware of basic debugging such as using the Error Reporting. The breakpoint debugging in PHPEclipse is also quite useful.

What is the best (in terms of fast and easy) way to debug in phpStorm or any other IDE?

Answer:
I've used the
Zend Studio (5.5)
, together with
Zend Platform
. That gives proper debugging, breakpoints/stepping over the code etc., although at a price.


Question:
How have you implemented Internationalization (i18n) in actual projects you've worked on?

I took an interest in making software cross-cultural after I read the famous post by Joel, The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!). However, I have yet to able to take advantage of this in a real project, besides making sure I used Unicode strings where possible. But making all your strings Unicode and ensuring you understand what encoding everything you work with is in is just the tip of the i18n iceberg.

Everything I have worked on to date has been for use by a controlled set of US English speaking people, or i18n just wasn't something we had time to work on before pushing the project live. So I am looking for any tips or war stories people have about making software more localized in real world projects.

Answer:
I worked on a project for my previous employer that used .NET, and there was a built in .resx format we used.  We basically had a file that had all translations in the .resx file, and then multiple files with different translations.  The consequence of this is that you have to be very diligent about ensuring that all strings visible in the application are stored in the .resx, and anytime one is changed you have to update all languages you support.
If you get lazy and don't notify the people in charge of translations, or you embed strings without going through your localization system, it will be a nightmare to try and fix it later.  Similarly, if localization is an afterthought, it will be very difficult to put in place.  Bottom line, if you don't have all visible strings stored externally in a standard place, it will be very difficult to find all that need to be localized.
One other note, very strictly avoid concatenating visible strings directly, such as
```
```
String message = "The " + item + " is on sale!";
```
```
Instead, you must use something like
```
```
String message = String.Format("The {0} is on sale!", item);
```
```
The reason for this is that different languages often order the words differently, and concatenating strings directly will need a new build to fix, but if you used some kind of string replacement mechanism like above, you can modify your .resx file (or whatever localization files you use) for the specific language that needs to reorder the words.


Question:
Given a relatively simple CSS:

div {
  width: 150px;
}

<div>
  12333-2333-233-23339392-332332323
</div>

How do I make it so that the string stays constrained to the width
  of 150, and wraps to a new line on the hyphen?

Answer:
Replace your hyphens with this:
```
```

```
```
It's called a "soft" hyphen.
```
```
div {
  width: 150px;
}
```
```
```
```
<div>
  12333233323323339392332332323
</div>
```
```


Question: What's the simplest way to connect and query a database for a set of records in C#?

Answer:
Very roughly and from memory since I don't have code on this laptop:
```
```
using (OleDBConnection conn = new OleDbConnection())
{
  conn.ConnectionString = "Whatever connection string";

  using (OleDbCommand cmd = new OleDbCommand())
  {
    cmd.Connection = conn;
    cmd.CommandText = "Select * from CoolTable";

    using (OleDbDataReader dr = cmd.ExecuteReader())
    {
      while (dr.Read())
      {
        // do something like Console.WriteLine(dr["column name"] as String);
      }
    }
  }
}
```
```


Question:
Attempting to insert an escape character into a table results in a warning.

For example:

create table EscapeTest (text varchar(50));

insert into EscapeTest (text) values ('This is the first part \n And this is the second');

Produces the warning:

WARNING:  nonstandard use of escape in a string literal

(Using PSQL 8.2)

Anyone know how to get around this?

Answer:
Partially. The text is inserted, but the warning is still generated.
I found a discussion that indicated the text needed to be preceded with 'E', as such:
```
```
insert into EscapeTest (text) values (E'This is the first part \n And this is the second');
```
```
This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.
As such:
```
```
insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');
```
```


Question:
I've read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python.

I understand that it's not always good to do so. But how might one do this?

Answer:
In Python monkeypatching generally works by overwriting a class or function's signature with your own. Below is an example from the
Zope Wiki
:
```
```
from SomeOtherProduct.SomeModule import SomeClass
def speak(self):
   return "ook ook eee eee eee!"
SomeClass.speak = speak
```
```
This code will overwrite/create a method called
```
speak
```
in the class. In Jeff Atwood's
recent post on monkey patching
, he showed an example in C# 3.0 which is the current language I use for work.


Question:
I need to grab the base64-encoded representation of the ViewState. Obviously, this would not be available until fairly late in the request lifecycle, which is OK.

For example, if the output of the page includes:

<input type="hidden" name="__VIEWSTATE"
  id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" />

I need a way on the server-side to get the value "/wEPDwUJODU0Njc5MD...=="

To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being sent to the client, not the ViewState I'm getting back from them.

Answer:
Rex, I suspect a good place to start looking is solutions that
compress the ViewState
-- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be.
Scott Hanselman on ViewState Compression
(2005)
ViewState Compression with System.IO.Compression
(2007)


Question:
After upgrading a rails 1.2 website to 2.1, the ExceptionNotifier plugin no longer works, complaining about this error:

ActionView::TemplateFinder::InvalidViewPath:  Unprocessed view path
  found:
  "/path/to/appname/vendor/plugins/exception_notification/lib/../views".
  Set your view paths with #append_view_path, #prepend_view_path, or #view_paths=.

What causes it and how do I fix it?

Answer:
This was caused by a change in rails 2.1 which prevents rails from loading views from any arbitrary path for security reasons.
There is now an updated version of the plugin on github, so the solution is to use that.
The old solution here for posterity
To work around it, edit
```
init.rb
```
under your
```
vendor/plugins/exception_notification
```
directory, and add the following code to the end
```
```
ActionController::Base.class_eval do
  append_view_path File.dirname(__FILE__) + '/lib/../views'
end
```
```
This adds the ExceptionNotifier plugins' views folder to the list, so it is allowed to load them.


Question:
What is the best way to display Flash content in a C# WinForms application? I would like to create a user control (similar to the current PictureBox) that will be able to display images and flash content.

It would be great to be able to load the flash content from a stream of sorts rather than a file on disk.

Answer:
While I haven't used a flash object inside a windows form application myself, I do know that it's possible.
In Visual studio on your toolbox, choose to add a new component.
Then in the new window that appears choose the
"COM Components"
tab to get a list in which you can find the
"Shockwave Flash Object"
Once added to the toolbox, simply use the control as you would use any other "standard" control from visual studio.
three simple commands are available to interact with the control:
AxShockwaveFlash1.Stop()
AxShockwaveFlash1.Movie = FilePath &
"\FileName.swf"
AxShockwaveFlash1.Play()
which, I think, are all self explanatory.
It would be great to be able to load
  the flash content from a stream of
  sorts rather than a file on disk.
I just saw you are also looking for a means to load the content from a stream,
and because I'm not really sure that is possible with the shockwave flash object I will give you another option (two actually).
the first is the one I would advise you to use only when necessary, as it uses the full blown
"webbrowser component"
(also available as an extra toolbox item), which is like trying to shoot a fly with a bazooka.
of course it will work, as the control will act as
a real browser window
(actually the internet explorer browser), but its not really meant to be used in the way you need it.
the second option is to use something I just discovered while looking for more information about playing flash content inside a windows form.
F-IN-BOX
is a commercial solution that will also play content from a given website URL. (The link provided will direct you to the .NET code you have to use).


Question: I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using File.Delete().

Answer:
You can use this program,
Handle
, to find which process has the lock on your file. It's a command-line tool, so I guess you use the output from that. I'm not sure about finding it programmatically.
If deleting the file can wait, you could specify it for deletion when your computer next starts up:
Start
```
REGEDT32 (W2K)
```
or
```
REGEDIT (WXP)
```
and navigate to:
```
```
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager
```
```
W2K and WXP
W2K:
Edit
Add Value...
Data Type:
```
REG_MULTI_SZ
```
Value Name:
```
PendingFileRenameOperations
```
OK
WXP:
Edit
New
Multi-String Value
enter
```
PendingFileRenameOperations
```
In the Data area, enter
```
"\??\" + filename
```
to be deleted. LFNs may
be entered without being embedded in quotes. To delete
```
C:\Long Directory Name\Long File Name.exe
```
, enter the following data:
```
```
\??\C:\Long Directory Name\Long File Name.exe
```
```
Then press
OK
.
The "destination file name" is a null (zero) string. It is entered
as follows:
W2K:
Edit
Binary
select Data Format: Hex
click at the end of the hex string
enter 0000 (four zeros)
OK
WXP:
Right-click the value
choose "Modify Binary Data"
click at the end of the hex string
enter 0000 (four zeros)
OK
Close
```
REGEDT32/REGEDIT
```
and reboot to delete the file.
(Shamelessly stolen from
some random forum
, for posterity's sake.)


Question:
For instance, my query is like the following using SQL Server 2005:

SELECT * FROM Table WHERE FREETEXT(SearchField, 'c#')

I have a full text index defined to use the column SearchField which returns results when using:

SELECT * FROM Table WHERE SearchField LIKE '%c#%'

I believe # is a special letter, so how do I allow FREETEXT to work correctly for the query above?

Answer:
Quoting a much-replicated help page about Indexing Service query language:
To use specially treated characters such as &, |, ^, #, @, $, (, ), in a query, enclose your query in quotation marks (“).
As far as I know, full text search in
```
MSSQL
```
is also done by the Indexing Service, so this might help.


Question:
Most mathematicians agree that:

eπi + 1 = 0

However, most floating point implementations disagree. How well can we settle this dispute?

I'm keen to hear about different languages and implementations, and various methods to make the result as close to zero as possible. Be creative!

Answer:
Here's a short list of implementations and languages I've tried. It's sorted by closeness to zero:
Scheme:
```
(+ 1 (make-polar 1 (atan 0 -1)))
```
⇒
```
0.0+1.2246063538223773e-16i
```
(Chez Scheme, MIT Scheme)
⇒
```
0.0+1.22460635382238e-16i
```
(Guile)
⇒
```
0.0+1.22464679914735e-16i
```
(Chicken with
```
numbers
```
egg)
⇒
```
0.0+1.2246467991473532e-16i
```
(MzScheme, SISC, Gauche, Gambit)
⇒
```
0.0+1.2246467991473533e-16i
```
(SCM)
Common Lisp:
```
(1+ (exp (complex 0 pi)))
```
⇒
```
#C(0.0L0 -5.0165576136843360246L-20)
```
(CLISP)
⇒
```
#C(0.0d0 1.2246063538223773d-16)
```
(CMUCL)
⇒
```
#C(0.0d0 1.2246467991473532d-16)
```
(SBCL)
Perl:
```
use Math::Complex; Math::Complex->emake(1, pi) + 1
```
⇒
```
1.22464679914735e-16i
```
Python:
```
from cmath import exp, pi; exp(complex(0, pi)) + 1
```
⇒
```
1.2246467991473532e-16j
```
(CPython)
Ruby:
```
require 'complex'; Complex::polar(1, Math::PI) + 1
```
⇒
```
Complex(0.0, 1.22464679914735e-16)
```
(MRI)
⇒
```
Complex(0.0, 1.2246467991473532e-16)
```
(JRuby)
R:
```
complex(argument = pi) + 1
```
⇒
```
0+1.224606353822377e-16i
```