How to dynamically switch PageLayout and MasterPage of SharePoint Publishing page?

Question: To improve both the editing and displaying experience of SharePoint WCM Publishing pages I would like to be able to switch to a special set of Masterpage/PageLayout when in edit mode.
So in /_catalogs/masterpage I want to have:
MyMasterpage.master - masterpage for display mode
MyMasterpage-edit.master - masterpage for edit mode, only use if available
MyPageLayout.aspx - pagelayout for display mode
MyPageLayout-edit.aspx - pagelayout for edit mode, only use if available
When I create a new publishing page in the Pages library, I select the MyPageLayout page layout.
When rendering the page I would like to detect if I'm in Edit of Display mode, just like the  server control does. This control executes the following code to determine the render mode:
private void calculateShouldRender()
{
    SPControlMode contextualFormModeFromPostedForm = ConsoleUtilities.GetContextualFormModeFromPostedForm();
    if ((SPControlMode.Display == contextualFormModeFromPostedForm) && (PageDisplayMode.Display == this.PageDisplayMode))
    {
        this.shouldRender = true;
    }
    else if ((SPControlMode.Edit == contextualFormModeFromPostedForm) && (PageDisplayMode.Edit == this.PageDisplayMode))
    {
        this.shouldRender = true;
    }
    else
    {
        this.shouldRender = false;
    }
    this.Visible = this.shouldRender;
}

If the render mode is Edit, I want to switch to the MyMasterpage-edit.master materpage and the MyPageLayout-edit.aspx pagelayout.
I could make a big switch in the masterpage and pagelayout controlled by  server controls, but I would like to split resposibilities. A SharePoint Analist can create optimal edit mode pages, and a front end developer can create clean and beautiful display mode pages without all the editing clutter.
Any ideas on how to accomplish this? Masterpage switching does not seem the problem, I once wrote a blogpost on this. The difficult thing seems the switching of the page layout.
Answer: I think you would be fighting SharePoint if you continue down that route, I fear it would also become something of a support nightmare as it becomes less clear where problems lie, or remembering to make changes in both (or all four!) places when something is updated.
You can have controls appear or hide depending on the editmode of a page so what is shown to the user is totally different but all the code for a page is still in one place.
Investigate the editmodepanel.
<publishingwebcontrols:editmodepanel ID="Editmodepanel1" runat="server">
   <link id="Link2" rel=Stylesheet href="<% $SPUrl:~sitecollection/EditMode.css %>" runat="server" type="text/css" />
</publishingwebcontrols:editmodepanel>

I realise that is not quite what you asked... but I find fighting SharePoint is a losing battle you just have to work with its 'way'.
Answer: I once wrote a feature to switch page-layouts depending on different criteria. The difference was, that the page-layout was changed during site-creation, not in view or edit mode. The code to change the page-layout is as follows:
    private void SetPageLayout(SPWeb web, string pageName, string pageLayoutName)
    {
        PageLayout layout = null;
        PublishingPage page = null;
        SPFile pageFile = null;
        bool checkedOut = false;

        try
        {
            PublishingWeb publishWeb = PublishingWeb.GetPublishingWeb(web);
            // verify that the requested pageLayout is available
            foreach (PageLayout pl in publishWeb.GetAvailablePageLayouts())
            {
                if (pl.Name.Equals(pageLayoutName, StringComparison.OrdinalIgnoreCase))
                {
                    layout = pl;
                    break;
                }
            }
            // got my layout
            if (layout != null)
            {
                page = null;
                foreach (PublishingPage pubPage in publishWeb.GetPublishingPages())
                {
                    if (pageName == pubPage.Name)
                    {
                        page = pubPage;
                        break;
                    }
                }
                // got my page
                if (page != null)
                {
                    pageFile = page.ListItem.File;

                    page.CheckOut();
                    checkedOut = true;

                    page.Layout = layout;
                    page.Update();

                    page.CheckIn("changed the page-layout to " + pageLayoutName);
                    checkedOut = false;

                    pageFile.Publish("");
                    // If required, approve the page
                    try
                    {
                        pageFile.Approve(string.Empty);
                    }
                    catch
                    {
                        // Page doesn't need to be approved
                    }
                }
            }
        }

Answer: Surely that would require subclassing Microsoft.SharePoint.Publishing.PublishingLayoutPage and use that to render the contents of the actual PublishingLayoutPage required depending on the "edit mode".
How to get a master page changed...ek.
Comment: A publishing page inherits from Microsoft.SharePoint.Publishing.TemplateRedirectionPage. A new page in Pages is automatically created with this inherit in it. I see no way to change this to a subclassed version. HttpModule might do the job, investigating that now. Will come back with the results. Any ideas still appreciated. I want that furious editing experience and elegant display experience;-)
Comment: The HttpModule route goes well, but I have a problem switching the pagelayout just for the edit request. I poseted a new question on this: http://stackoverflow.com/questions/991743/sharepoint-temporary-switching-pagelayout-of-publishingpage-in-httpmodule-fails
Answer: Trying to bend The SharePoint to your will again? ;)
I feel your pain. I'm using 2 ways to get similar behaviour:
A container control to condionally render parts of pages, I think like you suggested. Initially I needed it to hide parts of the page when some field had a specific value so no html was rendered. See wrapper controls.
The control itself is very simple, it needs a [ParseChildren(false)] on its class and the render method does not call the base render if the condition is not met.
You can extend this to display en entirely different page to an editor and designer although it would all still live in the same page. I guess you could strip out the part used by the analist and put it in its own usercontrol but thats not very maintainable.
Secondly, the form page, e.g. "/Pages/Forms/EditForm.aspx?ID=1", gives a clean view of all the fields on a publishing page.. no design to get in the way. (I use a control on all page layouts that provides 1 click access to this and the current pages library and shows the content type and page layout used. Quite useful when building WCM sites.)
Comment: He Arjan! Alles goed aan de andere kant van de wereld? The problem is that I want to really seperate edit and display mode. SharePoint analists can bother about best editing experience, and front end developers can create a crazy display experience. The EditForm.aspx is a bit restricted, it is not possible to edit web parts. So you would not be able to use the content by query web part.
Answer: My text was too long for the comment box, so I answer on Aiden as if it is an answer, but my question remains!
Hi Aidan, I see SharePoint as a platform where you can build your solutions on. And I think that the WCM solution built by Microsoft on top of the platform is weak. I know my way is not directly the SharePoint standard way, but the standard way just does not work. Combining edit and display mode leads to (pick your choice):
- standard SharePoint publishing sites that all look alike but work ok in edit mode
- a site that is very editable but very basic in its appearance
- a great looking site in display mode, that is almost impossible to edit
We have a lot of clashes between the stylesheets needed in display mode with the MOSS WCM stylesheet. We did write all kinds of compensating stylesheets to get it working, but it is a pain in the ***. It is a major flaw to inject code with styles in your page to make editing possible, this should have done completely outside the page you are editing. In an iframe for example which can be displayed as a floating window on top of the page you are editing. But this is not the case. And then I didn't even mention the issues you have when you have tabs or an accordion control on your page.
We are targeting really interactive web 2.0 sites where a lot of content management must be done. Getting editing mode right in the SharePoint way just does not work.
An optimal editing experience is key. So why not use the masterpage and pagelayout optimized for editing so all editable elements are reachable in a clear and consistent way. But then you still need the display mode. This could be done using a complete separate site that just uses the data produced in SharePoint. This can be an ASP.NET site, or if you want full control over the html MVC could be used. I don't at to go that way, because but has a lot of implications in navigation, security, reuse of controls, use of web parts etc.
I think you get best of both worlds if a masterpage/pagelayout is used that is optimized for editing, and another couple of masterpage/pagelayout is used for display only with a minimal set of code in the pagelayout.
So.. keep the answers coming please!
Comment: I understand what you want, I think.  You want a fast and furious editing experience and to also retain design and elegance for the display experience.

So, most likely you want a ton of custom javascript/css/html in edit mode, that will never render in display mode, and vice versa.

Also, switching the master page isnt a problem, really you are asking how to switch the page layout?  If so, edit your question some and maybe we can help you out.
Comment: Hi Marc, that is what I want!! In what way is my question unclear, so I can modiffy it.
Answer: The definitive answer to this question is now "baked" into a product which we call DualLayout for SharePoint! Our approach solves all your SharePoint WCM design nightmare:

Introduce an additional view for the end user, besides the WCM edit and display views
Never have clashes between SharePoint styles and your own styles
Make lean and mean "view" master pages and page layouts that don't interfer with the WCM master pages and page layouts
Make super-light pages for the end-user, remove all SharePoint specific page clutter
Improve the performance of the pages because we only have a minimal set of controls to render in the end user view

Check it out at http://www.macaw.nl/Het+Bedrijf/Producten/Macaw+DualLayout+for+SharePoint.aspx, see the blog posts in the blog roll of that page for detailed background information.


Does Windows Virtual PC automatically use hardware virtualization if it's available

Question: I'm underwhelmed by the performance of the XP VM that was provided by IT along with my win7 install.  Because it's a generic company wide image I'm wondering if it might be stuck running in software virtualization mode even though my laptop does support hardware virtualization.  Is this a legitimate concern?
Answer: AMD-V / VT-x is not always turned on by default.  If it is not turned on, you would have to turn this on in the bios.
Once it is turned on, WVPC will use it automatically.
See more info here: http://www.microsoft.com/windows/virtual-pc/support/configure-bios.aspx
-Josh
Comment: Thanks.  CPU VT was turned on; however IO VT was not.  Enabling the latter has improved performance.


Impact of modulation index in FM

Question:
If I have the spectrum of a FM modulation, does the frequency of the carrier disappear when the modulation index is too big?
Does the amplitude of any side band depend from the modulation index?
And does the total number of side bands depend on the modulation
index?
Comment: This sounds like homework. Did you try to answer these questions? What have you thought so far?
Comment: These are three questions in one. Reduce to one question, show what you've tried so far, and discuss where you encountered problems. If you don't do that: smells like homework you're trying to offload unto us, like Tendero said.
Answer: Assuming an FM modulation of a sine wave of frequency $f_m$. Theoretically, the modulated signal is an infinite sum of cosines at the frequencies $f_c + nf_m$ ($n\in \mathbb{Z}$) which the amplitudes depend on the coefficients $J_n(\beta)$ (of course in addition to the amplitude of the carrier wave), where $\beta$ is the modulation index and $f_c$ is the carrier frequency. At this stage, the answer to the question Q.2. is yes. For the other items:

Q.1. The PSD of the modulated signal in $f_c$ is determined for $n=0$, then the PSD at that frequency depends on the coefficient $J_0(\beta)$. Knowing that $J_n(\beta)$ trends to zero as $\beta$ trends to infinity, so the PSD of the modulated signal in $f_c$ trends to zero as the modulation index trends to infinity.
Q. 3. Theoretically the bandwidth of an FM modulated signal is infinite. But when considering Carson bandwidth rule ($B_C$), the answer to your question is yes since this rule considers the modulation index. $B_C=2(1+\beta)W$ where $W$ is the baseband bandwidth of the modulating signal (assuming a sine wave, $W=f_m$).
Comment: you might want to add the quantitative expression of the Carson rule.
Comment: @robertbristow-johnson Updated. Thanks.
Answer: Its IES or Gate question having last option which you didn't mention here as "carrier frequency can not disappear."
.
Here correct answer among these 4 option is b i.e. the amplitude of any sideband depends on modulation index .
.
2.Frequency spectrum of FM is analysed using Bessel's function .FM spectrum theoretically has infinite number of sidebands . Each sideband has an amplitude , a function of J(β) i.e. β dependent .
.
1.  Although , as β increases , J(β) decreases , and hence carrier frequency component decreases significantly , true , but won't disappear .
Carrier in FM disappears VIRTUALLY , what it means is , as the modulation index vary , sideband amplitudes varies and hence power contents in each side band , which is also a function of β , varies at the cost of power content in carrier component . Being total power constant and equal to carrier power without modulation, At some specific values of β ( not necessarily to be high) , whole of the FM power is distributed in sidebands and hence carrier power becomes zero , or we say carrier disappeared. So option 4 , carrier can't disappear is wrong , as it can disappear and option 1 is wrong as β need not to be high.
.
Option 3 , total number of sidebands are dependent on β ? Wrong . Total number of sidebands are always infinite , what Carson rule tells is , number of significant sidebands holding most of power ( ~90%) are equal to β+1 sidebands on either side , keeping in mind , channel is of finite bandwidth , we use those significant bands in calculation , that doesn't mean total number of sidebands are β dependent .

Impact of modulation index in FM


What to write in resume for game development?

Question: I am a Java developer and I am new to game development.
When I try for write my resume, I am able to write for other project but not able to write for gaming. Actually I don't know what to write and not to write for gaming.
Comment: Have you actually done any projects or work with game development or are just starting out in the field?
Answer: Your résumé should, as it always does, list your work experience and education.
Now, I assume you got to this point and decided you have a problem - you want to get a job in game development, but you have no work experience and no formal education in that field!
Have you got any non-professional game development experience? Written any small games? Contributed to open-source game projects? If so, put a section in there for "other experience" or some such title, and list this stuff out!
If you don't even have that, well, it's going to be an uphill battle no matter what. In that situation, your résumé is not going to speak for itself, so you're going to need a scintillating cover letter to go along with it. Talk about your passion and enthusiasm for the game development field, talk up whatever general software development skills you have that you think might be useful (team organization experience, software development project management techniques, integrating third-party components, whatever), and hope it gets you into an interview where you can really show your enthusiasm!
Answer: Game development is a term that encompasses a lot of jobs and technologies. Game development companies still have testers, IT, DBAs, QC/QA positions, web designers, graphic artists, technical writers. They work in multiple languages and platforms.
They also have specialized positions music, graphics, engines... But so does any other specialty program type.
Medical software companies have some people that know a lot about medicine, but not everybody has to.
You can work for a spacecraft development company and not be an astronaut.
You can work for a company that develops software for the insurance industry and not be sure about the difference between Whole Life an Universal life.
Your resume should reflect what you have done and what you can do. Apply for jobs with companies that do game development, then later leverage that experience into the job you ultimately want.  But don't expect to be able to jump directly to your dream job without either education or experience. So do it in two steps.


How many 5-digit zip codes can there be with exactly two digits the same?

Question:
How many 5-digit United States zip codes can there be with exactly one pair of digits? This includes both zip codes that correspond to an actual city, town, incorporated community, ghost town, etc. in the United States and zip codes that are not used currently.
Exactly one pair of digits means only two digits in a zip code can be the same, but the digits do not necessarily have to be next to each other.
Example zip codes that count:

99501 (Anchorage, AK) has one pair of $9$'s
02108 (Boston, MA) has one pair of $0$'s
63155 (St. Louis, MO) has one pair of $5$'s

Example zip codes that do not count:

59103 (Billings, MT) does not have any two digits to be the same
78727 (Austin, TX) has three--not two--digits to be the same
93388 (Bakersfield, CA) has two pairs--not one pair--of digits

I appealed to the fundamental counting principle, as usual.
Number of zip codes whose...

first two digits are the same (e.g. 99501): $10 \cdot 10 \cdot 9 \cdot 8 \cdot 7$
first and fourth digits digits the same (e.g. 02108): $10 \cdot 9 \cdot 8 \cdot 10 \cdot 7$
fourth and fifth digits are the same (e.g. 63155): $10 \cdot 9 \cdot 8 \cdot 7 \cdot 7$

