ASP.NET: how to load page faster

Question: We wrote Portal with ASP.NET. But it has many Javascripts and our pages loading slow.
In some page , page size is amount 1.5 mb!
What is the best way to reduce or compress page size to make it faster?
Thanks
Comment: Got any gridviews? Check your viewstate size as that could be the problem
Answer: Several things:

Minimize your javascript and CSS files. Google has a nice minimizer for JS.
Cache images, js files and css files. Info on how to do this from IIS, here.
Disable ViewState if you can or at least enable it only on the controls that need it.
Use compression on IIS
Use a content delivery network (CDN) to deliver javascript libraries such as jQuery, etc.
Optimize your images using Smush.it
Put javascript code at the bottom of the page so that the page starts rendering faster
If you use JSON for data interchange between the UI and the backend, make sure you compress it, too.
Use sprite me to create sprites for your image icons, backgrounds, etc.
Comment: @NuLLeR and do you have lots of js like that? Why not putting it on files so you can cache them?
Comment: thats not my writed js, thats Ajax and other components js
Comment: My main problem is with js generated by default.
Answer: There are so many different things you could do. Any easy one is to implement compression.
On my site, I have this in my web.config file:
<system.web>
    <httpModules>
        <add name="CompressionModule" type="Utility.HttpCompressionModule"/>
    </httpModules>
</system.web>

and this is the HttpCompressionModule:
public class HttpCompressionModule : IHttpModule
{
    ///
    /// Initializes a new instance of the <see cref="AjaxHttpCompressionModule"/> class.
    ///
    public HttpCompressionModule()
    {
    }

    #region IHttpModule Members

    ///
    /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
    ///
    void IHttpModule.Dispose()
    {

    }

    ///
    /// Initializes a module and prepares it to handle requests.
    ///
    /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
    void IHttpModule.Init(HttpApplication context)
    {
        context.BeginRequest += (new EventHandler(this.context_BeginRequest));
    }

    #endregion

    ///
    /// Handles the BeginRequest event of the context control.
    ///
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;
        string encodings = app.Request.Headers.Get("Accept-Encoding");
        Stream baseStream = app.Response.Filter;

        if (string.IsNullOrEmpty(encodings))
            return;

        string url = app.Request.RawUrl.ToLower();

        if (url.Contains(".js") || url.Contains(".css") || url.Contains("ajax.ashx"))
        {

            encodings = encodings.ToLower();

            if (encodings.Contains("gzip") || encodings == "*")
            {
                app.Response.Filter = new GZipStream(baseStream, CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "gzip");

            }
            else if (encodings.Contains("deflate"))
            {
                app.Response.Filter = new DeflateStream(baseStream, CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "deflate");
            }
        }
    }
}

Maybe you could try something similar.
Another thing you could do is minify your javascript and css. This means to do things like replace long variable names with short ones, and to remove comments and whitespace. You could include something that does this in your build scripts. My site uses python for its buildscripts, and they are very long and convoluted so I won't post them here. There is an older question on SO about writing a python script to minify css, which may give you a good place to start: Link.
Comment: What about runtime generated css and js file?
Answer:
Combine, minify and gzip your CSS into one file.
Combine and minify your JavaScripts files into one file.
Put your images, CSS and JS file on a CDN.
Depending on your IIS version, there are page compression options.

Also, don't forget about ViewState.  Turn it off when not needed, it can dramatically increase your page size.
Comment: My IIS version is 7.Where is the options?

ASP.NET: how to load page faster


Why all $3$-cycles are conjugate in $\mathfrak S_5$?

Question: Why all $3$-cycles are conjugate in $\mathfrak S_5$ ? Is it the case for all $n$ or only on $\mathfrak S_n$ ? I mean, in $\mathfrak S_n$ all $3$ cycle are conjugate or not ? (it doesn't look to be the case for $n=3$, but in the doubt, I prefer to ask).
Answer: In $\mathfrak S_n$, any cycles with the same length: $(i_1\,i_2\,\dots\, i_r)$ and $(j_1\,j_2\,\dots\, j_r)$ are conjugate.
Indeed, if $\sigma=(i_1\,j_1)(i_2\,j_2)\dots(i_r\,j_r)$, one has
$$\sigma(i_1\,i_2\,\dots\, i_r)\sigma^{-1}=\bigl(\sigma(i_1)\,\sigma(i_2)\,\dots\, \sigma(i_r)\bigr)=(j_1\,j_2\,\dots\, j_r).$$
As a consequence, two permutations are conjugate if and only if their decompositions as a product of disjoint cycles have the same cycles structure.
Comment: This is fine, as long as you note that there may be values of $k$ for which $i_{k} = j_{k}$, in which case, $(i_{k}j_{k})$ is not really a $2$-cycle, and should be omitted.
Comment: That was implicit,  of course.


How can I get a header that will work with IIS 6, 7 and Apache?

Question: I am trying to get a header that will work with Apache, IIS 6, and IIS 7.  I won't go into the reason for that here.  Let's just say that it's not as easy as I thought it would be :-)
Anyway, the problem has something to do with NPH.  In our code (originally written for IIS 6) we have
use CGI qw(:standard);

print "HTTP/1.0 200 OK\n";

print header;

at the top of every cgi script;  I read that this is how you tell IIS that you want NPH.
Apache uses the filename to see if the output is nph (nph- must be the beginning of the filename) so what I did (which works in both IIS 6 and Apache) is the following:
use CGI qw(:standard);
print header('text/html', '200 OK');

IIS 7, interestingly, seems to require NPH, so if I don't either do
use CGI qw(:standard -nph);

or
print "HTTP/1.0 200 OK\n";

print header('text/html', '200 OK'); #parameters are apparently optional

the browser tries to do something weird with the file, since it doesn't get the mimetype.
Also note: IIS 6 and 7 are ok without printing any header at all, but Apache doesn't like that.
Anyway, the best thing right now would be to make
use CGI qw(:standard);
print header('text/html', '200 OK');

somehow work in IIS 7.  Does anyone know how I can do that?  I don't know all the details for our server configuration, but if you tell me how to get any details you might need, I can do that.
Thanks either way!
Answer: I'd just create a subroutine that does the right thing depending on the server. You know what you have to do in each case, so just do that in that case.
The other option is to patch CGI.pm to set its $CGI::NPH variable correctly by looking at the server type. CGI.pm already has the basics there. Once you fix that, submit a patch.
Good luck :)
Answer: Brian (and others) have told me to write a subroutine that would Do The Right Thing.  Hope this helps someone else!
sub header {
    return (($ENV{PERLXS})?"HTTP/1.0 200 OK\r\n":"").CGI->header(@_);
}


Pandoc errors always give the wrong line number

Question: I've found Pandoc error messages to be completely uninformative, since the line number is always wrong. For example, right now I'm working on a file that is 223 lines long, and Pandoc says there's an error on "line 295" (specifically, it says l.295`. Line 295 obviously does not exist. Is there any way I can fix this? Am I just misinterpreting something?
Comment: the line number of the form `l.295` is from tex not pandoc so will relate to the tex file that pandoc generated (or a file include into that file) not your original source.
Answer: You could be calling some macro within your markdown file that uses a package. The arguments passed to that macro is processed and caused an error within the package code at line 295.
There's no true way to fix this in general, since the code is most likely valid within your document, but not within the package. Moreover, packages can call one another, making for a nested search of lines where mistakes can occur, with calls being valid until they are not. Another example of this is given in why is this error message line number wrong?
The proper solution here would be to understand what arguments are being passed to macros and compare that to what is allowed. Certain arguments may be fragile, for example.


Do certain epsilon transitions have to be a part of an epsilon nfa?

Question:
Hello,
Im new to learning epsilon nfas, and I have been wondering if we could leave certain epsilon transitions out, and if so would it still be a valid epsilon nfa?
For example regarding the image, couldnt I just delete the marked epsilon transition and the state that it leads to, thus only having the unmarked epsilon and c transition left, and the states that they lead to?
To me it seems that it is still equivalent to the epsilon nfa before deleting the marked transition, or does the marked epsilon transition have to exist?
Answer: Yes, it has to exist. If you remove the circled $\epsilon$-transition, your resulting NFA will be different since the second state will become unreachable. You would only be able to accept the empty string whereas your actual NFA accepts either the empty string, or strings that contain only $c$'s.
In essence, the resulting NFA stays valid, but will not recognise the same language as the complete one.
Comment: Hello, thank u for ur answer. But couldnt I just delete the circled epsilon transition and the second state, and take a c tranisiton from the initial state directly to the third state?
Comment: Yeah sure that will work too. But in that case, the $\epsilon$-transition to the accepting state would be useless. What you could do is a have a single starting state that is accepting, and do a loop on it that is used when recognising a $c$.
Comment: Hi, but wouldnt the ϵ-transition to the accepting state be necessary, so words like cc, cccc can be accepted, I mean without it there would only be words like c and ϵ possible.
Comment: @Seonix the goal of the loop is to avoid unnecessary $\epsilon$-transition. If you have a single accepting state with a loop for the character $c$ on it, then you will allow the empty string along with words with only $c$'s in it. In essence, your final NFA only has a single state which is accepting and a loop on it.


Fastest possible drivetrain?

Question: I am looking for the ideal gearing to achieve good speed on a gravel bike when commuting. 2x11? 1x12? 3x12? 10-52? 11-50? How many teeth on the chainring? I know I could go faster if I get a road bike with aggressive gearing but my current bike is my favorite to ride so I just would like to get the most out of it. Its the Marin Bear Valley SE steel framed mtb from '93 with 135mm rear dropouts and 26" wheels, so its been my long time bike that I am reviving. Thanks
Comment: Fastest possible? How about [204x11](https://www.bicycling.com/bikes-gear/a23305843/what-went-into-creating-this-record-breaking-bike/) or so?
Comment: How flat is your commute? The range of gears you need will depend on how much ascent and how much descent there is, and how steep those are
Comment: I think running Campagnolo Super Record EPS with nitric acid as chain lube would be the fastest way to empty your bank account ;)
Answer: The gearing does not make you faster. It only allows you to pedal at an optimal cadence. Sort of like selecting the right gear in your car. Shifting to the highest gear does not make your car automatically faster if it forces the motor to run on very low rpm.
There is no single optimal universal gearing. Not even for gravel. With 1x11(or 12) you get the simplicity. With 2x11(or 12) you get a wider gear range. 3x gearing was mostly abandoned, but both 1x and 2x is widely used on gravel bikes. Mountain bikes mostly use 1x because they do not use that high gearing for high speeds on tarmac.
The optimal gearing really depends on the slopes you will be riding on as steep hills require low gearing. The heavier your baggage, the lower gearing you need. On the other hand, if there is a lot of good tarmac with gentle downhills, you will be glad for relatively high gears.
Very high gears like 50x11 or even 53x11 are for sprints on good tarmac.
For 1x the chainring should be somewhere between what you would use for 2x but the actual choice (if you can choose at all) also depends on the available cassettes for your derailleur and the gear ratio you need to achieve.