...etc.
Was that correct or not? I thought since order matters in writing a zip code that I had to consider all those cases. If so, how can I consider all possible cases using a combinatorial argument, with permutations specifically?
(I have little background in combinatorics, but I am nonetheless curious. This is not a homework question; hence, my curiosity for asking this here.)
Comment: For "Fourth and Fifth digits the same" for example, once you have chosen the fourth digit **there is no longer any choice to be made** for the fifth, it must match the fourth in order to ensure it matches.  You pick the result of the fourth and fifth *simultaneously*, making it only $10\cdot 9\cdot 8\cdot 7\color{grey}{\cdot 1}$ for this case.  Now... how many cases are there?  Could you explain this more easily without cases by deciding where the matching numbers are beforehand?
Comment: Position cases: (1,2), (1,3), (1,4), (1,5), (2,3), (2,4), (2,5), (3,4), (3,5), (4,5). So there are 10 cases, I believe.
Comment: and how many ways can you **choose** *two* of the positions *out of five* (*order not mattering*) to place the matching numbers... **five** choices and we want to **choose two** of them.  Instead of wasting time and effort writing them all out by hand as you have (*because it is time consuming and prone to making mistakes*), [is there a convenient calculation we can make](https://en.wikipedia.org/wiki/Binomial_coefficient)?
Comment: There are $5 \choose 2$ ways. However, I thought order matters in writing a zip code. That's why I wrote them all out initially.
Comment: Order of the numbers matter, yes., but we aren't talking about numbers right now, we are talking about positions to be filled by repeated numbers.  Positions five and three matching is the same result as positions three and five matching.
Comment: I see now: since two numbers have to be repeating, regardless of the position, then the number of zip codes with, say, first two digits are matching (e.g. 99801) is actually $10 \cdot 1 \cdot 9 \cdot 8 \cdot 7$. It does not matter where the $1$ is placed in computations like that one (for e.g. fourth and fifth repeating digits, second and fourth, etc.); obviously every quantity will always be $10 \cdot 9 \cdot 8 \cdot 7$, no matter the positions. And then there are ${5 \choose 2 }= 10$ such positions. Hence, $(10 \cdot 9 \cdot 8 \cdot 7) \cdot (10)=50400$, just like @RobertIsrael's answer.
Comment: If now **three** digits in a zip code must match, then there are $(10 \cdot 9 \cdot 8) \cdot {5 \choose 3} = 7200$ such zip codes.
Answer: I presume you're talking about a $5$-digit zip code (not ZIP+4).  To choose a zip code satisfying your condition, choose an ordered $4$-tuple of distinct digits from $0$ to $9$ ($10 \times 9 \times 8 \times 7  = 5040$ ways to do this), then choose an unordered pair of
positions out of the $5$ (${5 \choose 2} = 10$ ways, and assign the $4$-tuple in order to this pair and the other positions.  The total
number of such codes is thus $5040 \times 10 = 50400$.
Comment: It should be $5040 \times 10 = 50400$, not $3024 \times 10$
Comment: What would be the result if the first digit could not be 0?
Answer: Choose any $4$ digits from $(0,1,\cdots,9)$
$\dbinom{10}{4}$ ways
Choose any one digit from the selected $4$ digits (this is our repeating digit)
$\dbinom{4}{1}$ ways
The $5$ digits can be arranged among themselves
$\dfrac{5!}{2!}$ ways

Required number of ways $\dbinom{10}{4}\dbinom{4}{1}\dfrac{5!}{2!}=50400$


Repair of Faulty Concrete Work

Question: I need some advice. Over the summer we had a concrete contractor come in to replace the floor in the carport that became a garage that became my shop. The space is about 20' x 20' and there was a slope of about 6.5" over that distance. The carport slab extended under the walls of the garage, so the contractor proposed to support the shop structure, remove the slab, and pour a new foundation. Since they claimed that they found rot in the plates of the side walls, they were going to remove about a foot off the bottom of each wall.
What they actually ended up doing was to prop up the structure and build forms about 4" inside of the walls. Apparently they thought that the concrete would fill the forms well enough to provide support and a weather / critter seal where the walls met the foundation. At least I guess that is what they were thinking…
When they built the forms they didn't bother to check that the wall was still plumb. Not surprisingly it was not, and it now needs to move about 1.5" towards the outside on one end. That will put the wall (framed in 2x4s) off the foundation to the outside. At the other end of the wall, where it was attached to the house, the wall is still plumb. There are also many places where the forms did not fill, so there are large gaps between the plate and the new foundation. The attached image is a section though the wall.
The contractor is eager to fix it (and get their final payment), I'm wondering if there are good ways to fix this – other than tearing out the work and starting over. Is there some way to pour a patch on the outside of the wall? Are the other options to consider?
Answer: I suggest adding a concrete ledge as shown, then fill the space with bricks.

Repair of Faulty Concrete Work


Rigify rig controll issue with switching between IK and FK mode within one motion

Question: I'm doing some really basic exercises to learn how to control a Rigify human rig. I've seen a tutorial by CGdive which shows you can change between IK and FK mode within one motion of a bone chain (like starting to raise the left arm in IK, then during the movement change to FK and finish the motion in FK mode). The combined motion itself goes decently by itself, though I'm having an issue when try to keyframe it. To do it (sorry for the tedious details), I'm keying the starting frame with the IK control for the hand, make an inbetween pose with IK, keyframe it (still with IK active), then try to do the switch. I hit the "magnet snap" button for IK>>FK, not to lose the previous motion, then turn from IK mode to FK in the Info panel, then move in the timeline to the final frame position of the movement, set the pose now with the FK controller (rotating the upper arm) and keyframe it. However, something is going wrong, because when previewing the animation, only the widget controls make the motion as planned, while the mesh remains fixed throughout the whole movement, from frame zero. Has anyone of you perhaps run into such issue? Thank you, if you can help in it
Comment: The bones change, but the mesh does not?  Then the mesh is not being deformed by the armature, and keyframing doesn't have anything to do with it (not yet).  It could be that the mesh doesn't have an armature modifier targeting that armature, it could be that it doesn't have weights, it could be that all the bones in the armature have "deform" disabled, it could be that the armature is vertex group modulated and none of the verts are in that group, etc-- can't say without a file.
Comment: Thank you Nathan for your reply. As I wrote,the motion is doing fine, as the poses go alone, without keyframing. It doesn't look like a general problem with the rig (like no proper weights), I just can't record the pose in keyframes properly. As I looked around,the switch between IK and FK needs to have an "extra keyframe" at FK parent level.Though I have it in the workflow,I have a feeling something needs to be cleaned up in that area.I will post the file tomorrow,if I can't dig up a solution till then.And thank you for your reply
Comment: Okay.  I'm confused perhaps then by this: "only the widget controls make the motion as planned, while the mesh remains fixed throughout the whole movement, from frame zero."  Perhaps you could offer some pics-- or better yet a file-- to demonstrate what you mean?
Answer: I make an example to illustrate what would be my workflow in this case:
slider on IK
frame 1: set a keyframe on the IK controllers
slider on FK
frame 21 set a keyframe on the FK chain
frame 11 set the inbetween using FK, use snap IK>FK, set a keyframe on both IK and FK, set a keyframe on the IK-FK slider (1.0 as FK)
frame 10 set a keyframe on the IK-FK slider (0.0 as IK).
If you need to edit the IK-FK slider keyframes, you can find them selecting the gear_shaped bone "upper_arm_parent.L" (in example), part of the IK chain.
Comment: Thank you Josh for the advice,will have a go with it tomorrow and return with the result. As I wrote to Nathan, my feeling is that turning the IK-FK switch (0>>1) and keyframing it at FK parent level is where it gets messy for me so far.Thank you again!
Answer: Finally I could set up the keyframing that it recorded the proper result. Thank you Nathan and Josh for your answers to the issue. The earlier setup didn't work for two reasons:

I was missing a keyframe that the motion starts in IK mode (as default value for IK-FK was zero, I was thinking Blender would use it in the replays as default as well, without an additional keyframe about it). Thus when I replayed the animation in loop,  the rig reached the final frame with IK-FK switch @ 1.0 (as the closing motion was FK). When the scene looped back to te beginning, the mesh wouldn't start the first motion, which was keyed as IK, and change of modes was missing from the keyframes.
Without deeper knowledge about what the magnet snapping does between IK and FK, I used it wrongly. Labelling of snap buttons suggested (as I misunderstood) that when switching from IK to FK mode, perhaps I should snap from IK to FK, what is actually the opposite how it should be done. As now I understand, what snapping does is moving the unused puppet, which should follow after the switch beween IK to FK, into the position of the active mode at the time of the switch (FK copies IK's transforms). So if I start in IK, then at the inbetween pose (when switching is done between the modes), I need to snap FK to IK, to get FK bones into the position of the IK bones, by the time of the switch. So it could carry on the second motion from this point.

Keyframing that worked finally was:
(motion is between 3 poses with 1 inbetween, starting in IK, then switching at the inbetween to FK)

frame 0, about IK widget's starting position
frame 0, about IK-FK switch at IK mode (0)
inbetween keyframe (like frame 20), for final IK pose
fr.20, snap FK to IK (to move FK bones into IK bones' position)
fr.20, IK-FK switch at FK mode, @ 1 (telling Blender to move FK bones from now on)
end frame (like fr.30), about final FK pose


Better incentive to provide feedback on answers

Question: Can we find a better way to give an incentive for people to give feedback on the answers to their questions. I'm thinking about a mechanism to help us close the loop. Sure, there is the "accepted answer" check mark. That works well, but I see a lot of questions with several plausible answers but no accepted answer. There are also cases where there isn't one single answer. I assume that most people eventually find a solution to address their question. It would be nice to have a mechanism that gave them a bigger incentive to tell us what worked and therefore help the next person with the same question. Maybe that could be folded in the reputation score. Just a thought.
Answer: I've said this before, but the OP doesn't owe it to anyone to accept an answer. While it would be polite for the OP to accept the answer that they used there's nothing the system can do to force them to accept it. Increasing the amount of rep you gained for accepting an answer could be counter productive, as it could lead to people accepting anything just to get the rep.
The currently highest voted answer is the "accepted" answer as it's what most people agree with. If you think it's not then down-vote it and/or post a better answer.
Answer: If you have a better solutions to your problem than the ones in the list, post it, you will be voted up.


How does the rand() function in C work?

Question: I want to know how rand() works (even when I don't provide any seed how it produces PRNs?) thanks!
Comment: Given the typical implementation of `rand()`, you're using a quite generous definition of "works". IMO it does not work, even for non security related stuff.
Comment: The `rand()` function of C is not a cryptographic pseudo-random generator, and as such off-topic here. Therefore I'm closing this question.
Answer: Well, successive calls rand() just produce numbers that "look random".
Now, rand() doesn't take a seed; that means that everytime the program runs, calls to rand() will generate the exact same sequence of numbers.  This is a deliberate design decision; that means that the program behavior is reproducible (which can be important if you're debugging).  If you don't want this behavior, well, that's why srand() is provided.
As for what "looks random" means, well, it essentially means "if you eyeball the output, no obvious pattern jumps out at you".
When working with cryptography (you did ask in the crypto stack exchange), we don't have much use for rand(); even if you feed in a seed via srand(), that seed is generally too small to be useful, and even if the rand() output isn't obviously patterned, crypto has much higher criteria for randomness.
On the other hand, other uses need not have such high standards.  I believe rand() may be useful within some randomized algorithms; just not cryptographical ones.
Comment: Even when eyeballing the plot of `rand()` it often exhibits total failure
Answer: You can see in stdlib.c (I found it here) that rand() is defined as:
static long holdrand = 1L;
...
int rand() {
  return (((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff);
}

Of couse this may vary from disto to distro and version to version. You should find your local stdlib.c file (or the one that corresponds to your distro) to see how exactly it's implemented. srand() merely changes holdrand:
void srand(unsigned int seed) {
   holdrand = (long) seed;
}

so as @poncho said it merely garbles the output. No true randomness whatsoever.
Comment: That implementation is just one possibility; in fact, the C standard provides a different sample implementation (similar, but with a different multiplier and constant). Different C compilers/libraries are perfectly free to use something else (and likely will).
Comment: Yes that's very likely. I posted the source to show there's no elaborate algorithms behind rand(), just vile trickery and deception.
Comment: OMG, that's exactly how rand() works on Windows systems!!!! Thank you so much

How does the rand() function in C work?


components magnitude is same to the magnitude of vector and its not parallel or perpendicular to it, how?

Question:
In this picture if R is the component of P which is the reactionary force of mg, then according to the picture R is balancing mg in equilibrium. So my question is how can a component of a vector have same magnitude as that of a vector if its not perpendicular or parallel to it???
Comment: Your question does seem to make sense.  Could you define all of the vectors in your figure?  I suspect that you have an inconsistent view of what each is with respect to the others or that one of the vectors does not belong on the figure.
Comment: the figure is about a object kept on a rough surface and when a force F is applied on it the Vector P which was the reactionary force of mg inclines to the left as F's direction is right. Now fs and R are the components of P and fs is static frictional force and R's has been described in  the question.
Comment: **R** and **mg** are indeed parallel, they just have opposite directions. And **R** is a component of **P**, not of **mg**.
Comment: thats what ive written man
Comment: R is not parallel to P........
Comment: Exactly you how do you get that R is the same magnitude as P? Clearly from the image they are not the same length.
Comment: yeah i got it what i did..... lol
Answer: Your figure is unconventionally made insofar as it suggests that all of the vectors represent independent forces whereas $P$, $R$, and $f_s$ are constrained such that two are the decomposition of the other.
If the block is in equilibrium, then the horizonal forces must balance, and, separately, the vertical forces must balance.  That's a relationship between $F$ and $f_s$ and, separately, between $R$ and $mg$.  Once you solve that, $P$ is determined.
I'm still not able to make sense of the question as you asked it.  Solve the equations, and you have the vector forces.  For each individual vector, the relationship between magnitude and direction depends on the axes you use for the decomposition.  If you decompose along the direction of the vector, then one component is magnitude (and the others are 0), otherwise no component equals the magnitude.  But that's got nothing apparent to do with the diagram since solving for the forces as described will not result in a situation that violates that expectation.
Answer: You have either three forces acting (black in the diagram below) or four forces acting (not the forces labelled $P$.

Force $P$ is the sum of the normal reaction force $R$ and the frictional force $fs$.
The three force look as though they meet at a point $X$ and so it could be an equilibrium situation.
Comment: yeah it is an equilibrium condition
Answer: The component of your vector can have the same magnitude of another vector even if it is not in the same direction because of the principle of superposition: a vector could be seen as a sum of many other vectors along a system of axis. By that, you can thus decompose vectors along the lines that you want in their components.
So, now that you know that you can decompose a vector along the direction (that is "a line") that you want, you can decompose it along the same direction of another vector, to compare them. In our example, you decompose the vector P along the direction of vector $m\vec{g}$.
Parallel means that they lie on a same line (or at least parallel lines) ergo they have 0 angle between them, so you can compare them in a forces' problem like yours to see if there's equilibrium or acceleration.
EDIT: I added an image that make you see how you can use the superposition principle to remember that even if a vector is not on a precise direction, it has its component along that direction, that is the circled one that you don't have to forget


What's wrong with my basil plant?

Question:
Any ideas what's wrong with this plant? It's watered regularly, gets sunlight, in warm climate. Just will not grow. Stems are woody or black. What have I done wrong?
Answer: You probably haven't done anything wrong, but if you've had the plant for a while and/or it flowered, these are only annual plants, meaning they die off as the growing season comes to an end, or after flowering. You can sometimes take  cuttings and start new plants, but otherwise, it just means you need to buy a new plant. The black stems have just gone woody, which usually means the plant is a few months old - mine bought back in May is in the same state as yours.
If you haven't had it too long, you can try cutting it right down to where there are 2 or 3 new leaves towards the base and it might put out some new growth, but if its a few months old, it might not respond.
Comment: Yeah, I'd say just plant some new seeds. Basil doesn't tend to last forever, but it is easy to grow from seed.
Comment: Yes, it has flowered. I had one that lasted for years, I had no idea you had to replant.
Answer: It seems that this basil plant have flowered in past. You might have observed tiny white flowers on this before. The best way to take care of a basil plant is to keep pruning it form the top. This way you will also get regular supply of fresh leaves. Though I do not have much information about it, but it seems that this plant needs to be re-potted. Make sure to add compost/manure to the soil while re-potting. Once the stem becomes woody, there is not much we can do about it. However, basil can be propagated from cutting. You can cut  small top portion with green stem and keep it in a glass with water upto height of around 1.5 inch. This should develop new roots and then that small plant can be planted in fresh soil.
Comment: Yes, it is flowering. I've had a basil plant previous to this that was years old and I never did anything to it! Maybe a different type?
Comment: Maybe. Regular pruning and regular supply of compost / manure is the best way to take care of basil.  Good luck!

What's wrong with my basil plant?


Explanation Of Cauchy's Integral Theorem

Question: When we integrate in terms of  real variables over a closed loop  then we get a positive area enclosed by that loop( in 2D). I don't understand why integration of a complex analytic function comes out to be zero.
Please explain this to me.
Pardon me if you find this question silly.
Answer: Let $\gamma=\partial \Omega$ be a loop bounding the domain $\Omega$ in the plane. Then according to Green's theorem
$${\rm area}(\Omega)=\int_\gamma x\>dy=-\int_\gamma y\>dx={1\over2}\int_\gamma(x\,dy-y\,dx)\ .\tag{1}$$
These are special formulas, and do not contain an arbitrary $f$.
If the same $\Omega$ is considered as a domain in ${\mathbb C}$ and $f=u+iv$ is an analytic function in the neighborhood of $\Omega$ then Cauchy's theorem says that $$\int_\gamma f(z)\>dz=\int_\gamma (u+iv)\>(dx+i\,dy)=0\ .$$
Separating real and imaginary parts here one obtains the two real equations
$$\int_\gamma(u\>dx-v\>dy)=0,\qquad\int_\gamma (u\>dy+v\>dx)=0\ .$$
For the special analytic function $f(z):=z=x+iy$ this gives
$$\int_\gamma(x\>dx-y\>dy)=0,\qquad\int_\gamma (x\>dy+y\>dx)=0\ .\tag{2}$$
Both these integrals are completely different from the area integrals $(1)$. The vanishing of the first is pretty obvious since ${1\over2}d(x^2-y^2)$ is integrated over a loop. It is a consequence of  Green's formula $(1)$ that also the second of the integrals $(2)$ has to vanish.
Answer: A complex analytic function satisfies the Cauchy–Riemann equations and so  both integrands in Green's theorem are zero.
See the details in Wikipedia.
See also Is there any connection between Green's Theorem and the Cauchy-Riemann equations?.
Answer: I think that's a rather deep question. I myself have not studied in depth the proof of Cauchy's Integral Theorem and so can't provide a very thorough answer, but perhaps we can get some intuitive insight if you've studied any vector calculus.$\newcommand{\del}{\nabla}$
In vector calculus there is a similar theorem which states that if a vector field is the gradient of some scalar field (i.e. $\vec F = \del f$ for some $f$), then the vector line integral about any curve $C$ equals the difference in the values of the endpoints of the potential function $f$:
\begin{align}
\int_C \vec F(\vec r) \cdot d \vec r = f(\vec r(b)) - f(\vec r(a))
\end{align}
Hence if the curve $C$ is closed, then $\vec r(a) = \vec r(b)$ and we get
$$ \int_C \vec F(\vec r) \cdot d \vec r = 0 $$
which you can intuitively think of as being a march around a hill. If you start at some elevation and you keep track of your upward and downward movement (that is, you keep track of $\vec F(\vec r) \cdot d \vec r$), you'll find that if your march takes you to your original starting location, then you're upward movement exactly matches your downward movement, and hence your net change in elevation is zero.
You can imagine something similar is happening with integrals in the complex plane. Holomorphic functions are like vector fields that are a gradient of a scalar field, and indicate that "moving around" (that is, integrating) the function is like moving around a hill: if you return to where you start, you won't have changed elevation.
Comment: Thanks for answering. You have made it little bit clear for me. I find your answer more close to what I was asking. Thanks again to all of you.
Comment: This is a bad answer. Having a gradient is not the same as being a gradient. You just gave the intuition for the fundamental theorem of calculus in complex analysis -- iff a function has an antiderivative, its integral on a closed curve is zero. But the essence of the Cauchy Integral Theorem is that if a function has a derivative, its integral on a closed curve is zero, i.e. differentiability implies integrability (at least on a simply-connected domain).


How to enable 1 user to update the database while allowing others to only read in Microsoft Access?

Question: I am planning to put my microsoft access application with forms and database onto a shared drive for around 10+ people to use. However, there is the issue of concurrency. Is there any way to set it such as to allow the microsoft access database to be only updated by 1 person at any one time while allowing others to read it but not update it? For now, the access database can only be updated and read by a single person while the others cannot even open the file. Thanks a lot for any help rendered!
Comment: There is NO reason why multiple users cannot use the database at the same time with full read/write/update ability. So I not sure if your question about allowing or wanting users to be read only is based on massive confusing on your part, or you are attempting to WANT only some users to be read only. Out of the box, Access is multi-user and 5 or 25 users should be able to open and use the application all at the same time. You should however split your database. This concept is explained here: http://www.kallal.ca/Articles/split/index.htm
Comment: What i want to do is allowing only 1 person to be able to update the database while others will read-only.
Answer:
What i want to do is allowing only 1 person to be able to update the database while others will read-only.

Yes, it can be done, and you don't need to change your application code to do it. It can be accomplished by adjusting the permissions on the shared folder and the shared file.
Permissions on the Folder
Whenever one or more users need read/write access to an ACE/Jet database file (.accdb or .mdb), all users must have Create files / write data permission on the folder in which the file resides. This is because their copy of the Access Database Engine needs to be able to create the lock file (.laccdb or .ldb) if they are the first person into the database.
Note that even users who will just have read-only access to the file still need "Create files" permission on the folder. This is essential.
Permissions on the File (.accdb or .mdb)
This is where you differentiate between users who can update the database, and users with just read-only access. Simply use the Windows permissions on the file to give them read+write or read-only permissions as desired.
Common mistake #1: Set user/group permissions (read-write or read-only) on the folder and let the database file (.accdb or .mdb) inherit them
In this situation, "read+write" users can create the lock file but "read-only" users cannot.
• Scenario A: If a "read+write" user opens the database first then the lock file gets created and everything operates as expected. Additional "read+write" users can open the database and make updates, and additional "read-only" users open the database read-only.
• Scenario B: If a "read-only" user opens the database file first, then their copy of Access opens the file as read-only, as expected. However, if a "read+write" user (according to their file permissions) then tries to open the database file they will open it as read-only too. Everyone can get in, but nobody can make changes.
Common mistake #2: Prohibit "create files" on the folder for everyone
In this case nobody can create the lock file so everybody opens the database read-only, regardless of their permissions on the database file itself.
Additional notes:
The results above were confirmed with a mix of Access_2010 and Access_2013 clients connecting to a shared .accdb back-end on Windows Server 2012. In earlier versions of Access, if nobody could create the lock file then the first person "in" would open the database file in "Exclusive mode" and get whatever access their file permissions allowed, while all subsequent users would be denied access with an error message stating that "The file has been opened exclusively by another user."
Answer: No. You could make something programmatically, but it was sure to be rather fragile, locking everybody out every odd day. Access is a good front-end, but not a good back-end for multiuser. Use another database as back-end. In principle SQL Server Express is the easiest option. Of course, you have to split the database into front-end and back-end, it's not clear if you have already done so. If you haven't, you could try how it works with both parts in Access, but my experiences with multiuser networked Access back-ends are not good.
Comment: -1 because "No" is incorrect, and "Use another database as back-end" (with subsequent editorial content) does not address the question.


Weight paint substraction not working? Blender 2.8

Question: i am trying to remove weight paint from a vertex group.
Adding weight works just fine but when i change the weight scale to 0.0 it does not remove weight. What am i missing or how else do i remove weight paint? (I am using Blender 2.8)
Comment: Hi. Can you explain what exact process you are doing when you say "i change the weight scale to 0.0"? Are you clicking buttons, using weight-paint mode? Thanks.
Comment: I imported a 3D-Model, rigged it and applied auto weight assignment (which worked fine), i select a vertex group of which i want to adjust the weight paint and i just want to remove some of the weight paint (make it blue). In order to do that i right click while in weight paint mode and set the "Weight" value to 0. From what i know this is supposed to remove weight, but nothing changes when painting then.
Comment: Stop the presses. It is an Auto-normalize issue. Killing Auto-normalize fixed this problem for me. I hate that solution, but it works.
Answer: The Brush is set to Add by default.
In the top left corner go to View > Tool Settings, now you can change the Brush Mode to Subtract.
Answer: Try changing the brush from "draw" to "Subtract". Draw is designed to create more weight, and subtract to remove it. If it is still not working, try adjusting the strength tab. As far as I know, the weight parameter is the target weight, and the strength is the percentage of that that is added. If that doesn't work, try posting the .blend.
Comment: There is no subtract brush in blender 2.8. If the weight scale on the draw brush is <0.5 it is supposed to subtract and above to add weight.


How to enter special characters like ∞, ˚ in macOS?

Question: I can't enter special characters like ∞, ˚ in macOS. How to enter this character in macOS?
Comment: Switch to the Unicode Hex Input keyboard layout, and you can enter any character by holding down the Option key and its (hexadecimal) code point number.
Answer: While you figured out how to get ∞ and ˚ somehow, a great way to explore keyboard combinations on your own is to do the following:

Open up system preferences.
Go to "Keyboard."
Then go to "Input Sources" and check off "Show Input menu in menu bar."

There will be a small keyboard palette in the menu bar. Select it and click the "Show Keyboard Viewer." You will then see the following virtual keyboard.

In this screenshot you can see I am pressing Option and it shows the characters and combos related to holding down Option. The smaller items in the upper left-hand corner of the keys can be accessed by holding down Option and Shift.
Play around with it to get to know what combos can be use.
Answer: Press Ctrl+Cmd+Space to get an emoji and character picker. At the top right next to the search bar of the pop-up there is an icon to switch between emojis and general characters. It also remembers frequently used characters.
You can also long press a key like E to add diacritics to it (if you long press an unsupported key nothing will happen). You will get a pop-up with è, é, ê, etc. Each option has a number assigned which you can press, but you can also click it.
These two work in most apps on macOS.
Answer: Also from the "Input Sources" pane on the Keyboard preference panel, click the + button to add the Unicode Hex Input keyboard layout (select "Other" from the list of languages on the left to reveal it).
Using this keyboard layout, you can enter any Unicode character by holding down the Option key while typing its code point number in hexadecimal.
Comment: Great answer! Never knew about this.
Comment: Thanks for adding the screenshot; I was too lazy to do that.
Answer: To enter ∞: Option + 5
To enter ˚: Option + 0
Comment: This assumes a specific keyboard layout; it's not true in general.
Answer: If you are trying to edit a document with math symbols that will be made into a pdf, you might consider LaTeX.  One easy-to-use online implementation is overleaf.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: This is not an answer. The original poster is looking for macOS specific character entry; not a specific application. And honestly, no person who does basic day-to-day work ever wants to enter more than a few key combinations. LaTeX is its own world.


opamp power supply

Question: I have a 24-48V power supply and opamp that i want to use is lmp8601 which takes +5V-GND power supply and can take common mode voltage upto 60V. Problem here is that I do not want to use two separate power supplies.
I wanted to know if the opamp will work until the difference between postive and negative rails is 5V i.e if I give let's say 40V to +Vs and 35V to -Vs, will the opamp still work or is there any limitation for that?
Answer: The maximum supply voltage of the LMP8601 is 6V so indeed you cannot use the 24-48 V supply. As long as you make sure the opamp's supply voltage does not exceed 6V it will work. So yes you can feed it with 40 - 35 V = 5V as long as you make sure that the input voltage remains within spec.
The input voltage range is -22 - + 60 V but that is relative to the -Vs pin of the opamp ! So if you feed it with 35 V and 40 V then the lowest input voltage allowed is 35 V - 22 V = 13 V ! Also note that the output voltage of the opamp will then also be relative to 35 V since this will be the "ground" from the opamp's view.
So the opamp's output voltage will always be between 35 V and 40 V.
But why not feed the opamp with +5 V and ground ? Just make a local supply voltage using a regulator or a resistor and a zener diode ?
Comment: Yes, that's the first thing that came to my mind also but power loss is major issue here. If the desired specs aren't met then I guess I will have to stick with LDO or zener only.

opamp power supply


Linux fgrep how to extract "only_words_in_my_language" from a big "MIXED_WORDS" file?

Question: I want something to extract "only_words_in_my_language(900kb)" from a big "MIXED_WORDS(160mb)" file and for that i used the syntax bellow but with poor results:
fgrep -w -f "only_words_in_my_language.txt" "MIXED_WORDS_from_all_over_the_world" > extracted_word_of_my_country_only.txt

That's why i'm thinking mmmm.. to ''MATCH'' the entire WORD,for better results
For example this is a WORD in my language:
Maimuta - 7 letters lenght,if i match the entire word the results could be:
maimuta@123
maimuta2016!
Maimuta01!
maimuta@123456

if i match 6 letter the res. could be:
maimut
maimutoi1
Maimutareala01!

So my question is how to do that??how to match the entire word
A regex or something for linux please
thank you
Godluck to all!!
i tried this but,dnes't work:

fgrep -iowf "my_lang_dict.txt" "mixed_words" >
  my_lang_unique-words.txt

My lang.dict.txt(900kb) and mixed_file(64 mb),grep says: Memory Exhausted
Imagine ur bulgarian,russian and you want to extract ''only'' the words that are in the language of your country from a big mixed words all over the wordl text file.How u would do that?u need a ''ur country'' dictionary right?and then compare all the words from ur country dictionary with the mixed one and i think best results are.... when u match the entire word!
Answer: As the error message tells you, you don't have enough memory. The system is building up a regular expression to match all the words in your 900KB file. The size of the mixed_word file doesn't matter. The error message might be misleading in that it might be that it really means regular expression too complicated.
You should be able to break your lang.dict.txt into smaller chunks. You can use the unix command split to do this.

Linux fgrep how to extract “only_words_in_my_language” from a big “MIXED_WORDS” file?


CiviCRM SearchKit Field Style

Question: I have built a table in SearchKit and I want to colour the rows based on a person display name. Whilst the available styles are useful I would like to expand these to have more colours available I have searched on Google and looked through Civi docs but could not find much information. Any ideas would be much appreciated. See the image below for further detail:
Answer: You can add your own class with the Other option and then load some css targeting that class, either via a custom css file (under Admin > System Settings > Resource URLs), from your CMS or in an extension. The custom css file option is the easiest, though it will load on all pages.
Comment: Thanks this is great, ideally I would prefer not to use the Resource URLs as I don't want it to appear anywhere else but the table. We are running on top of Drupal, are there any existing extensions that supply the required functionality ? Appreciate the help.
Comment: I've used CSS Injector for this on D7 (Asset Injector on D8).
Comment: Yeah I did try that is there any way to prevent the CSS applying across the whole website? I only want to color the rows if they match the set display name? Appreciate all your help thus far.
Comment: You should be able to set the path for the rule in CSS Injector. Unless that doesn't work with angular pages?
Comment: It should work if embedded on an afform. Afform routes are "real" pages :)

CiviCRM SearchKit Field Style


Cocos2d - Setting Device/Screen Orientation

Question: I am new to the cocos2d API and have noticed that there are a few ways to set the screens orientation within the templates. I have not been able to figure out the correct way to set my orientation to LandscapeRight and keep it that way throughout the entire game. How do I change my orientation so that it maintains LandscapeRight? Any help is appreciated. Thank you!
Answer: The answer here has changed with cocos2d 2.0, as CCDirector is now a ViewController on iOS:

CCDirector no longer supports device orientation. All autorotation and
  device orientation is handled by RootViewController now. Fortunately,
  [[UIDevice currentDevice] orientation] can be used in place of
  [[CCDirector sharedDirector] deviceOrientation]. The enums are the
  same, except that they begin with UI instead of CC.
Forcing a specific orientation is a simple matter of returning YES
  only to the desired orientation in the RootViewController method
  shouldAutorotateToInterfaceOrientation.

Choosing between Cocos2D v1.x & 2.x and Tips for updating to Cocos2D 2.0 at learn-cocos2d.com
Answer: Modify GameConfig.h from the cocos2d template.
#define GAME_AUTOROTATION kGameAutorotationNone
/* original code is kGameAutorotationUIViewController. */

And modify AppDelegate.m as well.
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
    [director setDeviceOrientation:kCCDeviceOrientationPortrait];
#else
    [director setDeviceOrientation:kCCDeviceOrientationLandscapeRight];
    /* original code is "Left". */
#endif

Answer: Use this line:
[[CCDirector sharedDirector] setDeviceOrientation:kkCCDeviceOrientationLandscapeRight];

Answer: In the RootViewController.m,search for the line
return ( UIInterfaceOrientationIsPortrait(interfaceOrientation ));

change it to
return ( UIInterfaceOrientationIsLandscape(interfaceOrientation ));

Answer: if you added shouldAutorotateToInterfaceOrientation and not solved your problem
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

THEN
Try to add this line to appDelegate.m
[window_ setRootViewController:navController_];

Good Luck
Answer: The correct answer - took me a while to find - is in the info.plist, change the supported interface orientations values, item 0 and item 1 have 4 possible values, Portrait (top home button) etc.


run bunch of commands and wait

Question: I want to run bunch of commands simultaneously and when all of them finished, run another bunch of commands.some thing like this
command1 & command2
echo "command 1 and 2 finished"
command 3 & command 4
Comment: Look into using the wait command.
Answer: command1 &
command2 &

wait
echo 'command1 and command2 have finished'

command3 &
command4 &

wait
echo 'command3 and command4 have finished'

The call to wait will pause the script until all backgrounded tasks have finished executing.
Alternatively (just "for your information"), depending on whether you want command 1 and 2 to run concurrently or not (equivalently for command 3 and 4):
( command1; command2 ) &
echo 'command1 and command2 are running'
wait
echo 'command1 and command2 have finished'

In the above case, command1 and command2 will run in the background, but not concurrently with each other.

Doing
command1 & command2
wait

is equivalent to
command1 &
command2
wait

... which will work, but command2 will not be running in the background and wait will not be called until command2 has finished executing.
Comment: @Leo The process ID (PID) of the most recently started background task is available in `$!`. You could save these in an array (`pids+=( "$!" )` after starting a job) and then wait for them (`wait "${pids[@]}"`).  That's assuming you have a shell that supports arrays.
Comment: Problem is that I have some other tasks running already in the background. Lets call them `&1` and `&2`. Is there a version of this where I can capture the task ids of `command1` and `command2`, then do a `wait &3 &4`? Ta.
Comment: Thanks for that. I'll try. In the meantime maybe you could add the answer here: https://unix.stackexchange.com/questions/554602/wait-for-processes-started-in-a-for-loop-but-not-others-started-earlier
Answer: The actual answer of my question was something like this, special thanks from @raman-sailopal
command1 & command2
wait
echo "command 1 and 2 has finished"
command3 & command4

Comment: That will work, but thu `wait` will only wait for `command1` as `command2` is not run as a background task.  The same goes for `command4`.
Answer: command1 & command2; echo "command1 & 2 complete" && command3 & command4; echo "command3 & 4 complete"

& runs commands simultaneously
; emulates a new line - i.e. will be run after completion
&& runs once the previous job has finished, provided the previous job was successful (i.e. didn't return any exit code but 0)
Comment: This doesn't work: `command1` will run in the background, the first `echo` will run as soon as `command2` completes, regardless of whether `command1` has finished. Likewise for `command3`.

run bunch of commands and wait


If I upgrade my clan castle after war loot has been given out, will I get more loot?

Question: I am in a clan war, and I will get more loot than I have room for in my clan castle. If I upgrade my castle before I collect the loot, will there be more to collect than there currently is?
Answer: Nope.
Whenever you receive loot, you only receive the full amount (if your resources have space for them all), or up to the amount to entirely fill up your resource tanks. The rest is lost into the abyss.
As for upgrading your resource tanks/clan castle - Overspilled resources (that amount that couldn't fit into your already-full resource buildings) cannot be recovered.

All I can suggest is that always have a big-enough resource storage or: make sure you can house more resource than you can think of ever getting.
(My resource tanks always get filled up by the harvesting of a single full resource collector. Basically: My resource tanks can hold one third of what I harvest.)
Answer: Answer would be "Yes" if you able to upgrade ur castle before end of war. And "No" if u upgrade castle after end of war.
 Don't attack on base whose town hall outside. Because other player also do same which will affect war result at end of war.
Answer: no matter how much your clan castle is upgraded, once you use your attacks the loot you get from that is how much you get.


Zlib Error Message

Question: I have a "zlib error" message as I'm playing an old school RPG called "Laxius Power" on Windows XP. It just kicks me out of the game! How can I fix it?
Comment: At least post the error message.
Answer: Zlib is a compression library.  Perhaps your game uses some data files that are stored compressed on disk, and one of those files is corrupt or missing.  If the error happens when you start the game, there's a chance that's the problem.  If the error happens during game-play, who knows.

Zlib Error Message


What is the Scriptural basis for Modalism?

Question: We hear a lot at times about the godhead, so that got me wondering: what is the Scriptural basis for the Christian doctrine of Modalism?
Answer: The United Pentecostal Church International, who are a denomination of Oneness Pentecostalism, and adopt the doctrine of Oneness, which is essentially the same as Modalistic Monarchianism, offer the following in support of their Doctrinal Foundation:

The Oneness of God
God is absolutely and indivisibly one (Deuteronomy 6:4;
  Galatians 3:20). In Jesus dwells all the fullness of the Godhead
  bodily (Colossians 2:9). He is the self-revelation of the one
  God, the incarnation of the full, undivided Godhead (John 20:28;
  I Timothy 3:16).
God has revealed Himself as Father (in parental relationship to
  humanity), in the Son (in human flesh), and as the Holy Spirit (in
  spiritual action).  (See Deuteronomy 32:6 and Isaiah 63:16;
  Luke 1:35 and Galatians 4:4; Genesis 1:2 and Acts
  1:8.) The one God existed as Father, Word, and Spirit before His
  incarnation as Jesus Christ, the Son of God; and while Jesus walked on
  earth as God Himself incarnate, the Spirit of God continued to be
  omnipresent. However, the Bible does not teach that there are three
  distinct centers of consciousness in the Godhead or that Jesus is one
  of three divine persons.
Jesus is true God and true man as one divine-human person. We can
  distinguish these two aspects of Christ's identity, but we cannot
  separate them. The Incarnation joined the fullness of deity to
  complete humanity.
Jesus possessed all elements of authentic humanity as originally
  created by God, without sin. Thus we can speak of Jesus as human in
  body, soul, spirit, mind, and will. (See Matthew 26:38; Luke
  2:40; 22:42; 23:46; Philippians 2:5.) According
  to the flesh, Jesus was the biological descendant of Adam and Eve,
  Abraham, David, and Mary. (See Genesis 3:15; Romans 1:3;
Galatians 3:16; Hebrews 2:14-17; 5:7-8.) We should
  not speak of two spirits in Jesus, however, but of one Spirit in which
  deity and humanity are joined.
Christ's humanity means that everything we humans can say of
  ourselves, we can say of Jesus in His earthly life, except for sin. In
  every way that we relate to God, Jesus related to God, except that He
  did not need to repent or be born again. Thus, when Jesus prayed,
  submitted His will to the Father, and spoke about God, He simply acted
  in accordance with His genuine humanity.
As Jehovah manifested in the flesh, Jesus is the only Savior (Isaiah
  45:21-23; Matthew 1:21-23). Thus, Jesus is the only name
  given for our salvation (Acts 4:12). The Father was revealed to
  the world in the name of Jesus, the Son was given the name of Jesus at
  birth, and the Holy Spirit comes to believers in the name of Jesus.
  (See Matthew 1:21; John 5:43; 14:26; 17:6.)
  Thus, the apostles correctly fulfilled Christ's command in Matthew
  28:19 to baptize "in the name [singular] of the Father, and of the
  Son, and of the Holy Ghost" by baptizing all converts with the
  invocation of the name of Jesus.

Source: Our Doctrinal Foundation; United Pentecostal Church International
Comment: That's what the UPCI–who are a global modalist denomination–provide as scriptural evidence. I created links for all of the references they provide in support of their claims.
Comment: Was that meant to provide Scriptural evidence for modalism?
Answer: The umbrella term for the doctrines that include Modalism is Unitarianism.
The scriptural support for Modalism is the same as that for the Trinity, except they interpret the scripture as speaking of God as one person manifest in our dimensions in differing modes. I would argue that the Unitarian interpretation involves ignoring multiple key scriptures that evince three separate persons, such as at Jesus' baptism where the Holy Spirit comes down and the Father speaks:

9 In those days Jesus came from Nazareth of Galilee and was baptized by John in the Jordan. 10 And when he came up out of the water, immediately he saw the heavens being torn open and the Spirit descending on him like a dove. 11 And a voice came from heaven, "You are my beloved Son; with you I am well pleased."

In Unitarian thinking, therefore there is one person who, in the OT, is revealed as the Father God, and in the New Testament is revealed first as the incarnate Christ, and then, after the ascension, as the Holy Spirit.
They contest the orthodox claim that there are three persons in the Godhead, and claim instead there is one person who, at different times, wears a different "mask", if you will.
Closely related is Patripassionism, which takes Modalism further and says that the Father suffered at the cross (and, presumably so did the Holy Spirit) since each is merely the same person in different guise.
The Trinitarian doctrine, is that God is one in nature and three in persons. Conversely, the Unitarian doctrine is that God is one in nature and in person.


Lectrosonics LMa's vs Sennheiser EW100's

Question: I have two Sennheiser EW100 (G1's I think) radio mic kits, but they only put out 10mW and I often have issues with dropouts.
Now I am looking at purchasing the Lectrosonics LMa series of transmitters and the UCR100 receivers, together with the MP152 lapel mics.
Does anyone have experience with the LMa and UCR100 setup and the MP152 microphones?  I'd love to hear your views and comments!
Answer: We finally replaced the last of our Sennheiser's with SMQV's paired with the SRa's. We have also been using the LMa's with the UCR411a's. They are used in a run and gun style all day event.
We don't have the same setup as you but I have to say Lectrosonics are magical.
Comment: +1. I also use LMa's, 401's, and 411's. All stellar, bombproof, and never an issue when used properly.


Reactive power in a system

Question: Generally speaking, reactive power in a system is not good in any system (say transmission lines, etc.), but if somehow we decrease the reactive power to zero then will it be a perfect system? Or is decreasing the reactive power in a system to very low not good for that system?
Comment: Try looking up power factor correction and also consider that for the questions you have previously asked, some folk might see it as rude if you don't formally accept the best answers. It's a small price to pay for getting good advice.
Answer: The statement "reactive power is not good" is not always applicable. Yes reactive power does not contribute to any energy transfer but contributes to losses. However there are situations (notably fault recovery in a large power system) where reactive power is highly desirable.
EDIT: adding some info based on comments:
Induction machines- motors and generators-  need reactive power to function: in crude terms this reactive power sets up the "magnetic field" in the machine. Transformers draw reactive power too.
Comment: Asynchronous AC motors are inductive loads so they need reactive power, too.

Reactive power in a system


CMake: relink when linked package is rebuilt

Question: I apologize if this has been asked already but I can't find online the right way to get this thing to work.
I have a cmake project Foo which depends on another cmake project Bar. Goal: whenever Bar is reinstalled (changing only the libraries, not the headers), then Foo should re-link (without rebuilding, of course).
So, in the CMakeLists.txt in the top folder of project Foo (which has only one target, an executable) I have the cmake command
FIND_PACKAGE(Bar REQUIRED)

Which, correctly, finds project Bar at configure time. In the part where I create the target, I have
LINK_DIRECTORIES (${BAR_LIBRARY_DIRS} )
ADD_EXECUTABLE(foo.exe main.cpp)
TARGET_LINK_LIBRARIES(foo.exe ${BAR_LIBRARIES})

The two variables in there are defined in BarConfig.cmake, which is the one that FIND_PACKAGE(Bar) looks for, and contains only the following instructions
SET(BAR_INCLUDE_DIRS "${CMAKE_CURRENT_LIST_DIR}/../../../include")
SET(BAR_LIBRARY_DIRS "${CMAKE_CURRENT_LIST_DIR}/../../../lib")
SET(BAR_LIBRARIES bar)

I printed on screen those variables and they contain what you expect them to contain (/path/to/folder/include, /path/to/folder/lib and bar).
So, I read somewhere that cmake cannot add a dependency to a library which is not specified with its complete path. One should write
TARGET_LINK_LIBRARIES (foo.exe full-path-to-bar-libraries)

In that case, it works. But it's unsatisfactory. First, cause the path can change. But you can read it from a variable, you might say. True. But, second, even in that case, if the project Bar contains a number of libraries that is not known, one would have to sweat to create the correct string to add there...
However, I also read that if that library is also built and installed with cmake, it should work automatically. As a matter of fact, I have another project pair, A depends on B, both built with cmake. In that case the dependence works. Unfortunately, the project B is HUGE, and defines TONS of cmake macros, and I can't identify the part where it sets up the right variables.
Do you have any idea of how to get Foo to re-link (without rebuilding) every time that the library Bar is reinstalled? I would like to avoid to use full path.
Thanks
Edit: to be more clear: if library Bar set up a variable BAR_LIBRARIES containing all its libraries with the full path, then TARGET_LINK_LIBRARIES would work. However, most likely BAR_LIBRARIES would contain 'bar', rather than '/some/path/libbar.a'. I'd like cmake to be able, given the directories provided with LINK_DIRECTORIES and the library names provided with TARGET_LINK_LIBRARIES to put the two pieces together. E.g. if BAR_LIBRARY_DIRS contains '/folder1/;/folder2/' and BAR_LIBRARIES contains 'bar1;bar2', I'd like cmake to establish a dependency on libbar1.a and libbar2.a, found in any of the following:

/folder1/libbar1.a
/folder2/libbar1.a
/folder1/libbar2.a
/folder2/libbar2.a

And relink if any of the ones upon which a dependency has been created is changed since the last linking.
Answer:
and contains only the following instructions

You don't need to set all this variables manually, just use CMakePackageConfigHelpers module:
configure_package_config_file(
    "./FooConfig.cmake.in"
    "${foo_config}"
    INSTALL_DESTINATION ${CONFIG_INSTALL_DESTINATION}
    PATH_VARS CONFIG_INSTALL_DESTINATION
)

install(
    FILES "${foo_config}"
    DESTINATION ${CONFIG_INSTALL_DESTINATION}
)

and install targets:
install(
    TARGETS foo DESTINATION ${LIB_INSTALL_DESTINATION} EXPORT FooTargets
)
install(
    EXPORT FooTargets NAMESPACE Foo:: DESTINATION ${CONFIG_INSTALL_DESTINATION}
)

Usage in other project:
find_package(Foo CONFIG REQUIRED)
target_link_libraries(boo Foo::foo)

That's all. Work like a charm (Makefile generator example):
> cmake -HFoo -B_builds/Foo -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="`pwd`/_install"
> cmake --build _builds/Foo/ --target install
> cmake -HBoo -B_builds/Boo -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="`pwd`/_install" -DCMAKE_VERBOSE_MAKEFILE=ON
> cmake --build _builds/Boo

One more time (check no relink):
> cmake --build _builds/Boo

Modify target Foo and reinstall:
> echo "void some(){}" >> Foo/foo.cpp
> cmake --build _builds/Foo/ --target install

Now build Boo:
> cmake --build _builds/Boo
...
Linking CXX executable boo.exe
...

Relink!
Comment: Thanks for your reply. I followed the example at the link you posted, but I can't get the code to relink.
Comment: The cmake version is 188.8.131.52. The kernel is a Linux version 2.6.32 (gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC) )
Comment: Thanks, I'll try it out as soon as I have some time. Just...where can I find it?


how to block , a dieferent web pages with active directory (SMB 2003)?

Question: we apreciate your help...
best regards!!
Comment: Sorry, I was going to try and tidy up the language/structure of the question but I've really got no idea what's being asked.
Answer: Forget Active Directory, Look at DNS
It's not a particularly nice solution if you have a lot of them to block. Still possible though. Hopefully this explains how.
If you want to block entire domains you would:

Open the DNS Console
Expand Forward Lookup Zones
Create a new Forward Lookup Zone, as a Primary Zone
Give it the name of the domain you wish to block. e.g. annoyingdomain.com.

If you just want to block websites under domains you do almost the same:

Open the DNS Console
Expand Forward Lookup Zones
Create a new Forward Lookup Zone, as a Primary Zone
Give it the name matching the site you want to block. e.g. www.annoyingdomain.com.

This way, you could still send mail and access other resources as annoyingdomain.com, it's just the address for www.annoyingdomain.com which gets answered by your own DNS Server.
Like I said, not exactely a nice solution, but, if you just want to block a few sites like myspace of Facebook, and dont have the money to spend on an Appliance as Wesley Recommended
Although I will say an appliance is the better solution
HTH
Answer: Use Group Policy to edit IE's Content Advisor settings. You may need the ADM templates for IE. However, that will only work for Internet Explorer settings so you'll have to block all other browsers somehow. Really, your best bet will be an appliance (E.g. Websense) or proxy server (E.g. Squid Cache).


How do INFOSEC competitions deal with social engineering?

Question: Whenever I read about a cybersecurity competition, I always wonder, since almost everyone involved is a security professional, can such exercises ever be realistic? One of the weakest links in any information system is the user; how can a competition simulate the effects of social engineering? Do they find a bunch of random people to act as network users? Do they add in confederates who intentionally click on everything?
Comment: Can you give an example of a "cybersecurity" competition? Are you referring to Capture The Flag competitions?
Comment: Yeah, they don't really handle SE in that regard, they'll handle it as answered by Terry below. They don't have users in the environment that will click on stuff. I have seen some CTFs (especially oCTF at Defcon) that will award points by doing things like sneaking into the organizer area and grabbing a flag there, or spying on the other teams. There are no SET-like challenges, since it mostly requires an uneducated user.
Answer: I am not certain you understand the common types of security competitions. Most are specifically for security professionals, and have nothing to do with what a non-security-aware user would do.
Some examples: working out how to exploit rare or hard-to-find vulnerabilities, linking different vulnerabilities together, writing zero-days, identifying systems from limited information etc.
Simulating the effects of users randomly clicking on things is mostly irrelevant to those competitions, and is not what I would consider social engineering anyway.
That said, some competitions allow social engineering as a technique, giving you points for info/trophies gathered by non-technical means (ie lying, cheating, physically gaining access etc)
Answer: The point of those competitions is not perform an attack like if it was real where you can trick the user to give away data, rather it is a competition that shows who is the fastest team finding specific data (flag) using technical means.
As an example, look at it as if it was an online wargame (hackthissite, hackthis...) but played as a team.
Answer: One particular CTF I participated in, Air Raid organized by ThinkSECURE, awarded "social engineering" in two ways.
The first way is giving out points for obtaining the participant tags of other teams. Every team member is given a tag at the start of the competition. The tag is needed when claiming points from the game masters for completing certain task. Obtaining the tags of other teams using any means (besides physical of course), will earn your team a decent amount of points.
The second way is giving out points for catching other teams breaking the rule of the game. This requires some rather strong evidence but is worth a good amount of points if you successfully report another team.


How does Java makes use of multiple cores?

Question: A JVM runs in a single process and threads in a JVM share the heap belonging to that process. Then how does JVM make use of multiple cores which provide multiple OS threads for high concurrency?
Comment: As far as I'm aware, Java threads are native OS threads (in most JVMs). Nothing special about them.
Comment: Native application threads also run in a single process and share a common memory allocation (and can still make use of multiple cores).
Answer: You can make use of multiple cores using multiple threads. But using a higher number of threads than the number of cores present in a machine can simply be a waste of resources. You can use availableProcessors() to get the number of cores.
In Java 7 there is fork/join framework to make use of multiple cores.
Related Questions:

Is Multi-Threaded algorithm required to make use of Multi-core processors ?
Threads per Processor
Correctly multithreaded quicksort or mergesort algo in Java?
Comment: Machines usually have only 2 or 4 processors. You stated that "using a higher number of threads than the number of cores present in a machine can simply be a waste of resources", does that mean that we should have around only 2 or 4 threads to maximize performance?
Comment: "But using a higher number of threads than the number of cores present in a machine can simply be a waste of resources." That doesn't make a whole lot of sense in the general case. If you have more threads than the number of cores the threads would be distributed across those cores and would get their share of the given core just like any other running thread/process thereby allowing it to make progress which would definitely be more efficient than doing the work sequentially.
Comment: @ ChiefTwoPencils; If we have two applications and each application has 6 threads running on 4 CPU cores. In this case how tasks will distributed across these CPUs? Another question in a single application 6 threads are running on 4 CPUs will all 6 threads parallely running across these 4 CPUs or interleaving operations across thread
Comment: Is it true, that if you run a web application on Tomcat (on Java 8 for instance) where each incoming HTTP requests is processed by a Java-Thread, web apps therefore automatically benefit from multiple cores, right? Today you can rent 32-core AMD machines which sound perfect to me to run a web app. Sure: cloud is another option, but I'm talking about dedicated servers now... Any comments?
Answer:
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. Then how does JVM make use of multiple cores which provide multiple OS threads for high concurrency?

Java will utilize the underlying OS threads to do the actual job of executing the code on different CPUs, if running on a multi-CPU machine.  When each Java thread is started, it creates an associated OS thread and the OS is responsible for scheduling, etc..  The JVM certain does some management and tracking of the thread and Java language constructs like volatile, synchronized, notify(), wait(), etc. all affect the run status of the OS thread.

A JVM runs in a single process and threads in a JVM share the heap belonging to that process.

JVM doesn't necessary "run in a single process" because even the garbage collector and other JVM code run in different threads and the OS often represents these different threads as different processes.  In Linux, for example, the single process you see in the process list is often masquerading a bunch of different thread processes.  This is even if you are on a single core machine.
However, you are correct that they all share the same heap space.  They actually share the same entire memory space which means code, interned strings, stack space, etc..

Then how does JVM make use of multiple cores which provide multiple OS threads for high concurrency?

Threads get their performance improvements from a couple of reasons.  Obviously straight concurrency often makes the program run faster.  Being able to do multiple CPU tasks at the same time can (though not always) improve the throughput of the application.  You are also able to isolate IO operations to a single thread meaning that other threads can be running while a thread is waiting on IO (read/write to disk/network, etc.).
But in terms of memory, threads get a lot of their performance improvements because of local per-CPU cached memory.  When a thread runs on a CPU, the local high speed memory cache for the CPU helps the thread isolate storage requests locally without having to spend the time to read or write to central memory.  This is why volatile and synchronized calls include memory synchronization constructs because the cache memory has to be flushed to main memory or invalidated when threads need to coordinate their work or communicate with each other.
Comment: The whole point here @NikiHerl is that the Java threads have OS thread equivalents.   If I'm not specifying the type of thread then it doesn't matter.  For example, when I talk about isolating IO to a single thread, that is for both the JVM thread and the OS thread which is doing the work.
Comment: Thank you for this answer - but I have a request:
It would be really helpful if you could prefix "OS" or "Java" before each use of the word "thread". The clash of terms is terribly confusing to me (and I'd guess some others too) and I'd be lying if I said I really understood the whole thing now.
Answer: Java will benefit from multiple cores, if the OS distribute threads over the available processors. JVM itself do not do anything special to get its threads scheduled evenly across multiple cores. A few things to keep in mind:

While implementing parallel algorithms, it might be better to spawn as many threads as there are cores. (Runtime.getRuntime().availableProcessors()). Not more, not less.
Make use of the facilities provided by the java.util.concurrent package.
Make sure that you have Java Concurrency in Practice in your personal library.
Comment: Threads are just doing some processing but not waiting for any remote calls(Like Database, Remote API, JMS and so on.. ) then the above suggestion makes sense. But in practical, all regular applications make use of Remote calls. So the best number of threads can be vary based on on latency of your remote calls. do load test and decide.
Comment: Not more, Not less. Incorrect. As per the book you suggested, one should spawn (No. of processors + 1), since while some thread is doing IO, the extra thread can make use of idle C.P.U.
Answer: Green threads were replaced by native threads in Java 1.2.
Comment: +1 - In other words, the OS will arrange that different java threads using different cores ... depending on system scheduling and resource management constraints.


Using Well Pump 240 v Circuit For 110 v Light With Plug

Question: I built a shelter around my pump down here in central Fl. For a pump business I was suprised they ran 12-2 romex in the conduit from the breaker box on the power pole. The pump has red, black and green going into the well. They both ground on the pressure switch case. I bugged a receptacle on the black and ground and ran my miter saw and compressor to build the shelter with no issues. I would like to have a light in there and a gfi for power to work in there if needed. Is there any safe way to use a gfi or a light in there short of removing the romex and pulling re-pulling individual thnn wires with a neutral. I'm not sure the outdoor panel for the m/h bonds the neutral and ground, I have to recheck.  Thanks. GBY
Comment: I'll let the experts give the full (very detailed - ground rods, etc.) answer. But the short answer is: Replace the 12/2 with hot/hot/neutral/ground wires and put in a small subpanel. Run the pump 240V and put in a couple of 120V circuits all in the subpanel. Ground should be separate from neutral in the subpanel.
Comment: What size is the conduit in question, and is it a continuous conduit run from one end to the other, or just a protective sleeve where the cable enters the ground?
Answer: Stop using ground as neutral. If your grounding system is anything shy of perfect, you'll energize everything that's supposed to be grounded.
The fact that it has conduit on the ends doesn't mean it's entirely conduit.  If the line were direct burial, the descent to depth is required to be in conduit for physical protection.  *Push and pull the wire. If it has about an inch of relatively free play, then it's in conduit.
Use a subpanel
If it is indeed conduit, then you can fish in THHN wires: two hots, a neutral and a ground, all #10. Bring that to a subpanel, and have a 20A double breaker in the sub power the well, and 20A single breakers feed convenience outlets and other 120V loads.  You will also need a local grounding rod, or rather 2 rods 10' apart unless your AHJ will let you use the well pipe.  AHJ=authority that issues permits and inspects.
You can then upsize the breaker in the main panel to match the wire (30A for #10, 50A for #8 THHN).
Otherwise... Use a transformer
For casual loads like you might plug into an outdoor receptacle, a 1.5 KVA transformer will suffice.  If you want a LOT of power out there, a 5 KVA 1-phase transformer off Craigslist will do.  Do not use a "step-up/down transformer" because that can accidentally put 240V on your hot and 120V on your neutral.  You need an isolating transformer.  For small loads like this, I would leave it isolated, i.e. don't bond neutral to ground. And have it feed a GFCI recep for statutory reasons.
Why not bond?  Bonding (vs isolated system) is a double-edged sword.  An isolated system has no relationship with ground, so touching hot is harmless - power doesn't flow because there's no loop. On the other hand, bonding neutral to ground forces hot to be within 120V of ground, which protects you from leakage from the 7200V transformer primary.  But in this case, the transformer primary is + and - 120V from ground (summing to 240V), so bonding does not make it any safer. Therefore isolation affords better safety.
Comment: @manassehkatz Not a fan of that.  That would put the well on GFCI.  Like a refrigerator, a well pump attached to a 300' metal pipe isn't helped much by GFCI, and is hurt by the risk of nuisance trips. Noting your add, yes, Murphy's Law says that the trek outside to reset the well pump GFCI *will* happen when you're in pajamas and it is somehow both -10F and raining.
Comment: With subpanel option: Shouldn't OP replace original 20A breaker in main panel with 30A to get the most out of the #10 wires? With either option: I get totally confused about grounds - are they needed here since it is a separate structure?
Comment: @manassehkatz Dur, your intuition was right on both.
Comment: Not my intuition - my reading your other answers over the last couple of years.
Answer: There might be a safe, code compliant way do this with the existing cable in the conduit - if that cable is UF type.  (If it's NM, it's probably already a code violation.  However since the conductors inside the cable are probably THWN rated, and possibly stamped THWN, it might be passable.)
But none of the options I can see would be simpler, easier, cheaper, or safer than just running replacing that cable and adding wire for a second GFCI protected circuit for a light and a convenience receptacle.
The motor circuit has totally different rules than a general purpose circuit you'd use for receptacles / lights.  In some cases you can put a motor on a general purpose circuit, but not likely in this case, especially since you'll want GFCI protection on the general purpose circuit and you won't likely want it on the motor.
Comment: Nate S, Yes, they are. If you remove the jacket and look at the individual conductors, they often don't have markings because they are not required to. But starting in the 2008 NEC, equipment that says that you must use 90C rated wire resulted in the release of "NM-B" cable. Suppliers don't want to have to carry inventory of two kinds of NM cable, so everything you buy now is NM-B, meaning the internal conductors are rated for 90C, even though you still size it for 60C. UL just calls for 90C PVC insulation which translated to the mfrs using THHN/THWN inside since they already make that.
Comment: Actually, you may want **might even be required** gfci on the pump. But I don't know the code so just a comment.
Comment: Where are you finding NM with THWN rated wires inside?  I've never even heard of such a beast.  I'd argue that it's very likely that the internal wires are *not* TWHN rated in any random piece of NM cable.
Comment: Wow, impressed with all the comments and the knowledge here. I have to do a little digging or disconnecting to find more info. They did run 12-2 romex in 1/2" cantex conduit. I imagine that it's continous to the pump. I can't imagine they would bury romex as is but if the put it in conduit,   Really was hoping to figure it out without repulling. Might have to let this set as other projects have more priority
Comment: OK, latest update. I opened the mobile homes 200 amp breaker box at the pole. It has a double breaker for both hot legs, 90 amp double breaker for the heatpump package unit. It also has the 20 amp pump double breaker. I added a 20 amp double breaker with  12-3 with a ground uf cable in conduit out to two sheds.
Comment: One 110v leg to one shed and the other to the shed beside it. There was no neutral white wires except the one from the new uf cable. The neutral from the pole is bonded to the bus bars on either side. My white neutral to the sheds is the only one there. There in no ground rod for the box but the ground wire is going into the meter box. The connector between the meter and the breaker box is pvc  so I'm not sure if the neutral is electrically bonded to the power pole neutral to the meter case. As for the double wide there must be a ground/ground rod for the 200 amp interior breaker box.
Comment: Thoughts/comments. PS I dug down the 1/2 in. conduit, it appears it goes the 75 ft to the pump house.
Comment: Looks like I could be spending $80 + pulling new wire. Any good deals for an isolation transformer ?
Comment: @K S ... Wire is damn expensive but I think the wire will be less than the transformer when it's all said and done because you don't want a little control transformer for tiny loads, you want to be able to run a circular saw etc. out there.  Maybe start another question, put all the details in there, see what we come up with as your best buy, it would be another good question.


Error installing mail-stack-delivery

Question: So, I'm trying to set up an E-Mail server on an Ubuntu 10.04 VPS and when I try to use the command sudo apt-get install mail-stack-delivery (the package that I usually would use to get postfix and dovecot) it throws an error saying

E: Couldn't find package mail-stack-delivery

I was wondering if anybody has had this issue before or sees something I'm doing blatantly wrong? I set up a test server earlier today using the exact same command and the package installed just fine.
EDIT: This is a fresh server, I have not done anything to it beyond whatever stock configuration is done by ChicagoVPS
Answer: Okay, the problem was that the file '/etc/apt/sources.list' didn't contain the universe repository.  To fix this, just edit it with VIM and add the repository.

Error installing mail-stack-delivery