To give you some actual advice for a gravel bike: Go for a subcompact. It may be GRX or it may be something else, but smaller than the road cranks (e.g., 46-30 or 48-32). You can easily find steep hills off-road, steeper than even very steep roads. And a wide cassette like 11-32 or 11-34.
If you go for a road compact crankset 50-34, you will definitely want even larger sprockets in the back. That may be a problem for 9-speed or lower so you will be better served with 11 speed or even higher.
For a mountain bike I am less experienced in the modern combinations, but something even lower. Personally, I would now choose 1x for a MTB, if I had another bike for roads or faster gravel roads.

Finally, remember that a road bike does not get you faster because of aggressive gearing, it makes you faster because of good aerodynamics, the low rolling resistance with the road tyres and low weight of the bike.
Comment: Yup, where I live only the cheapest MTBs in shops have 2×; anything you'd want to ride and that you can actually buy (or order...) is 1×, with insane cassettes (*e.g.* the M6100 12-speed 10-51). Road sections in between trails on MTBs are painful now :-/, which I guess helps the popularity of gravel bikes — I'm happy with my 2× GRX gravel bike.
Comment: Interesting that there is a trend towards 1x with MTBs -- seems like with the need for larger range you'd be happy about smaller intervals that come with more gears! You'll be on some flat sections as well, after all. Although [the community appears split](https://mtbweekly.com/should-you-get-a-1x-or-2x-drivetrain/).
Comment: @Peter-ReinstateMonica The 1x config works great for trails where you grind up a paved or gravel fire road, then zoom down the trail. Removing that FD does great things for cockpit cleanliness, tire clearance, and frame design.
Answer:
... I know I could go faster if I get a road bike with aggressive gearing ...

This may be a misconception. With many drop bar bikes on paved roads, you can pedal as fast as you have the legs for. On most road-oriented gravel bikes specced with 48/31 or larger front chainrings and 11-34 (or larger) cassettes, you usually won't run out of gears if you have the legs to keep up. Exceptions may occur in really fast groups, or if you are trying to pedal on a steep descent (but in this case, chances are decent that you'd be better off coasting and tucking, unless you're trying to keep up with a fast group in a race/competitive ride). Some people spec drop bar bikes with chainrings like 46/30 to get more climbing gears, and it's more likely you'll run out of gearing in that case.
(NB: the discussion above assumes 700c wheels with 40mm tires; the OP's question has 26" MTB wheels, so the OP would be running a bit easier gear with the chainrings and cassettes stated above. There's something to say about that later. Also, the stated gearing is for Shimano or Campagnolo double drivetrains, which tend to be based around 11t small cogs and up to 34t large cogs (or you may be able to use some MTB cassettes for slightly lower gearing). SRAM's AXS groups are designed for smaller chainrings and a 10t starting cog; equivalents to the gearing above should be about 43/30 chainring, 10-36 or larger cassette.
With 1x drivetrains, you will trade off larger jumps between gears and potentially gearing at the high end. Having too large jumps between gears when you are trying to hold a group ride's pace can be annoying. It may fatigue you faster than with a double crankset, although many riders can potentially get used to this. However, your question may imply that your use case is for what some might all an all-road bike, e.g. you're traveling on paved and unpaved roads, and you only rarely encounter very rough gravel. In this case, you would benefit from more road-like gearing.
Subjectively, I would probably want 48/32 chainrings and an 11-34 or slightly larger cassette on a gravel bike for this use case. I might also consider a 1x with a 42t front ring and a 10-42 or larger cassette. Because I mainly ride road bikes and I like small gear steps, I'd be reluctant to get a 1x drivetrain with fewer than 12 gears for a more road-oriented use case. On gravel, especially rougher gravel, smaller steps are less important.

...Its the Marin Bear Valley SE steel framed mtb from '93 with 135mm rear dropouts and 26" wheels...

Unfortunately, there may be limits to the largest gears you can fit to your bike. The manufacturer probably stated a maximum chainring size, if you can still find it. Also, MTBs in that era were designed for triple cranks, and the chainring clearance for a current generation MTB or gravel double crankset may be less. I believe you can't mount road cranks to MTBs in general.
There isn't necessarily a need to go buy a new bike. You could try fitting slick tires to your current bike and seeing how you feel with it and its current gearing.
Comment: Agreed. A lot of road bikes have bigger gears than most mortals can push. Also, a lot depends on the terrain where you live. My commuter has a 2x11 drivetrain, but for riding around town, I only need 4 or 5 gears.
Comment: The small cogs have higher transmission loss. For best performance the ratios should be chosen so that you don't spend most of time on top gear anyway.
Answer: To add what everyone else is saying, start by measuring your speed, cadence, and ideally, power as well.
Cadence sensors that measure how fast you spin the pedals are relatively cheap. The data will help you to select an optimal gear. A good cadence is somewhere between 85-95 rpm. If you run out of gears with this cadence frequently, it is a good indicator that your drivetrain needs an upgrade.
The power meter is a pricey upgrade, however it will tell you exactly how much power you are putting out allowing you to optimize pedaling, gearing, and everything else to maximize the power transfer.
That all said, the low-hanging fruits likely are cleaning your current drivetrain, getting tires suited for your riding style, adjusting pressure, and watching a couple of youtube videos on how to get faster on the bike.
Global Cycling Network has a few good videos on this.
Comment: Remember GCN is an advertising network primarily.  Their advice should be viewed as sales/markettng material, ie grounded in fact but potentially biased.
Comment: True, there is a risk that the OP will buy Pinarello Dogma F12 and shave his legs to become a faster commuter. Noone should watch GCN!
The advice on how to wash your bike, fix common issues and do some biking-specific workouts still stand.

Fastest possible drivetrain?


Identically Distributed Uniform Variables U and 1-U

Question: In this post: Exercise regarding Poisson processes and the uniform distribution

It is noted that U and 1-U are identically distributed for the r.v. U which is uniformly distributed on (0,1). If a definition for two random variables being identically distributed is:

Random variables X and Y are identically distributed if  $ F_{X}(x) = F_{Y}(x)  $ for all x.

Then let $ X = U$ and $ Y = 1 - U $.

So $ F_{U}(u) = F_{1-U}(u) = Pr[U \le u ] = Pr[1-U \le u] $

I don't understand the last equality (if it is even correct). Isn't it that $1-U$ will be the complement of $U$ so the CDFs will be inverted?
Answer: Let $U$ be uniformly distributed on $[0,1]$. Then, for $0\le u \le 1$, we have $F_U(u)=u$.
Now let $V=1-U$. We find $F_V(v)$ for $0\le v\le 1$. We have
$$F_V(v)=\Pr(1-U\le v)=\Pr(U\ge 1-v)=1-\Pr(U\le 1-v)=1-(1-v)=v.$$
To complete the calculation, we need to show that $F_V(v)=0$ if $v\lt 0$ and that $F_V(v)=1$ if $v\gt 1$. This is straightforward. For example, if $v\lt 0$, then $\Pr(V\le v)=\Pr(1-U\le v)=\Pr(U\ge 1-v)$. Since $1-v\gt 1$, this probability is $0$.
Comment: Very clear, thank you very much.
Comment: What if we have Cauchy distribution here (instead of uniform distribution)?
Comment: @Wen: There are many versions of the Cauchy.  If $W$ is standard Cauchy, then $W$ and $-W$ have the same distribution.
Comment: @AndréNicolas Thanks for the reply. I meant standard Cauchy and I think $W$ and $\frac{1}{W}$ have the same distribution. I tried use similar steps in your post but there is a problem since $W$ here can be either positive or negative. Like we can't say $P(\frac{1}{W} \leq t)=P(W \geq \frac{1}{t})$
Comment: @Wen:  One can use similar calculation. If $t$ is positive, we have $1/W\le t$ if $W$ is negative or if $W\ge 1/t$.


Do compilers have to be written for each model of CPU?

Question: Do you need to take account of the different processors and their instructions when writing a compiler? Have instructions been standardised? Or what tools and techniques are available to assist with this? E.g. Ignoring machine instructions that are specific to a certain processor model.
Comment: Maybe you have heard of [LLVM](http://llvm.org/)?
Comment: Java springs to mind, of course, but there are many other systems like that. E.G. [UCSD Pascal](http://en.wikipedia.org/wiki/UCSD_Pascal), which was pretty decent for its time (1978).
Comment: llvm, java, pascal, python, etc have some flavor of common bytecode which is itself an instruction set (they dont share each one has its own different one).  Then for each cpu type you need to translate/simulate the bytecode in native cpu instructions.  For each supported cpu you have to do this work.  for llvm there is a bytecode to native backend for each processor target, for java there is a jvm for each target (and often each operating system for each target), etc.  so no there really isnt a common instruction set, they have always been very similar but not interchangable.
Comment: @rwong no I haven't - I know very little about compilers. Thanks for pointing me in the right direction and I'll read through the site (and try working with clang vs gcc) but it would be really useful if you could explain what it is as an answer just in case someday that link breaks
Comment: What do you mean with "model of cpu"? Do you mean the difference between an ARM and an x86 processor, processors with very different architecture. Or do you mean different "models" of processors within same family? Like: an old pentium processor vs a celeron. The answer will be different.
Answer: No, instruction sets aren't "standardized" in a way that you could produce assembly that's fit for – or is simply mappable to – ARM, x86, PPC, MIPS, Itanium, Sparc, ... (and their variants).
Native code compilers are pretty complex beasts. Not all the work they do is processor-specific. All the lexing/parsing is language-dependent but not chip-related. Some optimization passes are also hardware-independent, but possibly not all – e.g. the right code size v.s. raw speed tradeoffs might depend on the target.
At some point, if you're producing native code, you'll need to know the details of the chip you're targeting. You need to be aware of their "quirks" (memory coherency properties for instance) and complete instruction sets to produce an instruction stream that is both correct and reasonably efficient.
Even if you restrict yourself to one instruction set (say x86_64), different brands of chips have different extensions that need to be considered. Different models of the same brand also have instruction set differences (new features added, sometimes old features removed). Sticking with the "lowest common denominator" could work, but you'll be missing out on a lot of stuff.
Does that mean the you do a complete rewrite of the compiler for every new instruction set or extension that hits the market? Of course not. Those are incremental changes, sometimes only to "machine description files" or whatever the compiler uses to model the target instruction set.
But introducing a new ISA altogether is not a trivial task and requires detailed knowledge of the target.
If you're setting out to build a compiler yourself, do have a look at LLVM. Chances are you use it for the "emitting native code" part at least, whatever language it is you're trying to compile.

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
Answer: A compiler is usually composed of many parts. Generating the actual code is just one part, and a small one.  So, to make a compiler for a new processor, you only need to make small changes to an old one.
Also, processors come in families. When (for example) Intel releases a new processor, it does everything the old processor does, and more.  This means that you can continue to use the existing compiler.  It will make programs that work on the new processor.  They will not use the new instructions that is offered, but they will still work.
For example, rather old compilers will only produce 32-bit programs.  The programs still run on new 64-bit computers, but they do not run well.
You probably want a new compiler to truely take advantage of the new chip, but it isn't necessary.


Preventing "pocket calls" - iOS 11

Question: I know someone who is always "pocket calling" people, this happens because they use their phone (an iPhone 6s running iOS 11.4) they just put it back in their pocket and dont lock it. They then put their hands in their pocket and start pressing buttons by accident.
Ive tried to get them to get into the habit of locking their phone before putting it in their pocket, but they haven't been able to.
Is there a setting i could set for them where their phone auto locks after say 10 seconds instead of the current minimum 30 seconds. Or auto-locks if the light sensor notices its dark.
Answer: No, that is unfortunately not possible. Adjusting the habit would seem the only effective solution.

Preventing "pocket calls" - iOS 11


flv to mp4 converter in Trusty

Question: Anybody recommend a GUI app (preferably in Ubuntu repos) to convert from .flv to .mp4 other than Transmageddon? Transmageddon now crashes in Trusty.
Comment: Take a look at [FFmpeg](https://www.ffmpeg.org/).
Comment: I used VLC a lot to transcode. I think it uses some of the LI tools from the other answers as underlying engines. But it provides a GUI for the task.
Answer: I don't think so there is GUI app is available in Ubuntu repository.
But you can simply convert your required formats in terminal. Try the following,
First you have to install libav-tools, Open terminal(Ctrl+Alt+T) and type the below command,
$ sudo apt-get install libav-tools

Now you can do your needs,  for FLV file to MP4
$ avconv -i input.flv -codec copy output.mp4

Comment: On 18.04 and above you can apt-get install `ffmpeg` and run the exact command substituting `ffmpeg` for `avconv`, so just do: `ffmpeg -i input.flv -codec copy output.mp4`
Answer: Have a look at winff
It is a graphical application that uses ffmpeg (like a lot of other programs) to convert videos and audio.
It is included in the official Ubuntu repositories, so you can simply install it with
sudo apt-get install winff
The official website includes a link to a wiki and a mailing list if you need specific support and documentation with this tool
Answer: Handbrake is in the official repositories since Trusty (14.04).
It is a small, efficient DVD ripper and video transcoder with a clean GTK GUI.
It can convert from a number of video formats, including flv, to either MPEG-4 or Matroska.
To install:
$ sudo apt-get install handbrake

Comment: And Handbrake is of course available for Windows and OSX / macOS as well.
Answer: Abstract from the blog Transcoding an audio or a video file - http://www.frasq.org/en/transcoding-an-audio-or-a-video-file (look for mp4flv in the page):
To convert a FLV already containing a video in H264 and an audio in AAC in MP4:
ffmpeg -i file.flv -acodec copy -vcodec copy -y video.mp4

MP4Box -raw 1 video.mp4 -out video.h264
MP4Box -raw 2 video.mp4 -out audio.aac

MP4Box -add video.h264 -add audio.aac file.mp4

rm -f video.mp4 video.h264 audio.aac

If the FLV contains an audio in MP3, extract the video while converting the MP3 in AAC:
ffmpeg -i file.flv -vcodec copy -y video.h264 -f adts -ar 44100 -f wav -ac 2 - | faac -b 128 -o audio.aac -

Assemble the MP4 with MP4Box:
MP4Box -add video.h264 -add audio.aac file.mp4

The blog explains how to install ffmpeg, faac, MP4Box, etc.
La version en français : Transcoder des fichiers audio et vidéo - http://www.frasq.org/fr/transcoder-des-fichiers-audio-et-video
Answer: avconv -i input.flv -c:a copy output.mp4

This has the effect of transcoding the video stream with the default codec and copying the audio stream.
avconv can be installed with
sudo apt-get install libav-tools

Comment: @DavidFoerster This answer has different flags for avconv.  The flags in the top answer don't work for me, whereas these flags do
Comment: Fair enough. Could you please explain what this command will do, e. g. which streams are copied and which are transcoded (and to which codec)?
Answer: It's not in the Ubuntu repository, but I liked Format Junkie for video conversions:
Add repository:
sudo add-apt-repository ppa:noobslab/apps

Update:
sudo apt-get update

Install it:
sudo apt-get install formatjunkie

Cheers.
Answer: I've written a GUI (named ConvertFLVToMP4)for CLI avconv program. Its .deb can be downloaded from:
https://app.box.com/s/vyr473g7q2nwkj6haq22
It requires the installation of gambas3 from:
https://launchpad.net/~gambas-team/+archive/ubuntu/gambas3
before installing the app from the .deb.

flv to mp4 converter in Trusty


ArcGIS Pro add attribute rule (Arcade expression)

Question: I am trying to create an Arcade expression in add attribute rule which will auto populate the attribute field (DPA_GROUP) in my points layer (as I create new point features) from the underlying polygon which contains a DPA_GROUP field.
Point feature: Suppression_Repair_Points
Polygon feature: DirectProtectionAreas21_2
Common attribute Field in poly and point: DPA_GROUP
My arcade expression is as follows.  Expression returns as valid however it will not let me save the attribute rule.
{// Calculation rule
// Suppression_repair_points, field DPA_AGENCY
// Triggers: Insert, Update

// optional:
// if DPA_AGENCY is already filled, just return its value (do nothing)
//if(!IsEmpty($feature.DPA_AGENCY)) {
// return $feature.DPA_AGENCY
//}

// load the polygon fc
var dpa_fc = FeatureSetByName($datastore, "DirectProtectionAreas21_2")

// intersect the feature with the polyons
var dpa_inter = Intersects(dpa_fc, $feature)

// if the feature doesn't intersect a dpa polygon, return null
if(dpa_inter == null || Count(dpa_inter) == 0) {
return null
}

// grab the first intersecting polygon and return its DPA_AGENCY value
return First(dpa_inter).DPA_AGENCY}

Answer: I was able to use your script and was able to get it to save by removing the last bracket } from your last line of code.
Your original last line:
return First(dpa_inter).DPA_AGENCY}

My revision of your last line:
return First(dpa_inter).DPA_AGENCY


Homebrewing in a cooking pot?

Question: Can you do the beer brewing in a big 20ltr cooking pot instead of the plastic drums that come with the brewing kit
Comment: You mean use a pot as a fermenter ?
Answer: Yep!  You can ferment in a cooking pot if you wish, but keep reading.  The best fermentation vessels (like what pro brewers use) are indeed steel.  Plastic buckets are more susceptible to getting a scratch in them and harboring bacteria and letting light in which can damage a beer over time.  Glass carboys are heavy but won't scratch but let light in (so you cover it with a towel), can be a little tough to clean.  Steel conical fermentation vessels are considered the best, but are expensive and hard to move around.
So why doesn't everybody just us a big pot to ferment instead glass carboys/brew buckets? Well, it is going to be hard to seal it up and have a one way air lock so the off gas from fermenting can be released.  Once the wort is in the vessel you can't let any air get in there, otherwise bacteria can wreck your beer and/or have oxidation problems.  Brew buckets (pretty cheap) have a sealable lid with a little hole in the top what you can put a $1 air lock.  Glass carboys have a very small opening at the top where you put the air lock on.  So, if I were you I'd hit up my local homebrew store and get a bucket, should only be a few bucks for that and an air lock.  Later you can always upgrade to a glass carboy :)
On a side note you can ferment in a keg, just a wicked hassle to clean.  Good luck!
Answer: If your pot has a snug fitting lid, then you'll probably be able to just use that.
I've been brewing in the usual plastic fermenters with airlocks fitted into a grommet in a hole in the lid. However after the first couple of uses, the seal on the lid breaks and it's rare to see any bubbles coming out of the airlock because the gas is escaping through the gap between the lid and the bucket. Recent I bought a bigger fermenter and it didn't have a hole pre-drilled in the top, so I just used as is, with the lid not quite pushed down all the way round, and don't think it had any ill effects.
The yeast will produce a very large volume of CO2 in the first couple of days, which will prevent air from getting in assuming it's not subject to a lot of turbulence, and if the opening to vent is small, and you're not moving the vessel around a lot, this should not be a problem. You may not want to leave your beer like this for a long time (e.g lagering) because eventually, however small the opening, the CO2 will probably mix with air.

Homebrewing in a cooking pot?


Resistor in high frequency

Question: Can we use a simple resistor of any kind, with resistance of 1.2 kΩ in high frequency like 4 GHz?
Comment: Welcome! Have you looked into ESL for simple resistors? What impedance will that ESL have at 4 GHz?
Answer: Typical shunt capacitance of a 0201 or 0402 resistor is in the range of 0.02pF or above.
If you work out the effect of that you'll find it's quite significant for a relatively high value resistor such as 1.2k ohms at 4GHz.
You can work out the effect of the inductance as well.
Inductance has more effect on small values of resistance, and capacitance has more effect on high values of resistance.
Answer: No, definitely not any kind.
At least a wirewound resistors would be a terrible idea at 4 GHz, as it's simply a coil of wire. Most likely many other types of resistors will be unsuitable too.
Answer: For GHz range resistors it is better to use smaller SMT film types. As with many other high frequency parts there are specially made resistor types that are recommended for the GHz ranges, such as these from Vishay and some others. Notice that in the actual datasheets the higher value resistances and larger body sizes show higher Z/R characteristics.

Resistor in high frequency


Explanation on Android's onResume and onPause method

Question: I am starting Android Programming!
Can anyone give me a simple explanation about Android's onResume onPause event?
When does it occur and when does the activity get destroyed and free memory? Thanks!
Comment: you can easily find it in books or or google
Answer: Your application will be destroyed upon the onDestroy() method; this is generally called the last activity in your application has left the stack.
onPause() and onResume() I believe are called when another activity is placed on top of the current activity in the stack - onPause() would be called once said activity loses focus, and onResume() would be called once it gains focus again.
The below image should explain things better. Good luck!
Answer: when lauch: onCreate onStart onResume
when press HOME: onPause onStop
when restart through menu(or lastest shortcut): onRestart onStart onResume
when press BACK: onPause onStop onDestory
when change orientation:onPause onStop onDestory then onCreate onStart onResume
watch the Activity life circle for more details
It's recommend to save status in onPause


How to show different pagelayouts for different recordtypes?

Question: I have 10 record types, I want to display different page layouts for different recordTypes. In standard we can do this but i am using vf page. How can i show diff layouts for diff pages..?
Comment: What about page layout assignment?
Comment: Is your VF page using the apex:detail to consume page layouts, or is it a full custom page ?
Comment: It is full custom page.
Answer: you can use "apex:detail" tag in vf page to show detail page. I think it must respect your page layout settings.
Answer: On VisualForce pages you cannot use the'standard' Page Layout Assignment settings, since that only works with standard page layouts. Also if you use a VisualForce page, there's no use adding or removing fields from the standard page layouts, since you define the page layout in your VisualForce page.
Therefore you need to add conditional rendering to make the one VisualForce page behave in different ways for each Record Type. So what you need to do is add a 'rendered=' attribute to your inputfields, where it checks the recordType and based on that renders the inputfield or not.
Let me know if this helps.


Impact Flash? In Vacuum?

Question: I was wondering, when you have a "hypervelocity impact" e.g. a meteor or Space Debris hitting a body in orbit, why do you get a "flash" of light and how large would the flash be for a given impactor at a given speed?
Comment: Lots of energy released in a short time has many ways to make light.
Comment: Yeah but, it there a specific - I don't want to say "formula" - but a means to predict the flash from a given collision?
Comment: Think of it like this. Suppose you said two vehicles collided and asked for a formula of how big the repair bill would be. You can't really write one. The statement of what happened is too vague. There are too many ways things could break, too many variables affecting price. The way you would handle it is to take your collision to a mechanic and let him figure it out.
Comment: I expected that, but what if you had a general sense of how large the impactor was and how fast it was moving? A friend told me that the Thebit crater on the moon, at least the impact that created it, would be visible from Earth on a clear night, personally I'm skeptical of that, but I have no idea whether it's true or not.
Answer: An impactor of mass $m$ moving at speed $v$ will have kinetic energy $E_0=(1/2)mv^2$, which will be significant for hypervelocity impacts. When it hits something inelastically this gets converted into kinetic energy of ejected fragments, work in deforming the target, and through this heating. This heating will make the hot material radiate blackbody radiation - this is what produces the flash.
The problem is that the exact distribution of energy. Some of it will go into a hot spot or ball of plasma shining, but the amount is going to depend on how the impact happens.
If we just assume a fraction $\eta$ ends up as heating a plasma ball of radius $r$ it will have temperature $T=\eta E_0/(4\pi/3) r^3 C$ where $C$ is the volumetric heat capacity of the plasma. If it loses energy as blackbody radiation from a hemisphere as $E'=-(2\pi r^2)\sigma (E/(4\pi/3)r^3 C)^4 = -(27/128\pi^3 C^4) \sigma E^4 / r^{10}$, starting out as $E=\eta E_0$. The energy and brightness declines as $E\propto t^{-1/3}$. Note the extreme dependence on $r$; this is yet another reason it is hard to give a reasonable answer, since in practice $r$ (and $C$) will change fast over time.
To sum up, it all depends on complex deformation, fluid and plasma dynamics during the impact.
Answer: Hypervelocity is defined as the velocity being above sound speed of the materials involved. That said, there is a phase during a hypervelocity impact where the projectile progresses faster than the materials involved can react. The contact line between the impactor and the target progresses so fast that the compressed material near the initial contact point is not able to escape. In other words, the material is trapped. It can only escape at a later stage, when the speed of the contact line between impactor and target decreases below sound speed of the materials involved.
This causes substantial heating to typically thousands of Kelvin. The energies involved are high enough to cause phase transitions of the materials up to ionization. What you see as flash is hot material being ejected (as soon as it is able to escape) and radiating like a black body as Andreas Sandberg wrote. Additional energy is being released by recombination of electrons and ions.
It's difficult to quantitatively estimate the brightness of the flash. However, some estimations can be done for the amount of ionized material and the duration of the impact. Of the impactor, a significant amount is ionized, should be roughly in the order of 10%. A similar amount (mass) of the target material also gets ionized. This gives you an estimation of the masses involved. Since the material was previously solid, the volume of the ionized material should be at least an order of magnitude above the volume of the initial impactor.
The impact process itself is characterized by the size and speed of the impactor. So the characteristic duration of the process is $d/v$ (with impactor diameter $d$ and velocity $v$). The typical impact velocity at 1 AU is around 20 km/s.
I don't know what impactor caused the Thebit crater (ca. 110 km in diameter). Given the size of the crater I would estimate it was probably large enough so that the amount of ionized material was visible from Earth, and the impact duration was also long enough to be seen. So yes, I would estimate the impact flash could have been seen from Earth, but only for a short time.

Impact Flash? In Vacuum?


how to derive the mean and variance of a Gaussian Random variable?

Question: How do we go about deriving the values of mean and variance of a Gaussian Random Variable $X$  given its probability density function ?
Comment: A couple of integrations.
Comment: Funny thing is that given the density of Gaussian you do not need even an integration to find the mean and variance!
Comment: @MichaelHardy, You are right, I missed the term "deriving" at the question.
Answer: UPDATE 21-03-2017
A much faster way is to differentiate both sides of
$$\int_{-\infty}^{\infty}\frac{1}{\sqrt{2\pi\sigma^2}}\exp\left\{-\frac{(x-\mu)^2}{2\sigma^2}\right\}dx=1$$
with respect to the two parameters $\mu$ and $\sigma^2$ (RHS will then be zero).

The Gaussian pdf is defined as
$$f_X(x) =\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{(x-\mu)^2}{2\sigma^2}\right\}$$
where $\mu$ and $\sigma$ are two parameters, with $\sigma >0$.
By definition of the mean we have
$$E(X) = \int_{-\infty}^{\infty}x\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{(x-\mu)^2}{2\sigma^2}\right\}dx$$
which using integral properties can be written as
$$E(X) = \int_{-\infty}^{\infty}(x+\mu)\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx$$
$$=\int_{-\infty}^{\infty}x\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx \;+\; \int_{-\infty}^{\infty}\mu\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx \qquad [1]$$
The first integral, call it $I_1$ equals zero, because we integrate an odd function (the product of an odd times an even function gives an odd function), over an interval centered at zero. Being pedantic,  we have using additivity
$$I_1 = \int_{-\infty}^0x\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx + \int_{0}^{\infty}x\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx$$
Swapping the integration limits in the first we have
$$I_1 = -\int_{0}^{-\infty}x\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx + \int_{0}^{\infty}x\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx$$
and using again integral properties we have
$$I_1 = \int_{0}^{\infty}(-x)\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{(-x)^2}{2\sigma^2}\right\}dx + \int_{0}^{\infty}x\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx$$
$$\Rightarrow I_1 = -\int_{0}^{\infty}x\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx + \int_{0}^{\infty}x\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx = 0\qquad [2]$$
So we have that
$$E(X) = \int_{-\infty}^{\infty}\mu\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx $$
Multiply by $\sigma \sqrt2$ to obtain
$$E(X) = \int_{-\infty}^{\infty}\mu\frac{1}{\sqrt{\pi}}e^{-x^2} dx = \mu\frac{2}{\sqrt{\pi}}\int_{0}^{\infty}e^{-x^2} dx$$
...the last term because the integrand is an even function.
Now $$\frac{2}{\sqrt{\pi}}\int_{0}^{\infty}e^{-x^2} dx = \lim_{t\rightarrow \infty}\frac{2}{\sqrt{\pi}}\int_{0}^{t}e^{-x^2} dx = \lim_{t\rightarrow \infty} \text{erf}(t) = 1$$
where "erf" is the error function. So we end up with
$$E(X) = \mu$$
i.e. that the parameter $\mu$ is the mean of the distribution.
VARIANCE
We have
$$\text {Var}(X) = \int_{-\infty}^{\infty}(x-\mu)^2\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{(x-\mu)^2}{2\sigma^2}\right\}dx$$
Applying the same tricks as before we have
$$\int_{-\infty}^{\infty}(x-\mu)^2\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{(x-\mu)^2}{2\sigma^2}\right\}dx = \int_{-\infty}^{\infty}x^2\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{x^2}{2\sigma^2}\right\}dx  $$
$$=\sigma \sqrt2\int_{-\infty}^{\infty}(\sigma \sqrt2x)^2\frac{1}{\sigma\sqrt{2\pi}}\exp\left\{-\frac{(\sigma \sqrt2x)^2}{2\sigma^2}\right\}dx = \sigma^2\frac{4}{\sqrt{\pi}}\int_{0}^{\infty}x^2e^{-x^2}dx$$
Define $t=x^2\Rightarrow x= \sqrt t$ and $dt = 2xdx = 2\sqrt tdx \Rightarrow dx = (2\sqrt t)^{-1}dt$. Substituting
$$V(X) = \sigma^2\frac{4}{\sqrt{\pi}}\int_{0}^{\infty}(\sqrt t)^2(2\sqrt t)^{-1}e^{-t}dt =
\sigma^2\frac{4}{\sqrt{\pi}}\frac 12 \int_{0}^{\infty}t^{\frac 32 -1}e^{-t}dt= \sigma^2\frac{4}{\sqrt{\pi}}\frac 12 \Gamma\left(\frac 32\right)$$
$$\Rightarrow V(X) = \sigma^2\frac{4}{\sqrt{\pi}}\frac 12 \frac {\sqrt \pi}{2} = \sigma^2$$
where $\Gamma()$ is the Gamma function. So the parameter $\sigma$ is the square-root of the variance, i.e. the standard deviation.
Comment: @Sandi Let
$$\int_a^b xf(x-\lambda) dx$$

Define  $v \equiv x-\lambda  \implies x = v+\lambda \implies dv = dx$, and also $x = a \implies v = a- \lambda , x=b \implies v=b - \lambda$. Make the substitution to get

$$\int_a^b xf(x-\lambda) dx = \int_{a-\lambda}^{b-\lambda} (v+\lambda)f(v)dv$$

Note that $\infty -\lambda = \infty$. Don't forget that under the integral the variable of integration is a dummy, it does not carry any specific properties. So it is customary (although admittedly confusing) to keep using the same symbol (i.e. keep $x$ as I did in my post, instead of using $v$).
Comment: @Char Define $w = x/\sigma \sqrt{2}$ and make the substitution.
Comment: Just for I1, I would rather simply say that the function is odd and you integrate it on an interval centered around 0
Comment: @MysteryGuy You are right, just that sometimes it is useful to show all the intermediate tedious steps. But I added this as an explanation of what I am showing.
Comment: Hey, I'm trying to wrap my head around your derivation but I don't understand the step before [1] where you say "Using integral properties, this can be written as...". Could you provide some information on that step? Thx
Comment: When you multiply by $\sigma \sqrt{2}$ how do you cancel out the denominator of $e$?
Comment: @AlecosPapadopoulos: Thanks, I added modified versions of your proofs [here](https://statproofbook.github.io/P/norm-mean) and [here](https://statproofbook.github.io/P/norm-var).
Comment: This answer deserves much more upvotes !
Answer: If $x\mapsto f(x)$ is the density function of a random variable $X$ with expected value $0$ and variance $1$, then $x\mapsto \frac1\sigma f\left(\frac{x-\mu}{\sigma}\right)$ is the density function of $\mu+\sigma X$, and thus of a random variable with expected value $\mu$ and variance $\sigma^2$.
That can be shown by thinking about the substitution $u = \dfrac{x-\mu}{\sigma}$ and $du=\dfrac{dx}\sigma$.
Therefore the problem reduces to this: How do we show that
$$
x\mapsto \frac{1}{\sqrt{2\pi}}\exp\left(\frac{-x^2}{2}\right)
$$
is the density of a distribution with expectation $0$ and variance $1$?
If you know that the expectation of a distribution with density $f$ is $\int_{-\infty}^\infty xf(x)\,dx$, then you know that you need to find
$$
\int_{-\infty}^\infty x \frac{1}{\sqrt{2\pi}}\exp\left(\frac{-x^2}{2}\right)\,dx.
$$
Since this is the integral of an odd function over an interval that is symmetric about $0$, it must be equal to $0$ unless the positive and negative parts both diverge to $\infty$.  The positive part is a constant times
$$
\int_0^\infty x \exp\left(\frac{-x^2}{2}\right)\,dx = \int_0^\infty \exp(u)\,du,
$$
where $u=-x^2/2$ so $du=x\,dx$.  Clearly this is finite, and the negative part can be treated the same way.
The variance is
\begin{align}
& \int_{-\infty}^\infty x^2 \frac{1}{\sqrt{2\pi}}\exp\left(\frac{-x^2}{2}\right)\,dx \\[8pt]
= {} & 2 \int_0^\infty x^2 \frac{1}{\sqrt{2\pi}}\exp\left(\frac{-x^2}{2}\right)\,dx \\[8pt]
= {} & 2\int_0^\infty x^2 \frac{1}{\sqrt{2\pi}}\exp\left(\frac{-x^2}{2}\right)\,dx \\[8pt]
= {} & 2\frac{1}{\sqrt{2\pi}} \int_0^\infty \Big(x\Big)\Big(x\exp\left(\frac{-x^2}{2}\right)\,dx\Big) \\[8pt]
= {} & \frac{2}{\sqrt{2\pi}} \int x\,dv \\[8pt]
= {} & \frac{2}{\sqrt{2\pi}} \left( xv-\int v\,dx \right) \\[8pt]
= {} & \frac{2}{\sqrt{2\pi}} \left(\left[-x\exp\left(\frac{-x^2}{2}\right)\right]_0^\infty
-\int_0^\infty -\exp\left(\frac{-x^2}{2}\right) \,dx \right) \\[8pt]
= {} & \frac{2}{\sqrt{2\pi}} \int_0^\infty \exp\left(\frac{-x^2}{2}\right) \,dx.
\end{align}
You know that this is equal to $1$ if you know how the normalizing constant in the density function was found.
Comment: Here's an amusing additional exercise.  Consider the function $(x\in\mathbb R^n)\mapsto$ $c \cdot\exp\left( \frac{-1}{2} (x-\mu)^\top A^{-1} (x-\mu) \right)$, where $c$ is chosen to make this a density function and $A$ is an $n\times n$ positive definite matrix.  Prove that $\mu\in\mathbb R^n$ is the expected value and the variance is $A=\mathbb E((X-\mu)(X-\mu)^\top) \in \mathbb R^{n\times n}$. ${}\qquad{}$
Comment: Thanks for the explanation, there's a sign confusion in the line "where $u=-x^2/2$ so $du=x\,dx$", should be $du=-x\,dx$
Answer: $$E(X)=E(x - \mu) + \mu$$
So we're done by showing that $E(x - \mu)=0$
$$E(x- \mu)= \int_{ -\infty }^\infty \frac{(x-\mu)}{\sqrt{2\pi}\sigma}\cdot e^{-\frac {(x-\mu)^2}{2\sigma^2}}\,dx$$
Using the subsitiution $z=\frac{x-\mu}{\sigma}$ we get
$$E(x- \mu)= \frac {\sigma}{\sqrt{2\pi}} \int_{ -\infty }^\infty z \cdot e^{z^2/2}\,dz$$
The function $f(z) = z\cdot e^{z^2/2}$ is obviously odd. Which makes
$$\lim_{a \to \infty }\int_{ -a }^a z \cdot e^{z^2/2}\,dz=0 $$
and thus we're left with
$$E(X)= \mu$$
Answer: Another way that might be easier to conceptualize:
As defined earlier, ()= $\int_{-∞}^∞ xf(x)dx$
To make this easier to type out, I will call $\mu$ 'm' and $\sigma$ 's'
f(x)= $\frac{1}{\sqrt{(2πs^2)}}$exp{ $\frac{-(x-m)^2}{(\sqrt{2s^2}}$}.
So, putting in the full function for f(x) will yield
E(x)= $\int_{-∞}^∞ x \frac{1}{\sqrt{(2πs^2)}}$exp{ $\frac{-(x-m)^2}{(\sqrt{2s^2} }dx$. Pretty gross to look at.
Looking at the exponent that e is being raised to, it seems like an ideal candidate for a u-subsitution.
I will set u= $\frac {x-m}{s\sqrt2}$. That means that du= $\frac{dx}{s\sqrt2}$, or  in other words dx= du•$s\sqrt2$.
Let's simplify the integral as much as possible using what we now know. Recalling the term $\frac{1}{\sqrt{(2πs^2)}}$, we shall rewrite it as $\frac{1}{s\sqrt{(2π)}}$.
E(x)= $\int_{-∞}^∞ x \frac{1}{s\sqrt{(2π)}}$ exp {$-u^2$}du•$s\sqrt2$.
The $s\sqrt2$'s from the first and last terms will cancel, leaving a constant of $\frac{1}{\sqrtπ}$. Let's put this in front of the integral for now to make this look a little better.
E(x)= $\frac{1}{\sqrtπ}$$\int_{-∞}^∞ x $ exp {$-u^2$}du.
The derivative of $\int_{-∞}^∞ $ exp {$-u^2$}du is in the form of a Gaussian integral. I'm not going to pretend that I can easily derive it (multivariable calc???) but it is widely known that the value of this integral is $\sqrtπ$.
We can use this knowledge to perform integration by parts to determine the value of the integral. I like to use u and v for this, but this u is not the same as the u from earlier. I hope this still makes sense.
$\int{udv}$=uv-$\int{ vdu}$
Set u=x. This means u'= 1dx. In terms of dx from earlier, u'= $s\sqrt2$ du. v'= $e^{(-u^2)}$du, and so by definition v= $\sqrtπ$.
uv= x$\sqrtπ$ and vdu=$\sqrtπ s\sqrt2 du$.
The overall integral is now equal to $\frac{1}{\sqrtπ}$ [x$\sqrtπ$- $\int_{-∞}^∞ \sqrtπ s\sqrt2 du$] evaluated from ∞ to -∞.
Antideriving $\int vdu$ produces $s\sqrt2π$u. Recall our earlier value of u, u= $\frac {x-m}{s\sqrt2}$.
E(x)= $\frac{1}{\sqrtπ}$ [x$\sqrtπ$- $s\sqrt2π$$\frac{x-m}{s\sqrt2}$] or $\frac{1}{\sqrtπ}$ [x$\sqrtπ$- $\sqrtπ$(x-m)] from ∞ to -∞.
Within the brackets, the terms being evaluated from ∞ to -∞ are:
x$\sqrtπ$-x$\sqrtπ$ + m$\sqrtπ$= m$\sqrtπ$.
E(x)= $\frac{1}{\sqrtπ}$ • m$\sqrtπ$ = m, or the mean, just like the definition of the expected value says.


Transplanting young oak trees into buckets

Question: I have about 100 oak trees. I took the 100 oak trees out the ground and planted them into 5 gallon buckets. The trees were very healthy when i took them out the ground and about 3ft tall.  I used a soil sand mix i bought at a local nursery to use to replant them in the 5 gallon bucket. After about a week the trees in the 5 gallon bucket looked as they were dying.  I used a root simulator about 2 weeks in. So its now been about 2 months and the trees look almost dead. I notice at the base a sprout is coming up. What should I do altogether?
Comment: Could you tell us where in the world you are? Were the trees in leaf when you lifted them? What sort of oak tree are they (especially whether they are evergreen or deciduous)? Normally, deciduous trees are lifted when dormant in the winter. It is very hard to keep them alive if you lift them in summer.
Comment: Plus, could you tell us your ultimate goal for putting the trees into 5 gallon buckets?  What sort of light conditions are you storing them in?
Comment: Welcome to the site! Would you please post a picture or two? One of the trees and one including that sprout at the base would help us a lot. Thanks!
Comment: Oaks also put down quite a taproot.  If you don't either dig deep or cut it cleanly you're likely to damage the roots quite badly.  Commercial growers selling bare-roted oaks cut the taproot below ground even for smaller tress than you have.What did you do?
Answer: Oaks are difficult to dig and replant ; I have had some luck with seedlings smaller than 12 inches. You could collect a bunch of acorns and put them in your buckets ( worms inside the acorns will destroy most of them - so bury a bunch.)


time elapsed with pause logic mysql TIMEDIFF() and PHP

Question: I got this query that takes my elapsed_time and that works fine but then I realized I'm getting the value of actual_elapsed wrong. actual_elapsed is the running time of my timer that I take by using TIMEDIFF(). log_time is a datetime, it is the datetime when the action (play, pause) was inserted/made. sequence is int, it tells me which happened first for each user. status, also int, tells me if the action made was play(1), pause(2) or stop(3).
Like I said my problem is getting the right value for actual_elapsed by using TIMEDIFF(now(), log_time). It would've been just fine if I didn't have a pause action.
Example DB Entry
<code>log_time               sequence     status

2012-09-27 15:31:02     1            1
2012-09-27 15:31:04     2            2               **2  +**
2012-09-27 15:40:08     3            1
2012-09-27 15:40:45     4            2               **39 +**
2012-09-27 15:40:47     5            1
2012-09-27 15:40:57     6            3               **10 =**
                                                     **49**
</code>
My query gives me 09 minutes and 57 seconds, when I should only be getting 49 seconds.
My SAMPLE Query.
<code> (" select sequence_num, elapsed_time, status, TIMEDIFF(now(), log_time) as actual_elapsed from tbl");
</code>
I'm trying to get the duration of the actual_elapsed. To do that I'd have to somehow take the total duration of the break time (pause) and then get the difference of elapsed_time and the break time. But I'm having trouble on that part also since the user can pause the timer multiple times.
This seemed simple enough when I designed my DB. How do I go about this without so much mess?
Answer: SELECT iStop-iStart FROM
(SELECT SUM(log_time) AS iStop FROM tbl WHERE status IN (2,3)) a JOIN
(SELECT SUM(log_time) AS iStart FROM tbl WHERE status=1) b;
Above query only work if pause or stop is last record


Is 1/2 inch hardboard more durable than mdf for a table top?

Question: I'm totally new to woodworking and as my first project I want to make a small table. I'm planning to paint it so the wood material will not be visible. And I want to bevel the edges using a router. I'm trying to keep it on a budget since it is just a practice. There are several board materials I can use with almost the same price. OSB, plywood, MDF, and hardboard. I read online that mdf is stronger than plywood and OSB. But I can't find any info on the strength of hardboard. So my question is, if I use two layers of 1/4 inch hardboard, would it make a stronger tabletop than 1/2 inch MDF? Thanks.
Comment: Please be clear, hardwood is not the same as hardboard - they are different so edit appropriately.
Comment: Imo, 1/2" thickness of any of your options seems like a poor choice for a table-top, unless it's a very small table - something like 12" square, unless you're planning to add a significant number of strengthening members underneath to support it.
Comment: Gee... how did I miss that?! I mean hardboard. Thanks for pointing out.
Answer: ANYTHING is better than MDF for your project as it is a terrible material for furniture, especially custom made furniture.  Also you can't use a router on MDF - well you can but it will not turn out well.
So you can probably find pine, oak and cedar at big box.   All stronger than mdf, all suitable.   If you are painting, pine is my go to as you can cover it without seeing the grains.  (there are many many other choices of solid wood planks if you want to order or go to lumber yard.  I just answered the question in a wood that is reasonably easy to find.)
Comment: particle-board is worse then MDF,  low density fibreboard too. OSB is stronger but has surface texture.
Comment: Agree completely that there are better choices for tops than mdf. (Especially 1/2", unless the underlying structure was extremely solid.) As a minor point, I strongly disagree about the router on mdf comment. In my experience, mdf is excellent as a material to take a profile -- no chipout, and clean to the point of being dangerously sharp edges.
Comment: Make sure your cutters are extremely sharp, because MDF dulls blades very quickly, and dulled cutters will overheat with friction.
Comment: @AloysiusDefenestrate - yes you can route MDF.  But After you route it the edges will be extremely weak and it will chip or have issues unless you put a rock solid coating on it.
Comment: Good point @DMoore about mdf edges being weak. (I hadn't really separated that from every part of mdf being weak. In some applications, that's not a problem; others, it's a big deal.)
Answer: I've used MDF to make a table top. (the legs, and upper frame were pine) the strength was fine (I jumped up and down on it etc)
I didn't paint it because I wasn't going to do anything wet on it, and I didn't want to have to wait for the paint to cure (which can take weeks after it has dried) if you don't wait things will stick to the paint if left on the table.
if you do paint it use a two part paint because they cure rapidly.
Plywood and OSB are both stronger than MDF, but they have more surface texture.
Gluing two sheets of hardboard together without using a table-sized press sounds like a tricky task.
Answer: Yes.  Hardboard will not expand as easily as Mdf which will also absorb liquid spills more easily.  Mdf is not as compressed as hardboard. However,  Mdf is good for many projects. It has clean edges which can be painted and look the same as the rest of the panel .  With raw wood or plywood the edges look terrible if you leave them exposed. It really depends on how your table is going to be used . I would worry about the hardboard curling downwards on the edges of it hangs over at all.  I've not seen hardboard used for a table top.  I really don't know which one would me best,  they both have good features,  good luck!!
Answer: Depending on the type of table, tempered hardboard OVER a sheet of MDF can make an excellent table or work surface.
Now, it will be very utilitarian and probably not eye catching as a dining table... but with a couple coats of polyurethane it makes an excellent bench top, outfeed, cutting, or assembly table...maybe even house furniture too, maybe.
However, I would still put some kind of boarder around it and not attempt to keep a chamfered edge on the HDF/MDF.   This could be anything from a 1×2 strip of maple, oak, etc.  OR half of a nice exotic species of deck board, or even a decent grade of SPF (assuming southern yellow pine or Douglas fir, which hold up better).  The softwood will get dinged up, but maybe you won't mind if you like to put your feet up on the coffee table!


Database exclusivity design

Question: I am trying to build a tournament scheduler application. In the database I have one specific problem. I have the following database tables:

Hour (which is connected to the days that the tournament will run)
Official (the person who will officiate the match)
Field (the field on which the match will be played)

The problem I'm having is that if I 'connect' (use the PK of the above tables as a FK in my 'Match' table directly) I can have one official who can officiate two games at the same time OR I can have multiple officials who officiate on one and the same pitch at the same time OR I can have multiple matches on the same time on the same pitch.
How would I go about fixing this from a design point of view? I realise I could just limit the options one can choose programmatically but I'm really interested in how you can fix this from a design point of view.
Answer: You have to enforce the rules programatically either:
a) within your application programming language
b) in the database using triggers/functions/procedures

Database exclusivity design


What is the difference between root and chroot?

Question: Is there any different between root and chroot in Linux? Can anyone please explain them?
Comment: Those aren't remotely the same thing.  Have you [looked](http://en.wikipedia.org/wiki/Root_directory) [them](http://en.wikipedia.org/wiki/Root_user) [up](http://en.wikipedia.org/wiki/Chroot)?
Answer: chroot is an operation, it changes the apparent root directory for the current running process and it's children.
root is an account that by default has access to all commands and files on a Linux (Unix based) system.
root directory is the highest directory in a hierarchy.
Answer: root directory refers to / which you can take as the root of the filesystem. It contains directories such as home, var.
chroot is the command to change the root directory i.e. changing the / for different user.
For eg.
$ chroot /media
will change the root directory(/) to /media
This is generally used in services like ftp to allow any user to access only a subtree of the whole directory tree. Thus it provide restrictions upto which a user can traverse.


preseed using cubic for install automation on ubuntu server 18.04

Question: I'm trying to create a ubuntu server installation media with pre-defined programs and settings.
for that I am using Cubic.
Through the chroot terminal I am able to install all the software that I need and this works very well.
I would also like to customize the installation screen with some pre-defined settings, such as the user and your password, among others, and would like this information not be requested during installation.
for this I created a preseed with the settings that I want to be automatic and added in the grub the boot parameters of FILE = / cdrom / preseed / mv.seed and auto = true however the settings continue to appear when I try to install.
as I am using boot by UEFI I know it is the file /boot/grub/grub.cfg that is submitted to select my installation and not /isolinux/txt.cfg
would anyone have the idea why the preseed is not loaded?
grub.cfg:
<code>if loadfont /boot/grub/font.pf2; then
set gfxmode = auto
insmod efi_gop
insmod efi_uga
insmod gfxterm
terminal_output gfxterm
fi

set menu_color_normal = white / blue
set menu_color_highlight = black / light-blue

set timeout = 5
menuentry "Install MultivisOs Server" {
set gfxpayload = keep
linux / casper / vmlinuz file = / cdrom / preseed / mv.seed boot = casper auto = true quiet splash ---
initrd / casper / initrd
}

menuentry "Check disc for defects" {
set gfxpayload = keep
linux / casper / vmlinuz boot = casper integrity-check quiet splash ---
initrd / casper / initrd
}
</code>
/preseed/mv.seed:
<code># select language
d-i debian-installer / language string en

# netcfg will choose an interface that has link if possible. This makes it
# skip displaying the list if there is more than one interface.
# d-i netcfg / choose_interface select auto

# If you want the preconfiguration file to work on both systems and
# without a dhcp server, uncomment these lines and the static network
# configuration below.
d-i netcfg / dhcp_failed note
d-i netcfg / dhcp_options select Configure network manually

# Static network configuration.
#
# IPv4 example
d-i netcfg / get_ipaddress string 192.168.1.237
d-i netcfg / get_netmask string 255.255.255.0
d-i netcfg / get_gateway string 192.168.1.1
d-i netcfg / get_nameservers string 192.168.1.1
d-i netcfg / confirm_static boolean true

# If you want to force hostname, regardless of what the DHCP
# server returns or what the reverse DNS entry for the IP is, uncomment
# and adjust the following line.
d-i netcfg / hostname string Multivis

# To create a normal user account.
d-i passwd / user-fullname string comtex
d-i passwd / username string comtex
# Normal user's password, either in clear text
d-i passwd / user-password password Comtex @ 457
d-i passwd / user-password-again password
# or encrypted using a crypt (3) hash.
# d-i passwd / user-password-crypted password [crypt (3) hash]
# Create the first user with the specified UID instead of the default.
# d-i passwd / user-uid string 1010
# The installer will warn you about weak passwords. If you are sure you know
# what you're doing and want to override it, uncomment this.
# d-i user-setup / allow-password-weak boolean true

# If the system has free space you can choose to only partition that space.
# This is only honored if partman-auto / method (below) is not set.
# Alternatives: custom, some_device, some_device_crypto, some_device_lvm.
# d-i partman-auto / init_automatically_partition select biggest_free

# Alternatively, you may specify a disk to partition. If the system has only
# one disk the installer will default to using that, but otherwise the device
# name must be given in traditional, non-devfs format (so eg / dev / sda
# and not e.g. / dev / discs / disc0 / disc).
# For example, to use the first SCSI / SATA hard disk:
# d-i partman-auto / disk string / dev / sda
# In addition, you'll need to specify the method to use.
# The presently available methods are:
# - regular: use the usual partition types for your architecture
# - lvm: use LVM to partition the disk
# - crypto: use LVM within an encrypted partition
d-i partman-auto / regular string method

# You can choose one of the three predefined partitioning recipes:
# - atomic: all files in one partition
# - home: separate / home partition
# - multi: separate / home, / var, and / tmp partitions
d-i partman-auto / choose_recipe select atomic

# If you just want to change the default filesystem from ext3 to something
# else, you can do that without providing a full recipe.
d-i partman / default_filesystem string ext4

# This makes partman automatically partition without confirmation, provided
# that you told it what to do using one of the above methods.
d-i partman-partitioning / confirm_write_new_label boolean true
d-i partman / choose_partition select finish
d-i partman / confirm boolean true
d-i partman / confirm_nooverwrite boolean true

# Avoid that last message about the install being complete.
d-i finish-install / reboot_in_
</code>
Comment: I solved the problem by using the version http://cdimage.ubuntu.com/ubuntu/releases/18.04/release/ubuntu-18.04.2-server-amd64.iso without live
Answer: I solved the issue by using the version http://cdimage.ubuntu.com/ubuntu/releases/18.04/release/ubuntu-18.04.2-server-amd64.iso without live


I'm looking for some background on the word "breant"

Question: This quote was written by Henry Kelsey in his journal on August 6, 1691: "this river breants away much to ye Southward & runneth through great part of the Country".  Kelsey was born around 1667 in or near London and worked for the Hudson's Bay Company in Western Canada.  I haven't been able to find any reference to "breant" online.  I no longer (unfortunately) have access to the complete OED.  My speculation is that it means "bend."
Comment: @sumelic I don't have a facsimile, but rather a printed copy of The Kelsey Papers published by F.A. Acland, Printer to the King's Most Excellent Majesty in 1929.  There is a note saying "possibly treants" but I can't find any (relevant) occurences of that either.
Comment: *Breant* doesn't feature in OED.
Answer: In the following book Three Hundred Prairie Years: Henry Kelsey's "Inland Country of Good Report" they suggests it might mean "branches" probably based on the following:

on 6 August Kelsey recorded an interesting topographical situation: "... this river breants away much to ye Southward & runneth through great part of the Cuntry & is fed by a lake wch feedeth another River wch runneth down to ye Southward of us."
This river must be the Etomami, and Kelsey must have been near the present-day town of Hudson Bay, Saskatchewan when he made his journal entry. Once known as the North Etomami, the Etomami gets its name from the fact that it rises in a lake at the "divide," near which another river rises in a lake in the same valley and flows south. Now known as the Lilian, it joins the Assiniboine near Sturgis, Saskatchewan. In the following days Kelsey recorded his progress up the valley of the Etomami.

Manitoba Historical Society
Comment: That's the passage I'm wondering about and your answer points out my difficulty.  If "breant" means "branches" then Kelsey turned off another river.  If it means "bends" then he stayed on the same river.  I'm reading "First in the West" by James W. Whillans who also attempted to reconstruct Kelsey's route from the journal (which I also have).  He comes to a different conclusion, placing Kelsey on the South Saskatchewan, further west,  I've no idea who is correct but I clearly can't take Whillans at face value.  Thanks for the citation.


axis 2 and bitnami

Question: I just installed Bitnami Namp Stack 5.4.13-0. I want to get axis 2 up and running with the apache server. Is this included in the Bitnami install? if not, what do I need to do to get axis 2 working with bitnami?
Answer: You need a Servlet container like Apache Tomcat. You cannot start axis2 ws on Apache Http Server. Bitnami also provides tomcat stack http://bitnami.com/stack/tomcat

axis 2 and bitnami


Why did Katniss leave Gale for Peeta?

Question: I understand that Katniss left Gale, but why did she let him go so abruptly?
Comment: Have you read Mockingjay?
Comment: I'm trying but there's really no good way to answer this without writing the entire answer as a spoiler. Suffice to say, it's entirely clear in the book what causes Katniss to break with Gale.
Comment: I don't recall an abrupt "leaving". Which part of which book are you thinking of?
Answer: TL;DR:

 Katniss believes Gale's bomb killed her sister and she will never be able to forgive him or forget that.

More details / evidence:
Near the climax of the story:

Double bombs go off, first killing targeted victims, then targeting rescue workers, Primrose among them.

Katniss remembers where she first learned of this tactic:

 "Im in Special Weaponry back in 13 with Gale and Beetee. Looking at the designs based on Gales traps. That played on human sympathies. The first bomb killed the victims. The second, the rescuerers. Remembering Gale's words.

Katniss believes that the rebels, not the Capitol was the cause:

Those double exploding bombs. It's not that the Capitol couldn't have the same weapon, it's just that I'm sure the rebels did. Gale and Beetee's brain child.

She thinks Gale was involved:

What could I say, how could I phrase it, without implying that it was his bomb that killed Prim?....I finally just say it "Was it your bomb?"

Katniss and Gale both know she will not be able to forgive Gale:

"Was it your bomb?"..."I don't know. Neither does Beetee. Does it matter? You'll always be thinking about it." He waits for me to deny it; I want to deny it, but it's true. Even now I can see the flash that ignites her, feel the heat of the flames. And I will never be able to separate that moment from Gale. My silence is my answer.....Forgive him. But since I can't, I'll just have to deal with the pain.

Katniss learns about herself that what she needs emotionally, only Peeta can provide. Gale's actions further demonstrate this:

 What I need to survive is not Gale's fire, kindled with rage and hatred. I have plenty of that fire myself. What I need is the dandelion in the spring. The promise that life can go on, no matter how bad our losses. That it can be good again. And only Peeta can give me that.
Comment: I hate all these spoiler tags ^

Why did Katniss leave Gale for Peeta?


How to seal an outside hole temporarily

Question: Our house had a leak in the kitchen sink drain and a hole around the drain was cut in the outside siding in order to repair it. I would like to temporarily seal the hole until proper repairs can be made to the siding. What materials should I get (foam sealer, plaster, waterproof paint, etc)? Below is a picture of the hole.
Comment: A can of expanding foam will do just fine for a temporary fix
Answer: As Levi mentioned in a comment, a can of spray foam (urethane) will do the job quickly and easily. It'll last months, at least. I'd use the minimal expansion "window and door" variety to avoid a mess. If you do a careful job that doesn't require shaving lumps later, it'll have a reasonably smooth skin that would probably take paint, too.
Note that urethane foam, caulk, and glue are crazy sticky. They will remain on skin for days and clothing forever. Prepare accordingly.
Answer: With Winter coming, it is a good idea to insulate around the pipe to prevent drafts, and possible freezing. Since I am assuming that this clean out protruding outside of the wall will eventually be removed, the methods for repair should be somewhat reversible so you can easily gain access to the pipe without having to cut back any more siding.
I would take a batt of fiberglass insulation, and cut off a few strips approx. 6" wide, and then peel off layers of the strips, dividing the thickness in half or thirds which makes it easy to work with. Then you can stuff the insulation pieces all around the pipe. You should add enough to fill the voids, and you can use a paint stirring stick, or a similar tool to pack it in. Be careful not to overly compress the insulation because it loses its thermal efficiency when packed too tightly.
After the insulation is put in, you can take some foam backer rod, and wrap it around the circumference of the pipe to fill the hole up to near the surface of the siding. The hole should also be waterproofed, so you should apply a layer of paintable exterior caulk over the backer rod to completely seal off the hole. You could then paint right over the caulk. If you are unsure what color paint to use, you can take a piece of the siding that was removed to a store that sells paint and have them match the color. Judging by the size of the hole, you would only need a small amount of paint. You can also paint right over the PVC pipe as well. I would also recommend using a good exterior primer since the paint would peel off easily if it wasn't primed. If you are looking for a more permanent solution, you can also use wood putty that is rated for outdoor use prior to painting to smooth it out even more.

How to seal an outside hole temporarily


UILabel touch and get the text where touched

Question: I've UILabel which has some text and 2 month names like "In the month of January and July, sun shine will be peak"
I sub classed UILabel and added touch event to it.
Now I want to get the word below the text where user touched and find out whether user touched January/July or not. Is it possible?
Answer: I think you'll find what you're looking for in the documentation for UITextInputProtocol.
For some more high level information, check out Apple's Text, Web and Editing Guide, specifically in the section titled "A Guided Tour of a UITextInput Implementation". It discusses how you can create indexed positions in text, and ask touches what text position they've landed nearest.
Apple's references a sample projected called SimpleTextInput, but I can't seem to find it. I'll keep looking.
Comment: This is quite useful but doesn't answer the question.  UILabel doesn't conform to the UITextInput protocol.
Comment: Do you have any sample or tutorial on how to use it?
Comment: hey, apple mentioned sample code -- trying to see if I can find it now.
Comment: Now (2011-01-19) it is available here: http://developer.apple.com/library/ios/#samplecode/SimpleTextInput/Introduction/Intro.html
Answer: I've implemented your question, just for fun on my blog.
Simply i've subclassed UILabel adding touchEnded, to recognize touch position and letter position.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [[touches allObjects] objectAtIndex:0];
  CGPoint pos    = [touch locationInView:self];

  int sizes[self.text.length];
  for ( int i=0; i<self.text.length; i++ )
  {
    char letter         = [self.text characterAtIndex:i];
    NSString *letterStr = [NSString stringWithFormat:@"%c", letter];

    CGSize letterSize   = [letterStr sizeWithFont:self.font];
    sizes[i]            = letterSize.width;
  }

  int sum = 0;
  for ( int i=0; i<self.text.length; i++)
  {
    sum += sizes[i];
    if ( sum >= pos.x )
    {
      [ _delegate didLetterFound:[ self.text characterAtIndex:i] ];
      return;
    }
  }
}

Hope this helps
cheers.
Answer: I handled this problem by putting transaparent UIViews on top of the UILabel which were wired to handle touch events. You can adjust the position and size of the hit zone labels by calculating the size of the relevant portions of text. This approach also has the advantage of being able to tweak the sizes of your hit zones to make them bigger and so easier to tap with fat fingers.
Answer: I had a similar problem as the original poster.  I wanted the user to be able to long-press in a UILabel which was displaying a comma-separated list of strings, and extract a sub-string corresponding to the touch location between the closest enclosing commas.
The problem is that UILabel doesn't implement the UITextInput protocol, otherwise the implementation would be straightforward.
I didn't like any of the suggested workarounds I found, so I decided to come up with my own solution.  After some thought and research, I realized that while UILabel doesn't support UITextInput, UITextView does.  I didn't want to replace all the UILabels in the UI with UITextViews, so I thought, "why not programmatically create a UITextView behind the scenes, with the exact same text rendering settings, and use its UITextInput methods to map the touch point to the desired sub-string?".
This proved to be the ideal solution from my point of view.
I attached a UILongPressGestureRecognizer to the UILabels and call the following function in the gesture handler:
-(NSString*)commaDelineatedTextAtTouchPosition:(UILongPressGestureRecognizer*)longPress
{
    UILabel *gestureRecipient = (UILabel*)longPress.view;
    UITextView *textRegionClone = [[UITextView alloc] initWithFrame:gestureRecipient.frame];

    // tweak the text view's content area to get the same rendering (placement and wrapping)
    textRegionClone.textContainerInset = UIEdgeInsetsMake(0.0, -5.0, 0.0, -5.0);
    // copy the label's text properties
    textRegionClone.text = gestureRecipient.text;
    textRegionClone.font = gestureRecipient.font;
    [textRegionClone setNeedsDisplay];
    CGPoint loc = [longPress locationInView:gestureRecipient];
    UITextPosition *charR = [textRegionClone closestPositionToPoint:loc];

    id<UITextInputTokenizer> tokenizer = textRegionClone.tokenizer;
    UITextRange *searchRange = [tokenizer rangeEnclosingPosition:charR withGranularity:UITextGranularityCharacter inDirection:UITextStorageDirectionBackward];
    NSString *commaEnclosedText = @"";

    if (searchRange != nil) {
        NSString *tapChar = [textRegionClone textInRange:searchRange];

        if ([tapChar isEqualToString:@","]) { // tapped right on a ","
            // move the end of the range to immediately before the ","
            searchRange = [textRegionClone textRangeFromPosition:searchRange.start toPosition:[textRegionClone positionFromPosition:searchRange.end offset:-1]];
        }

        UITextPosition *docStart = textRegionClone.beginningOfDocument;

        // search back to find the leading comma or the beginning of the text
        do {
            searchRange = [textRegionClone textRangeFromPosition:[textRegionClone positionFromPosition:searchRange.start offset:-1] toPosition:searchRange.end];
            commaEnclosedText = [textRegionClone textInRange:searchRange];
        }
        while (([searchRange.start isEqual:docStart] == NO) && ([commaEnclosedText characterAtIndex:0] != ','));

        // now search forward to the trailing comma or the end of the text
        UITextPosition *docEnd = textRegionClone.endOfDocument;

        while (([searchRange.end isEqual:docEnd] == NO) && ([commaEnclosedText characterAtIndex:commaEnclosedText.length - 1] != ',')) {
            searchRange = [textRegionClone textRangeFromPosition:searchRange.start toPosition:[textRegionClone positionFromPosition:searchRange.end offset:1]];
            commaEnclosedText = [textRegionClone textInRange:searchRange];
        }

        commaEnclosedText = [[commaEnclosedText stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    }

    return commaEnclosedText;
}

The only thing that's a little bit hacky about this technique is that you have to hand-tweak the rendering in the UITextView by adjusting the textContainerInset region.  Otherwise you don't get exactly the same wrapping and placement of the text in the UITextView as you do in the UILabel.  Otherwise, this is reasonably generic code that should work for anyone else.
Answer:
- (void)tapped:(UITapGestureRecognizer *)tap
{
    CGPoint location = [tap locationInView:_label];

    NSDictionary *attribute = @{NSFontAttributeName: _label.font};
    CGFloat width = 0;
    for (int i = 0; i substringWithRange:NSMakeRange(i, 1)];
        CGSize lettersize = [letterStr sizeWithAttributes:attribute];
        width += lettersize.width;
        if (width >= location.x ) {
            NSLog(@"str: %@", letterStr);
            break;
        }
    }
}


How to turn off image tiling in the game engine?

Question: I was wondering how to turn off image tiling for textures in the game engine. My UV map would make it tile right now (i.e. it's bigger than the map), but I can't figure out how to turn tiling off. I'm using the game engine with GLSL enabled.
Comment: Just curious as pertaining my answer below. Your question is worded funny. Texture tiling and (tiling textures) can be interpreted as two different things.. please clarify exactly what you mean.
Answer: In the UV Image Editor, bring up the properties toolshelf with N and under Game Properties, under the Clamp group, tick X and Y, you can now scale your map larger than your image without tiling your texture..
Comment: Ah, it was working before, it just wasn't updating. Changing the shading settings to singletexture then back to glsl updated it.
Comment: Is there something I need to do in the texture settings also? It's still tiling.
Comment: @CharlesL hmm.. this worked for me, you could try under texture settings, change *Image Mapping* to *Clip* and also make sure that your mesh is unwrapped properly (the default unwrap) and under *Mapping*, *Coordinates* is set to *UV*.


emoji issues or in other words you could say problems

Question: On a Samsung Galaxy Exhibit, is there any way to show emojis in text messages or in social media apps?
Answer: Diddent quite understand that. But I i
 think I can answer:
What's you android version only 4.0 and higher has emojis.  (go to settings, my device and look at android version) you can get emojis on Android version 4.0 and bellow but you have to be rooted.
If you want to type emojis, download SwiftKey+emoji (free)  from play-store
Answer: Emoji are only supported on Android Jelly Bean 4.1 and up. I see that the Exhibit did have an update to Jelly Bean, but not all carriers necessarily provided that. Check your Settings, About, to see if you've got it. If you do, and you're still not seeing emoji, you may wish to try an alternate SMS application, such as GoSMS, to see if they function in that one, as Samsung may not have provided support in their messaging app. If they're still not working even with that, then it's possible Samsung didn't include the emoji functionality in their modified version of Jelly Bean, in which case you're likely SOL without rooting or custom ROMs.


How can I add an Automator application to the Dock?

Question: I followed the directions in How to put a custom launcher in the Dock (Mavericks) but my case has a different twist. I have an Automator application which runs a shell script that (1) changes the stack size with ulimit and (2) runs an application. I would like to add this to the Dock. I can run it from the Launchpad and everything works correctly. It shows up in my Dock, but only as the application, not the Automator version. As a result, if I right click and enable 'Keep in Dock', then close and run again, the stack limit change of (1) is ignored. How do I put an icon in the Dock which runs the Automator application and not just the application?
Answer: Just drag and drop the app_name.app bundle created in Automator onto the Dock where you want it.
Comment: I need to clarify, when I said _"...drag and drop the Automator.app bundle onto the Dock..."_ I didn't mean the actual "/Applications/Automator.app" bundle but the .app bundle created in Automator.  I've edited the answer to reflect the comment.
Comment: hrm, i only see a `.action` file, not a `.app` file...  ?
Comment: But it still shows the active indicator under the original app, not the Automator version. This also means that I cannot run both the original app and the Automator version simultaneously.


How long does it take for the vagina to return to the way it was after giving birth?

Question: After giving birth vaginally, how long does it generally take for the vagina to return to the state it was before?
Comment: Please do not answer in comments, they are intended only to clarify/refine questions and answers.
Answer: During birth, the pelvic floor is stretched significantly, and the stretch is probable to never get back to the way it was exactly before.
The NHS states it takes a few days for the swelling and openness [...] to reduce [...] after your baby is born. An interview on the independent says that it should at most take 6 weeks for the vagina to get roughly back to before:

The vagina is an extremely forgiving part of the body, it can be very swollen and can look quite distressing to some people but after six weeks when the healing has happened it can go back to looking quite normal. If you have had a normal delivery it is common, for some degree, to have bruising on the vagina but this and the swelling should all go within six weeks.
 Source: The Independent: What Happens to the Vagina after Childbirth? Obstetrician reveals it all, 2017.

It is strongly recommended to visit a doctor 6 weeks after the birth (other sources say prior to 12 weeks) so they'll check the vagina, cervix, and uterus. If one feels pain, if the vagina is bleeding more than usual, one should schedule an appointment before.

For further reading, this is a good study regarding postpartum care:
Romano M, Cacciatore A, Giordano R, La Rosa B (April 2010). "Postpartum period: three distinct but continuous phases". Journal of Prenatal Medicine.


Should my party get xp twice, first for a negotiation, and then for killing the creature

Question: My party negotiated a truce with the Nothic in LMoP, then shortly afterwards the wizard found the sword hidden away and decided to try and steal it. The Nothic noticed and engaged in combat, at which point it was killed. In the guidebook, it mentions that the party gains 450 xp for killing or negotiating with the Nothic, but what if they did both?
Answer: XP are for overcoming an obstacle. No matter how you overcome it (sneak around, negotiation, killing), you get XP.

the wizard found the sword hidden away and decided to try and steal it. The Nothic noticed and engaged in combat,...

The obstacle is overcome only once in the description: because they failed in stealing the sword or negotiating for it, the obstacle had not been cleared yet, no XP were to be awarded as the Nothic was still an obstacle. Only the killing actually overcame the obstacle of the Nothic stopping them from getting the sword.
So the XP are only awarded for the killing.
Even if they had negotiated and then killed the Nothic, they would not have gotten the XP twice: that is an inclusive or, which means "(A) OR (B) OR (A&B)".
Comment: My interpretation was that the Nothic itself was the obstacle, finding the sword is just a bonus. XP is awarded for getting past the Nothic one way or another, not for finding the sword.  The answer is still correct, but I'd award the XP after the truce was negotiated since that already overcomes the obstacle. But PCs don't get double XP for pissing the Nothic off and overcoming the same obstacle again.
Comment: @NuclearHoagie good point, if the sword is actually a bonus and not the means they came for. In either way, they pretty much *Fed up* and had to overcome the same obstacle again.
Answer: Only once.
We can examine this with some basic logic. The last sentence of the encounter states:

Divide 450 XP equally among the characters if the party defeats the nothic or negotiates a truce with it.

We can parse this more precisely. Make the following definitions:

A: the party defeats the nothic
B: the party negotiates a truce with it
C: Award 450 XP

The statement quoted above is logically equivalent to:

If (A or B) then C.

From here it should be clear that even if A and B are true, we only award the XP one time.
Comment: Exactly right. There are some quests/encounters which offer bonus XP for accomplishing extra objectives, though those conditions are explicitly spelled out. But if not following a module that exactly, it can be another option for parties that do more than the listed objective(s) which the DM feels deserve something extra.
Comment: `Thomas Markov says` *I'll attack this with logic* `Thomas Markov rolls a 19` DM says *Hit*
Comment: @Yakk: Exclusive OR would mean "award XP zero times," which is clearly absurd.
Comment: The idea that "or" means "inclusive or" in English is wrong.  It means inclusive or exclusive depending on context, and you didn't analyze the context, but just blindly asserted it means inclusive or.
Comment: @Kevin: Yakk's point is that sometimes an English sentence is constructed to mean you must do X or Y, but most not or should not do both.  In *this* case, the meaning is clearly inclusive OR, based on context and the absurdity of awarding XP zero times if you do both.  Also, this answer isn't claiming that "or" in English always means inclusive-OR, so that's fine.


Apple TV conflict

Question: Hey I seem to not be able to have airport express and Apple TV connected and the same time. I have tried various different setup methods( Ethernet, wireless . Extend, standalone) but keep experiencing drop outs with the atv . I have also tried changing settings via airport utility with no success...  Seems ridiculous that I have purchase AirPort Extreme to make these too work together . If anyone has any suggestions on how I can fix my deliemma it would be greatly appreciated?   Taylor
Answer: I have an Airport Express and 2 ATV's, and they all get along fine, so it is possible.  First, can you take you AE out of the equation?  Does the ATV work fine (wired or wireless) without the AE?
If so, add the AE into the mix.  You haven't explained what you're using it for.  I can't think of a valid reason to have them in the same room, so I'm going to assume you either need to extend your wireless range to reach the ATV in a remote part of the house or you just want to hang some speakers on the AE's audio port.
In either case, this works for me.  Setup the AE in the Airport Utility's "Wireless" tab (in Mac OS X) to "Extend a wireless network", and make sure to send the AE's network name to the SAME as the main wireless network.  This works really well to extend you wireless network into remote parts of the house!
I guess you could be using the AE as the (only) wireless router, connected to an Ethernet-only router, and connecting the ATV to this (only) wireless network.  In that case you'd select "Create a wireless network", and join the ATB to this network.
If you could provide more info about your setup, it might help with more suggestions!
Comment: Pretty much nailed it on the head. Yes I use ae for some outdoor speakers. I am connecting the AE via Ethernet and then linking Atv off the AE . Just about to setup the unit by creating a wireless network? Is this the correct way to do it? Ta
Comment: I have previously tried to extend the network but have found the atv drops out also...
Comment: It's possible that the ATV is binding itself sometimes to the "main" wireless network, and not the AE's.  If that's far away, it might drop out sometimes, and the ATV would have to switch to the AE's (extended) wireless).  You can use Airport Utility to figure out which network it's connected to, I think.  But, running Ethernet to the AE and then a wi-fi between AE and ATV should work too.  So, yes, choose the "create wireless network" and bind ATV to it.  Only problem with this approach is that you'll have 2 wi-fi networks (diff. names) instead of 1.

Apple TV conflict


Confusion about the relationship between current, resistance and potential difference

Question: If the voltage of a component has dropped, what will happen to the resistance? My book says it will decrease but I don't understand the logic. How can current and resistance go down at the same time? Please explain in easy words. Question The dc power supply is set to 12 V and the ammeter reading is 1.5 A. The student changes the emf of the dc power supply to 6 V. The lamp dims and the ammeter reading changes. What happens to the resistance of the filament lamp?
Comment: More of a context is required to answer your question.  Is the book referring to ohmic or non-ohmic conductors?
Comment: All that's told is a variable dc power supply is being used and its voltage has been dropped from 12 V to 6 V, which has caused a decrease in current.
Comment: But the key says temp decreases and thus resistance decreases( the arrangement is in series)
Comment: A light bulb filament is a temperature dependent resistor.  When the temperature drops, the resistance drops.
Answer: The answer key is correct! The conductivity and resistivity of any metal is dependant on temperature. The resistivity at Celsius temperature $t$ is given by:
$$\rho=\rho_{20}[1+\alpha(t-20^\circ C)] \space ,$$
See the resistivities and temperature coefficients below:

Moreover, we have:
$$R=\frac{L}{A}\rho \space ,$$
where $L$ is the length of the wire, and $A$ is its cross-sectional area. When the voltage is dropped, the current reduces, then the LED filament becomes cooler and its resistance $R$ decreases.