<input type="text" lose focus after 1'st key press in chrome

Question: I'm having a textbox which is "observed" by a jquery for several actions, all code being a part of a "search-as-you-type" form.
Well, everything works flawlessly on Mozilla but in Chrome, the textbox is losing focus after 1'st hit, so I have to click again in textbox to continue search. Any clue ? My experience is leading me to a bug

    <input type="text" placeholder="Search.." name="searchb" >

Comment: Why are you doing `window.open()`?
Comment: does this happen only when `if ($(this).val().length > 2)` condition is true?
Comment: This code works for me in both Chrome and Firefox. If you comment out just this event listener, does the input still lose focus after 1 keystroke?
Comment: @Patrick Q, because I have to post the results somewhere, I see no other way to do that other than opening a page in a frame, I could try with div refresh, still can't figure out the best practice, nevertheless I might end up hitting the same problem.
Comment: @kingunits Do some research on ajax.  That's what you want here.
Comment: @newUserName02 if I strip out the event listener the input box behave as a regular text box. Forgot to mention that  browsers runs on macOS Mojave 10.14.4, even safari works fine with event listener. Must be something chromish here.
Comment: @ekcrisp -no , as I said it lose focus after 1'st keystroke, so the event listener is bothering it, not the alleged window.open()
Comment: I tried Chrome and on Linux and Windows, same stupid behavior.
Answer: Your search input is losing focus because the new opened window will gain focus.
Moreover, with your current code, a new window is opened each time an input with a length more than two characters is detected.
There are many solutions, here are two of them. I didn't put them into code snippets because they will not work correctly.

AJAX
You can get the generated HTML of main.php thanks to an AJAX request:
HTML

    <input type="text" placeholder="Search.." name="searchb" >

Javascript
$('input[name="searchb"]').on('input propertychange paste', function() {
    // Empties the result container.
    $('#searchb-result').empty();

    if ($(this).val().length > 2) {
        document.cookie = `psearch=${this.value};path=/`;

        // Gets the HTML by AJAX and adds it to the result container.
        $.get('main.php', `psearch=${this.value}`, (html) => {
            $('#searchb-result').html(html);
        });
    }
});

You can load your URL in a  tag.
HTML

    <input type="text" placeholder="Search.." name="searchb" >

Javascript
$('input[name="searchb"]').on('input propertychange paste', function() {
    // Hides the  by default.
    $('iframe').hide();

    if ($(this).val().length > 2) {
        document.cookie = `psearch=${this.value};path=/`;

        // Updates the  source when an input is detected.
        $('iframe')
            .attr('src', `main.php?psearch=${this.value}`)
            .show();
    }
});

Answer: I rewrote the entire section without jquery , clean and a with bit of 4'th grade approach, but it works. The lost focus was the problem.

      <input type="text" placeholder="Search.." name="searchb" id="search" autofocus="autofocus">


Cannot link library when compiling with gcc

Question: My directory structure is:
── bin
│   ├── mylib-osx.so.1.72
│   ├── mylib.so.1.72
├── my.c

I am trying to compile my.c and link mylib-osx.so.1.72 (I'm on a macOS), but to no avail:
ld: library not found for -l:PhotoDNAx64.so.1.72

I tried:

gcc -o my -lmylib-osx my.c
gcc -o my -lmylib-osx.so.1.72 my.c
gcc -o my -lmylib my.c
gcc -o my -L./bin -lmylib-osx my.c
gcc -o my -L./bin -l:"mylib-osx.so.1.72" my.c

What am I doing wrong and why cannot the library be found?
Comment: Read the documentation of MacOSX linker (probably of the `ld` program)
Answer:
What am I doing wrong and why cannot the library be found?

Read about Invoking GCC. You was wrong in not reading that (or any other documentation of gcc).
Order of program arguments to gcc matters a lot (and in practice several arguments are very useful, e.g. both -Wall and -g at least, and probably -v sometimes). You want something like
gcc -v -Wall -g my.c -lmylib-osx -o my

(also try variants of that), since gcc is running some ld or equivalent linker command, and if you want to pass some -Llib-directory use something like
gcc -v -Wall -g my.c  -L./bin -lmylib-osx -o my

and you also need to read the documentation of MacOSX linker (probably named  ld). You could also read Levine's Linkers and loaders book.
If you are not happy with gcc (but please use a recent version, so GCC 8 in 2019, not the crappy software sold by Apple named gcc) consider using Clang (a recent version too, e.g. Clang 8 in 2019). It has the same limitation regarding order of program arguments than gcc does (since order of program arguments even mattered for Unix or POSIX cc).
In general, read the documentation of a command before asking questions here about that command. A minima, man gcc on your Apple (or Linux) computer.
PS. The last time I have used some MacOSX was in 2004. My biased recommendation is to install and use Linux (which I use since 1993; I tried MacOSX around 2004 during less than a year, and have been disappointed both by the operating system, including its display server and GUI desktop environment, and by the Apple hardware).
Comment: I've tried various combinations and to no avail. What do I need to read about linkers in this case? Obviously the whole book is not an option; same with changing the OS.
Comment: You need to read the documentation of  `gcc`  and of `ld`, because `gcc` is invoking `ld`


Call to action: Add the "wsod" tag to the relevant questions

Question: I have noticed that we get questions related to 500 errors and the White Screen of Death.
I think we need a tag for both of these so people can locate questions easier, and that we should potentially make the tags synonyms (since a WSOD is nearly always a 500 error).
I went ahead and added wsod to a few questions, and stubbed out the tag wiki.
There really isn't a consensus on the SE sites about what tag to use for 500 errors.  SO uses "http-status-code-500", and SF uses "500-error".  Personally, I think the SO one is better, and it does autocomplete if you start typing "500".
I also think we should make an effort to edit questions to add wsod as appropriate.
Comment: I edited the question to make clear it is also a call for action to add [tag:wsod] to the questions requiring it.
Answer: If I have to choose a synonym, I would go with 500-error. http-status-code-500 is too long, and it is necessary on Stack Overflow to avoid it gets confused with a compiler error code.
Right now, I would set http-status-code-500 as synonym, just in case there are questions using that tag that are migrated to Drupal Answers, and wait to set any other synonym to see which tags users use instead of wsod.
Answer: I would go ahead and close any such questions, pointing the user to http://drupal.org/node/158043 so that they can enable error reporting
and find the actual error, allowing it to be debugged.
Comment: What would the reason to close those questions be? There isn't actually a closing reason that is "answer already exists in an external site." There are then questions for which that page doesn't have an answer.
Comment: @kiamlaluno I'm not sure I agree with you. If the question is so vague that it's like "Aaaaaaah! I did something and now I have WSOD! Troubleshoot plz!", learning how to enable error reporting should be a first step akin to doing a Google search (Is how to do that in the FAQ somewhere? It should be...). On the other hand, there's the possibility the WSOD is from something done while writing new Drupal code, at which point there's the possibility of the question becoming too localized. Granted, most people writing code know how to turn on error handling anyway...
Comment: That is not what this answer is saying. The answer is proposing a "let's close them, and point the users to http://drupal.org/node/158043 " blanket to cover all the [tag:wsod] questions. The "too localized" closing reason is for questions about code with a typo, not for questions where the problem is the OP not calling a function/method with the right parameters. Again, "too localized" is not a blanket for all the [tag:wsod] questions.


Should I fill 3/4-inch gaps along the wall before laying ceramic tile?

Question: We put down two layers of 3/8" plywood over planks (tar paper over planks).  Some of our expansion joints are up to 3/4" at the walls.  Should I fill them with something?
Comment: "Expansion joints", eh? *wink wink*
Comment: @isherwood The questioner was pretty clear on calling them "expansion joints"; the question is whether 3/4" of expansion joint is too much.
Comment: Yep, got all that. I gave a wink because subfloor sheathing is usually rigidly installed with no expansion joint needed or implemented. I suspect hasty cuts. Just a bit of ribbing. (If there's that much movement, tile is a bad idea anyway.)
Answer: I wouldn't bother for two reasons. One, it's unlikely that there will ever be any load placed on the tile close enough to the wall to cause breakage. Two, you may be installing baseboard trim or base shoe, which will cover most of that gap anyway.
If you have reasons to disagree, fill the gap with mortar as you tile. Consider laying a row of fiberglass tape along the wall to help prevent cracking.
Comment: I agree with filling with mortar unless a wide base board is used. Mortar would provide a good base for grout when you tile then no one but you will know there was a gap.
Answer: First - 3/8" times 2 is the very minimum for a bathroom getting ceramic tiles.  3/8" plywood has a lot of play and is flimsy.  Stacking it hardly makes a good substrate.  This is dependent on the joists below and load but for the most part I would not tile on that.  I would put a 1/2" of durarock over what you have.
Second - Your question...  No issues with that.  Your tile will cover that as you should generally try to tile about 1/4" from wall.  You may need to lay more thinset down.  I would also "test these areas while laying the tile as your tile should not tip if pressure is put on the side.  This isn't really about people walking and stuff like that but often in bathroom a pole or cabinet might push on the edges.   I don't foresee any issues at all but just in case the 3/4" is a little bigger, you just need to fill the void so that your tile lays flat.
Comment: Thanks, guys!  I hadn't thought about the trim.  And - of course it was shoddy cutting.
Comment: Ditto on the statement about 3/8" times 2 is too flimsy. Then there is the fact that very often these days plywood of nominal sizes is actually 1/32" thinner than the nominal dimension. In other words that plywood is likely to be 11/32". Add up that twice and you are a sixteenth thinner than 3/4".
Comment: @MichaelKaras - you are right.  Big boxes by me don't even sell 3/8" true.  Also unless they glued them there is no way staples or nails hold things this thin together well.
Comment: And on a side note, once I've put thinset into expansion joints, how are they still expansion joints?
Comment: We would normal shove a piece of plywood or even cardboard - shipping box - on the edges until everything sets and pull it out.  People cut corners around edges in bathrooms all the time.   Again I think the main issue you have is the plywood isn't thick enough for tile.  Bathrooms make things worse for this too as they get hot and cold more than the rest of the house and more moisture of course.  I would think yours will crack pretty bad within a couple years.
Comment: BTW - kitchen, not bathroom.
Comment: Maureen - how big is your kitchen and what is underneath it?  Also are you tiling first then cabinets or tiling around the cabinets?  And if tiling around the cabinets did you also leave 3/4" around them?
Comment: Kitchen is about 5x12.  The good kind, where you can reach everything by standing in the middle!  16" joist spacing, 1x6 diagonal planks, new tar paper.  Two layers of 3/8" plywood (laid in opposite directions).  And now Ditra.  It feels very solid.  Glass of water in the middle barely ripples at all.  Cabinets have not been removed.  Fridge and stove removed.  Yes, 3/4 inch approximately around cabinets.  Not consistently, just made several errors cutting.


Getting a valueset around a specific values

Question: say  I have the following value for x = 0.5
how can I get a array of values around it  something :
y = [-4,-2 -5 , 0.5 , 1 , 3, 6,8]

is there a python function that can do this , something :
radomaround(value, numberOfValuesBefor,numberofvaluesafter)

or randomaround(value,numberofValues)
Answer: It seems like a very special case to me, so I guess you need to write yourself one:
import random

def randaround(value, low, hi, num=5):
    lower = [random.uniform(low, value) for _ in range(num)]
    higher = [random.uniform(value, hi) for _ in range(num)]
    return lower + [value] + higher
x = 0.5
print(randaround(x, -2, 4))

Outputs:
[0.33673180511496215, -1.2546042323682594, -0.681556151907607, 0.3568323009807952, -0.24707450425223398, 0.5, 1.0553226028673577, 2.913246921202094, 1.5029344184335343, 2.420987178172286, 1.8538880531275126]

If you want them sorted, you can of course sort them before assembling the returned list.
Comment: Did you mix up global `x` and argument `value`?
Comment: @Engine it perfectly answers the question as you asked it... you did not actually ask for performance or stated that you have a working solution.
Comment: @Engine Then you should probably state, that you need an optimized version of it :-)
Comment: For performance use numpy: `lower = np.random.uniform(low, value, num)`
Comment: that wasn't the question. I've done it already , I need to do it 10M+ times that why I was asking
Comment: If you don't care about the distribution you can even create random values where the mean is your `value`. So you can create all the numbers in one numpy call: `np.random.uniform(value-x, value+x, num)`. Depending on your usecase you may need a sort afterwards, which may be even more expensive for large arrays.


How to access flag passed to npm script

Question: In my package json I created a seed script which uses mocha to initialize my environment and then run a bunch of database calls:
"seed": "./node_modules/.bin/mocha seed/seed-bootstrap.js seed/seed.js"

I want to be able to pass a flag to this which specifies a seed number that will determine how many of each object will be created so I could run
npm run script --seedNum=10

and have 10 of each object created.
I just can't figure out how to access the value of seedNum inside my script. I thought it would be in process.argv but it is not. process.argv seems to only contain the contents of my mocha.opts file.
Answer: Like so:
npm run seed -- --seedNum=4
as per
https://docs.npmjs.com/cli/run-script
Apparently the first -- is used by npm as a delimiter for the arguments intended for npm and the arguments thereafter intended for your script.
Comment: Works great! One question though:
Right now I'm grabbing that value via: process.argv[process.argv.length - 1]

Is there a better way to access this value?
Comment: The simple answer is "nope".  The  javascript fu answer is "don't index your  argv array dynamically (by doing the length - 1 calculation) unless you know you'll only ever need the last argument passed to your script; just start by indexing it at 2".  If you're doing  anything complicated, maybe   look into using a command line interface library. Or passing config via env variables (process.env).

How to access flag passed to npm script


How create thumbnail from doc docx in c#?

Question: Hello I would like to create thumbnail from doc docx, actually I use library Leadtools but I have this error :

ExceptionFilter Leadtools.RasterException: Invalid file format
     at Leadtools.Codecs.RasterCodecs.CheckExceptions(Int32 code)
     at Leadtools.Codecs.RasterCodecs.DoLoad(LoadParams loadParams)
     at Leadtools.Codecs.RasterCodecs.Load(String fileName, Int32 width, Int32 height, Int32 bitsPerPixel, RasterSizeFlags flags, CodecsLoadByteOrder order)

I would like to use an another lib for create the thumbnail.
Answer: LeadTools is an image processing library so will fail to process non-image formats like DOCX.
The ability to read the Windows created thumbnail for other files is covered in the existing article;
C#/ASP.NET - Get thumbnail from PDF/DOC files which references the Microsoft documentation here https://msdn.microsoft.com/en-us/library/aa289172.aspx that explains how to get the image. The Microsoft doc explains how to do this in SharePoint but the example is in VB.net so should be easy to follow.
Comment: Thx perfect PhillipH !
Comment: Your solution generate a standard thumbnail from windows not for example the first page of my word document..
Comment: A 1 minute google turns up this project which previews DOCX. http://blog.maartenballiauw.be/post/2008/01/11/Preview-Word-files-(docx)-in-HTML-using-ASPNET-OpenXML-and-LINQ-to-XML.aspx. The NTFS thumbnail is the only way of doing this without actually opening and parsing the word document.
Comment: All the MSDN links now gives error. Excellent job Microsoft for ruining the knowledge base that contributors have built up on multiple sites.
Answer: The phrase about LEADTOOLS being "an image processing library so will fail to process non-image formats like DOCX" is not entirely true. With some formats such as Word, Excel, PowerPoint and PDF files (among others), the toolkit can convert them to images but only if a Document Imaging toolkit is used. Entry-level Imaging Pro cannot load such formats. Also, if the appropriate format codec assembly is missing from the project, you will get "RasterException: Invalid file format".


Is it better to use std::memcpy() or std::copy() in terms to performance?

Question: Is it better to use std::memcpy() as shown below, or is it better to use std::copy() in terms to performance? Why?
char *bits = NULL;
...

bits = new (std::nothrow) char[((int *) copyMe->bits)[0]];
if (bits == NULL)
{
    cout << "ERROR Not enough memory.\n";
    exit(1);
}

memcpy (bits, copyMe->bits, ((int *) copyMe->bits)[0]);

Comment: Why aren't you using `std::vector`? Or since you say `bits`, `std::bitset`?
Comment: not sure why something that seems like such a mess with so little vital context provided was at +81, but hey. @user3728501 my guess is that the start of the buffer holds an `int` dictating its size, but that seems like a recipe for implementation-defined disaster, like so many other things here.
Comment: In fact, that `(int *)` cast is just pure undefined behaviour, not implementation-defined. Trying to do type-punning via a cast violates strict aliasing rules and hence is totally undefined by the Standard. (Also, in C++ although not C, you can't type-pun via a `union` either.) Pretty much the only exception is if you're converting **to** a variant of `char*`, but the allowance is not symmetrical.
Comment: Actually, could you please explain to me what `(int*) copyMe->bits[0]` does?
Comment: Note that `char` can be signed or unsigned, depending on the implementation. If the number of bytes can be >= 128, then use `unsigned char` for your byte arrays. (The `(int *)` cast would be safer as `(unsigned int *)`, too.)
Comment: I believe that the use of `std::nothrow` is incorrect here, is that correct? I thought `nothrow` was for overloading of the operator `new` only?
Comment: [SSE-copy, AVX-copy and std::copy performance](https://stackoverflow.com/q/18314523/995714)
Answer: I'm going to go against the general wisdom here that std::copy will have a slight, almost imperceptible performance loss. I just did a test and found that to be untrue: I did notice a performance difference. However, the winner was std::copy.
I wrote a C++ SHA-2 implementation. In my test, I hash 5 strings using all four SHA-2 versions (224, 256, 384, 512), and I loop 300 times. I measure times using Boost.timer. That 300 loop counter is enough to completely stabilize my results. I ran the test 5 times each, alternating between the memcpy version and the std::copy version. My code takes advantage of grabbing data in as large of chunks as possible (many other implementations operate with char / char *, whereas I operate with T / T * (where T is the largest type in the user's implementation that has correct overflow behavior), so fast memory access on the largest types I can is central to the performance of my algorithm. These are my results:
Time (in seconds) to complete run of SHA-2 tests
std::copy   memcpy  % increase
6.11        6.29    2.86%
6.09        6.28    3.03%
6.10        6.29    3.02%
6.08        6.27    3.03%
6.08        6.27    3.03%

Total average increase in speed of std::copy over memcpy: 2.99%
My compiler is gcc 4.6.3 on Fedora 16 x86_64. My optimization flags are -Ofast -march=native -funsafe-loop-optimizations.
Code for my SHA-2 implementations.
I decided to run a test on my MD5 implementation as well. The results were much less stable, so I decided to do 10 runs. However, after my first few attempts, I got results that varied wildly from one run to the next, so I'm guessing there was some sort of OS activity going on. I decided to start over.
Same compiler settings and flags. There is only one version of MD5, and it's faster than SHA-2, so I did 3000 loops on a similar set of 5 test strings.
These are my final 10 results:
Time (in seconds) to complete run of MD5 tests
std::copy   memcpy      % difference
5.52        5.56        +0.72%
5.56        5.55        -0.18%
5.57        5.53        -0.72%
5.57        5.52        -0.91%
5.56        5.57        +0.18%
5.56        5.57        +0.18%
5.56        5.53        -0.54%
5.53        5.57        +0.72%
5.59        5.57        -0.36%
5.57        5.56        -0.18%

Total average decrease in speed of std::copy over memcpy: 0.11%
Code for my MD5 implementation
These results suggest that there is some optimization that std::copy used in my SHA-2 tests that std::copy could not use in my MD5 tests. In the SHA-2 tests, both arrays were created in the same function that called std::copy / memcpy. In my MD5 tests, one of the arrays was passed in to the function as a function parameter.
I did a little bit more testing to see what I could do to make std::copy faster again. The answer turned out to be simple: turn on link time optimization. These are my results with LTO turned on (option -flto in gcc):
Time (in seconds) to complete run of MD5 tests with -flto
std::copy   memcpy      % difference
5.54        5.57        +0.54%
5.50        5.53        +0.54%
5.54        5.58        +0.72%
5.50        5.57        +1.26%
5.54        5.58        +0.72%
5.54        5.57        +0.54%
5.54        5.56        +0.36%
5.54        5.58        +0.72%
5.51        5.58        +1.25%
5.54        5.57        +0.54%

Total average increase in speed of std::copy over memcpy: 0.72%
In summary, there does not appear to be a performance penalty for using std::copy. In fact, there appears to be a performance gain.
Explanation of results
So why might std::copy give a performance boost?
First, I would not expect it to be slower for any implementation, as long as the optimization of inlining is turned on. All compilers inline aggressively; it is possibly the most important optimization because it enables so many other optimizations. std::copy can (and I suspect all real world implementations do) detect that the arguments are trivially copyable and that memory is laid out sequentially. This means that in the worst case, when memcpy is legal, std::copy should perform no worse. The trivial implementation of std::copy that defers to memcpy should meet your compiler's criteria of "always inline this when optimizing for speed or size".
However, std::copy also keeps more of its information. When you call std::copy, the function keeps the types intact. memcpy operates on void *, which discards almost all useful information. For instance, if I pass in an array of std::uint64_t, the compiler or library implementer may be able to take advantage of 64-bit alignment with std::copy, but it may be more difficult to do so with memcpy. Many implementations of algorithms like this work by first working on the unaligned portion at the start of the range, then the aligned portion, then the unaligned portion at the end. If it is all guaranteed to be aligned, then the code becomes simpler and faster, and easier for the branch predictor in your processor to get correct.
Premature optimization?
std::copy is in an interesting position. I expect it to never be slower than memcpy and sometimes faster with any modern optimizing compiler. Moreover, anything that you can memcpy, you can std::copy. memcpy does not allow any overlap in the buffers, whereas std::copy supports overlap in one direction (with std::copy_backward for the other direction of overlap). memcpy only works on pointers, std::copy works on any iterators (std::map, std::vector, std::deque, or my own custom type). In other words, you should just use std::copy when you need to copy chunks of data around.
Comment: I want to emphasize that this doesn't mean that `std::copy` is 2.99% or 0.72% or -0.11% faster than `memcpy`, these times are for the entire program to execute. However, I generally feel that benchmarks in real code are more useful than benchmarks in fake code. My entire program got that change in execution speed. The real effects of just the two copying schemes will have greater differences than shown here when taken in isolation, but this shows that they can have measurable differences in actual code.
Comment: Very informative analysis. Re _Total average decrease in speed of std::copy over memcpy: 0.11%_, whilst the number is correct, the results aren't statistically significant. A 95% confidence interval for the difference in means is (-0.013s, 0.025), which includes zero. As you pointed out there was variation from other sources and with your data, you'd probably say the performance is the same. For reference, the other two results are statistically significant -- the chances you'd see a difference in times this extreme by chance are about 1 in 100 million (first) and 1 in 20,000 (last).
Comment: @ST3: I would imagine that in the worst case, `std::copy` is a trivial inline function that just calls `memcpy` when it is legal. Basic inlining would eliminate any negative performance difference. I will update the post with a bit of an explanation of why std::copy might be faster.
Comment: I want to disagree with your findings, but results are results :/. However one question (I know it was a long time ago and you don't remember research, so just comment the way you think), you probably didn't look into assembly code;
Comment: In my opinion `memcpy` and `std::copy` has different implementations, so in some cases compiler optimizes surrounding code and actual memory copy code as a one integral piece of code. It other words _sometimes_ one is better then another and even in other words, deciding which to uses is premature or even stupid optimization, because in every situation you have to do new research and, what is more, programs are usually being developed, so after some minor changes advantage of function over other may be lost.
Comment: This runs contrary to what I have seen with GCC under templates. The code was slowed down by 5% using std::copy over memset, however this may be to do with the additional code generated by std::copy and how that is optimised in template use, rather than by the speed of the code itself.
Comment: Your architecture may have an instruction to copy 64, 128, or 256 bit objects at a time. With `memcpy`, to take advantage of this, there has to be a prologue and an epliogue that copy any extra trailing data byte by byte. With `std::copy`, because the types are maintained, there are certain alignment guarantees that are not lost. In theory, the optimizer could see this as part of its inlining as well, at which point there would be no difference.
Comment: Your answer largely depends on external code which could change and you didn't explain where to look in your code, so everyone interesting need to look through all your code.
Comment: `std::copy` might be fast, but is not guaranteed to be. No compiler specification explicitly documents that `std::copy` is always optimized when possible, even on the highest optimization level.
Comment: Is there any penalty by using `std:copy(std::begin(a), std::end(a), std::begin(b))` ?
Comment: Sorry about that but I didn't understand how std::copy can beat memcpy? Doesn't memcpy just copie words of data (according to HW support) without knowing what this represents? How can this be beaten?
Comment: TL;DR the main difference is that std::copy is fully defined in stdlib and can be inlined with all further optimizations applied, std::memcpy relies on libc and usually binaries link with it dynamically (for instance, due to architecture glibc heavily uses dlopen, so it loads itself dynamically anyway). Anytime you call memcpy you will get (pun intended) `call memcpy` in asm code. So yeah in heavy-loaded loops, operating on small enough chunks of data std::copy can be a winner with high percent of sure.
Comment: The repo links are dead now so we can't see how you called `std::copy`, like for what size or types, or whether it was likely to optimize away.  (Note that compilers like GCC define `memcpy` as `__builtin_memcpy`, and will inline it using XMM or YMM instructions for small fixed-size copies.)
Comment: And BTW, glibc memcpy does *not* have to copy a byte at a time on ISAs with efficient unaligned load/store.  Its actual strategy on x86 for copies from 15 to 31 bytes, for example, is to do two `movups xmm` loads that line up with the start and end of the region, then two stores.  So it works as memmove without any special overlap checking, too.  For size=16 they're fully overlapping, instead of doing it as two 8-byte halves which could lead to store-forwarding stalls later depending how it's reloaded.  And for size=31 they overlap by 1 byte.  (Size=32 uses YMM).
Comment: See https://code.woboq.org/userspace/glibc/sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S.html#19 for source in AT&T assembly syntax, with comments describing the strategy.  Of course that's only relevant when GCC does *not* inline the `memcpy` itself.  e.g. runtime-variable copy size, or large.  (Large copies benefit from letting runtime dispatching via dynamic linking maybe use wider vectors that weren't enabled at compile time, and allow unrolled loops too large to inline, and picking a strategy...)
Answer: All compilers I know will replace a simple std::copy with a memcpy when it is appropriate, or even better, vectorize the copy so that it would be even faster than a memcpy.
In any case: profile and find out yourself. Different compilers will do different things, and it's quite possible it won't do exactly what you ask.
See this presentation on compiler optimisations (pdf).
Here's what GCC does for a simple std::copy of a POD type.
#include <algorithm>

struct foo
{
  int x, y;
};

void bar(foo* a, foo* b, size_t n)
{
  std::copy(a, a + n, b);
}

Here's the disassembly (with only -O optimisation), showing the call to memmove:
bar(foo*, foo*, unsigned long):
    salq    $3, %rdx
    sarq    $3, %rdx
    testq   %rdx, %rdx
    je  .L5
    subq    $8, %rsp
    movq    %rsi, %rax
    salq    $3, %rdx
    movq    %rdi, %rsi
    movq    %rax, %rdi
    call    memmove
    addq    $8, %rsp
.L5:
    rep
    ret

If you change the function signature to
void bar(foo* __restrict a, foo* __restrict b, size_t n)

then the memmove becomes a memcpy for a slight performance improvement. Note that memcpy itself will be heavily vectorised.
Comment: @Konrad, you're correct.  But `memmove` shouldn't be faster - rather, it should be slighter slower because it has to take into account the possibility that the two data ranges overlap.  I think `std::copy` permits overlapping data, and so it has to call `memmove`.
Comment: How can I do profiling. What tool to use (in windows and linux)?
Comment: @Konrad: If memmove was always faster than memcpy, then memcpy would call memmove.  What std::copy actually might dispatch to (if anything) is implementation-defined, so it's not useful to mention specifics without mentioning implementation.
Comment: Although, a simple program to reproduce this behavior, compiled with -O3 under GCC shows me a `memcpy`. It leads me to believe GCC checks whether there's memory overlap.
Comment: @Konrad: standard `std::copy` allows overlap in one direction but not the other. The beginning of the output can't lie within the input range, but the beginning of the input is allowed to lie within the output range. This is a little odd, because the order of assignments is defined, and a call might be UB even though the effect of those assignments, in that order, is defined. But I suppose the restriction allows vectorization optimizations.
Comment: You don't even need to use a tool for this. Just get the time before the copy, the time after, and subtract to get the time it took :-)
Comment: IIRC `copy` actually dispatches to `memmove`, not `memcpy` (in the cases where it does that at all) but I think it's safe to surmise that it does that because it's even faster.
Comment: @user576670: A profiler!  (I couldn't resist.)  A profiler depends on implementation details of the compiler (in various ways), and is generally written to work with a specific compiler.  Gprof works with gcc.
Comment: @Fred: yes, of course. FYI, the implementation I had in mind is GCC (current versions but I don't know if there are specific versions for which this doesn't apply).
Comment: And FWIW, a quick test with overlapping reveals it optimises to `memmove`. I'll never use `memcpy` and `memmove` again :)
Comment: @PeterAlexander: Great presentation. Thanks for sharing!
Comment: @StackedCrooked: See my edit. It seems that GCC just calls `memmove`/`memcpy`. Obviously, those will be vectorised for the general case.
Comment: If you're looking to make sure your own containers take advantage of this make sure you don't define a iterator class. In libc++ `vector::iterator` is defined as `T*` and that enables the `memmove` optimization (when the iterators are pointers to a trivially copy assignable type)
Comment: gcc and clang don't seem to like to inline a `rep movsq` if the copy size isn't known at compile time.  And even then, they don't like to inline it for `std::copy`, only for `memcpy`.  Even then, gcc5.3 will only `memcpy`/`memmove` [with `-mtune=generic`](http://goo.gl/4Jq56X), not `-mtune=haswell`.  And it makes insane code with `-mtune=intel` (conditional branches on different bits of addresses, I guess checking alignment?  Try it on that godbolt link by editing the command line.)  `std::copy` checks for non-zero before tail-calling `memmove`, but the compiler see through it better, IDK.
Answer: Always use std::copy because memcpy is limited to only C-style POD structures, and the compiler will likely replace calls to std::copy with memcpy if the targets are in fact POD.
Plus, std::copy can be used with many iterator types, not just pointers. std::copy is more flexible for no performance loss and is the clear winner.
Comment: You're not copying the iterators, but rather the range defined by two iterators. For instance, `std::copy(container.begin(), container.end(), destination);` will copy the contents of `container` (everything between `begin` and `end`) into the buffer indicated by `destination`. `std::copy` doesn't require shenanigans like `&*container.begin()` or `&container.back() + 1`.
Comment: Why should you wanna copy around iterators?
Answer: In theory, memcpy might have a slight, imperceptible, infinitesimal, performance advantage, only because it doesn't have the same requirements as std::copy.  From the man page of memcpy:

To avoid overflows, the size of the
  arrays pointed by both the destination
  and source parameters, shall be at
  least num bytes, and should not
  overlap (for overlapping memory
  blocks, memmove is a safer approach).

In other words, memcpy can ignore the possibility of overlapping data.  (Passing overlapping arrays to memcpy is undefined behavior.)  So memcpy doesn't need to explicitly check for this condition, whereas std::copy can be used as long as the OutputIterator parameter is not in the source range.  Note this is not the same as saying that the source range and destination range can't overlap.
So since std::copy has somewhat different requirements, in theory it should be slightly (with an extreme emphasis on slightly) slower, since it probably will check for overlapping C-arrays, or else delegate the copying of C-arrays to memmove, which needs to perform the check.  But in practice, you (and most profilers) probably won't even detect any difference.
Of course, if you're not working with PODs, you can't use memcpy anyway.
Comment: This is true for `std::copy`. But `std::copy` can assume that its inputs are int-aligned. That will make a far bigger difference, because it affects every element. Overlap is a one-time check.
Comment: @MSalters, true, but most implementations of `memcpy` I've seen check for alignment and attempt to copy words rather than byte by byte.
Comment: There is an opposite argument that can be made: when going through `memcpy` interface it loses the alignment information. Hence, `memcpy` has to do alignment checks at run-time to handle unaligned beginnings and ends. Those checks may be cheap but they are not free. Whereas `std::copy` can avoid these checks and vectorize. Also, the compiler may prove that source and destination arrays do not overlap and again vectorize without the user having to choose between `memcpy` and `memmove`.
Comment: std::copy() can ignore overlapping memory, too. If you want to support overlapping memory, you have to write the logic yourself to call std::reverse_copy() in the appropriate situations.
Answer: My rule is simple. If you are using C++ prefer C++ libraries and not C :)
Comment: C++ was explicitly designed to allow using C libraries.  This was not an accident.  It is often better to use std::copy than memcpy in C++, but this has nothing to do with which one is C, and that kind of argument is usually the wrong approach.
Comment: @FredNurk Usually you want to avoid weak area of C where C++ provide a safer alternative.
Comment: @underscore_d `std::copy` is safer because it correctly copies the passed data in case they are not POD-types. `memcpy` will happily copy a `std::string` object to a new representation byte by byte.
Comment: @Phil1970 I'm not sure that C++ is much safer in this case. We still have to pass valid iterators that don't overrun, etc. I *guess* being able to use `std::end(c_arr)` instead of `c_arr + i_hope_this_is_the_right_number_of elements` is safer? and perhaps more importantly, clearer. And that'd be the point I emphasise in this specific case: `std::copy()` is more idiomatic, more maintainable if the types of the iterators changes later, leads to clearer syntax, etc.
Answer: Just a minor addition: The speed difference between memcpy() and std::copy() can vary quite a bit depending on if optimizations are enabled or disabled. With g++ 6.2.0 and without optimizations memcpy() clearly wins:
Benchmark             Time           CPU Iterations
---------------------------------------------------
bm_memcpy            17 ns         17 ns   40867738
bm_stdcopy           62 ns         62 ns   11176219
bm_stdcopy_n         72 ns         72 ns    9481749

When optimizations are enabled (-O3), everything looks pretty much the same again:
Benchmark             Time           CPU Iterations
---------------------------------------------------
bm_memcpy             3 ns          3 ns  274527617
bm_stdcopy            3 ns          3 ns  272663990
bm_stdcopy_n          3 ns          3 ns  274732792

The bigger the array the less noticeable the effect gets, but even at N=1000 memcpy() is about twice as fast when optimizations aren't enabled.
Source code (requires Google Benchmark):
#include <string.h>
#include <algorithm>
#include <vector>
#include <benchmark/benchmark.h>

constexpr int N = 10;

void bm_memcpy(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    memcpy(r.data(), a.data(), N * sizeof(int));
  }
}

void bm_stdcopy(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    std::copy(a.begin(), a.end(), r.begin());
  }
}

void bm_stdcopy_n(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    std::copy_n(a.begin(), N, r.begin());
  }
}

BENCHMARK(bm_memcpy);
BENCHMARK(bm_stdcopy);
BENCHMARK(bm_stdcopy_n);

BENCHMARK_MAIN()

/* EOF */

Comment: Measuring performance with optimizations disabled is... well... pretty much pointless... If you are interested in performance you won't compile without optimizations.
Comment: @bolov Not always. A relatively fast program under debug is in some cases important to have.
Comment: @bolov I used to think the same, but actually games running in debug mode can be heavily impacted by this. Well, maybe there are other solutions like inlining in debug mode... but that is a use case already.
Answer: If you really need maximum copying performance (which you might not), use neither of them.
There's a lot that can be done to optimize memory copying - even more if you're willing to use multiple threads/cores for it. See, for example:
What's missing/sub-optimal in this memcpy implementation?
both the question and some of the answers have suggested implementations or links to implementations.
Comment: pedant mode: with the usual caveat that "**use neither of them**" means _if you have proven that you have a highly specific situation/requirement for which neither Standard function provided by your implementation is fast enough_; otherwise, my usual concern is that people who haven't proven that get sidetracked on prematurely optimising copying code instead of the usually more useful parts of their program.
Answer: Profiling shows that statement: std::copy() is always as fast as memcpy() or faster is false.
My system:

HP-Compaq-dx7500-Microtower 3.13.0-24-generic #47-Ubuntu SMP Fri May 2
  23:30:00 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux.
gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2

The code (language: c++):
    const uint32_t arr_size = (1080 * 720 * 3); //HD image in rgb24
    const uint32_t iterations = 100000;
    uint8_t arr1[arr_size];
    uint8_t arr2[arr_size];
    std::vector<uint8_t> v;

    main(){
        {
            DPROFILE;
            memcpy(arr1, arr2, sizeof(arr1));
            printf("memcpy()\n");
        }

        v.reserve(sizeof(arr1));
        {
            DPROFILE;
            std::copy(arr1, arr1 + sizeof(arr1), v.begin());
            printf("std::copy()\n");
        }

        {
            time_t t = time(NULL);
            for(uint32_t i = 0; i < iterations; ++i)
                memcpy(arr1, arr2, sizeof(arr1));
            printf("memcpy()    elapsed %d s\n", time(NULL) - t);
        }

        {
            time_t t = time(NULL);
            for(uint32_t i = 0; i < iterations; ++i)
                std::copy(arr1, arr1 + sizeof(arr1), v.begin());
            printf("std::copy() elapsed %d s\n", time(NULL) - t);
        }
    }

g++ -O0 -o test_stdcopy test_stdcopy.cpp
memcpy()   profile: main:21: now:1422969084:04859 elapsed:2650 us
  std::copy()   profile: main:27: now:1422969084:04862 elapsed:2745 us
  memcpy()    elapsed 44 s   std::copy() elapsed 45 s
g++ -O3 -o test_stdcopy test_stdcopy.cpp
memcpy()   profile: main:21: now:1422969601:04939 elapsed:2385 us
  std::copy()   profile: main:28: now:1422969601:04941 elapsed:2690 us
  memcpy()    elapsed 27 s   std::copy() elapsed 43 s

Red Alert pointed out that the code uses memcpy from array to array and std::copy from array to vector. That coud be a reason for faster memcpy.
Since there  is
v.reserve(sizeof(arr1));
there shall be no difference in copy to vector or array.
The code is fixed to use array for both cases. memcpy still faster:
{
    time_t t = time(NULL);
    for(uint32_t i = 0; i < iterations; ++i)
        memcpy(arr1, arr2, sizeof(arr1));
    printf("memcpy()    elapsed %ld s\n", time(NULL) - t);
}

{
    time_t t = time(NULL);
    for(uint32_t i = 0; i < iterations; ++i)
        std::copy(arr1, arr1 + sizeof(arr1), arr2);
    printf("std::copy() elapsed %ld s\n", time(NULL) - t);
}

memcpy()    elapsed 44 s
std::copy() elapsed 48 s

Comment: So, switching `std::copy` from a vector to an array somehow made `memcpy` take nearly twice as long? This data is highly suspect. I compiled your code using gcc with -O3, and the generated assembly is the same for both loops. So any difference in time you observe on your machine is only incidental.
Comment: wrong, your profiling shows that copying into an array is faster than copying into a vector. Off topic.
Comment: I could be wrong, but in your corrected example, with memcpy,  aren't you copying arr2 into arr1, while with std::copy, you are copying arr1 into arr2?... What you could do is to make multiple, alternating experiments (once a batch of memcpy, once a batch of std::copy, then back again with memcopy, etc., multiple times.). Then, I would use clock() instead of time(), because who knows what your PC could be doing in addition to that program. Just my two cents, though... :-)


How to caulking a bathtub with various size edge between wall and tub

Question: Background:
Bathtub was re-caulked by maintenance few months ago. 2-3 months after the caulk that the guy put in fell out. Given few other things that maintenance did that were poor jobs I am not sure I trust them anymore for anything I can do myself.
My bathtub has very varying space between the edge of the tub and where the tile starts. It varies anywhere from 0.5" to 1.25". It looks like there are multiple layers since in one part it fell out, and I am not sure what is in there (grout?). How should I go about repairing it?
My initial guess is:

Let the bathroom dry overnight first
borrowing multimax tool to clean out the whole area between tiles and bathtub (1*)
utility knife to for basically same purpose. Also will use this to clean out the group between the tiles that are molded (pretty much entire thing)
silicone caulk (not 'water clean up' type) around bathtub (2*)
grout for between tiles

1* - How deep should i go with the multimax oscillating tool?
2* - Is it too wide to just caulk it? Should I use grout? Combination maybe? Anything else to add?

Any steps I missing that I should do?
Comment: I'd consider installing trim pieces in front of that gap,  caulked top and bottom, to achieve a consistant and minimal gap. These could be cut/ scribed to fit to obtain a nice straight line parallel with the existing grout lines.
Comment: @Iggy - there is absolutely nothing wrong with a large grout gap by the tub.  That is 1% of the issue.  The water isn't hitting that grout and climbing up the wall.
Comment: What is the problem you are trying to solve?
Comment: It looks like the tile is mounted on standard Sheetrock. Once that stuff is wet it really falls apart and nothing will stick to it. Make sure to document this problem so you are not held responsible.  Putting in new grout will never match in color and cutting a mess like this you might find tiles falling off right and left. At most I would bridge the gap making sure to touch the tub and tile so the calk has something to stick to.
Comment: @DMoore I want to get rid of the mold
Comment: @EdBeal Can you elaborate - what do you mean it falls apart? How do I fix it to prevent mold from accumulating? I am not worried too much about matching in color as long as mold is out
Comment: Once the sheetrock picks up water and the paper is gone (it looks like that) it really falls apart easily. I would be very careful.
The tile is probably holding the wall together and with much vibration tiles may just start falling off.
I would let the owner tackle this one, you can never match the old grout and there is a cracked tile in the photo.
@ keshlam has a good suggestion + from me. From what I see it looks like some old nightmare jobs I have tackled in the past.
Comment: My only issue is that I'm the owner :(. Bathroom renovation is definitely out of question for a while. I'm going to get one of those tile sets with thin strips of tile and put that around the widest areas. It will look funky but I'll just have to take that.
Comment: Well, there goes my answer. I was going to suggest the thin Accent Tiles for filling in the really large areas. You may consider a sheet of Mosaic Tiles with different sizes to possibly get you further. Run your bath exhaust fan extensively, at least 30-minutes after a shower...mold doesn't like that at all. But, you don't want silicone, it'll fail worse, you want an actual Tub & Tile caulk with mold resistance, which your guys didn't use. Completely fill & finger force it in & up to really fill the whole void, then press the tiles in flush to the above tiles.
Comment: Oh I know. But, having a big gap is going to separate regardless of what you fill it with, the surface needs to be bridged & reduced for whatever to do it's job for mold to be minimized if not eliminated. Stan's made it clear that he's not ripping out the bath any time soon. A waterproof long lasting patch is what's needed.
Comment: @Iggy why not silicone? This is what I got "Silicone II Premium Waterproof Kitchen and Bath Squeeze Tube" - 5-year mold-free product protection.
Comment: Silicone is organic & thereby more prone to mold. But hey, maybe they finally came up with a blend that has the best of both. Go ahead with what you have.
Answer: Just my thoughts on this:

I see mold everywhere, even by the faucet
the first thing you need to do is figure out what is behind the tile.  If it is drywall you are absolutely wasting your money doing anything.
if it is not drywall the first thing I would do is give it a heavy heavy spray of anti-mold cleaner.  Maybe 2-3 doses.  Scrub away mold using as little water as you can (this is a whole different question and will take a lot of man power).  I would then either not use the tub for a couple weeks or put up plastic sheets around tub.  You can get some painters plastic and tape it 5 feet high and your walls will stay dry.
if after a couple of weeks (at minimum) you still don't see the mold come back then we can talk about grout and caulk.  If the mold grows back either take down tile or keep plastic sheets up.  Either your mold is out of control or you have a leak behind wall.
if no mold you can grout and caulk.  Let's start with the gap by the tub.  This is too big to caulk for sure.  There is nothing wrong with grout here.  Do not install trim or other tiles at the bottom, that introduces more problems.  What happens if water gets in this first grout line?  It sits on tub, no big deal.  Your mold is coming from above.  After the mold is gone simply add more grout over this.
for the rest you are are going to have to scrape out caulk and grout, regrout, then caulk and quite possibly put some sort of waterproofing on the whole area.  The water could also be entering through the tiles themselves.  If they are old ceramic these will let water through.
my final thought is just I would never worry about doing anything more than hitting it with some mold spray.  All the other time/money is a waste.  You can buy cheap tile for $100 and another $50 for grout/thinset.  Add another $50 for backer and you are at $200.  Thinking about the time and money you are going to spend I would just wait and do it right.
Comment: Thank you for an awesome answer. So for my next steps - I found some information about mold http://blackmold.awardspace.com/kill-remove-mold.html - based on this I am planning to 1) Do Borax + Vinigar mixture, 2) soak paper towel in bleach and stick into that crack for a bit, 3) do Baking Soda one. After that I will wait a few weeks to see if it starts growing back, and if it does I will repeat the process maybe with bleach or something like that. At that point I will put a layer of grout (?) and then caulk between the grout line and the bottom tile - is that right?
Comment: Also is there a guide how to properly do grout & caulk? and would that be better than small tile + caulk?
Comment: The cleaners are just part of the process.  The area needs to be properly scraped.  I use a cleaner from Big Blue box that is in a pretty plain dark blue container (if anyone knows the name).    The key is to let it dry out for a while and see if it is still growing from behind.  Also it sounds like your bathroom has some humidity and airflow issues - this needs to be solved.  On the grout and caulk that will take too much room to respond and that is its own question.
Answer: Listen to @dmoore, but here's an alternative take.
You're not supposed to caulk gaps larger than a 1/4", but what choice do you have here?  This tile is a mess and should be torn out and re-done. I'm guessing that's not something you want to get into or pay for.
The recent caulk that just fell out was probably due to poor prep. They probably didn't even clean the surface first. Clean out all the old caulk. Clean off the mildew and soap scum. Let it dry over night then lay down some painter's tape at least  1/8" away from both sides of the gap. Slather on some 100% silicone caulk then use the back of a plastic spoon to smooth it down. Peel away the tape to leave nice a clean edge.
It's not really the right way, but it'll last for a few years and won't cost much.
Comment: Based on @dmoore's answer that's what I will basically do. Initially I will try my best to kill the mold thats there but the end result I will do what I can to just keep it away.
Answer: Responding to your Question & Comments. You're absolutely right. Get the old caulk out however & with whatever works...Multi-max, screwdriver, utility knife, etc. Fill the entire void & more (up behind the tile) with caulk & bridge that gap to drastically reduce the area that future mold can take up residence. This will also make cleaning a lot less involved. Only the surface matters concerning mold.
After this, there's no need to rip out the caulk in the future. You just scrub it clean & apply just enough new caulk to pretty it up for one, but more importantly to fill any gaps that may have appeared.
However, the main & even sole reason for mold is nothing but ventilation. Mold doesn't like wet & mold doesn't like dry, mold likes right in the middle. If the area can't dry quickly after it's been wet then you'll get mold. So, you must use your window or exhaust fan liberally. Open the window (top sash) or run the fan (either, not both) for 30-minutes after showering & don't stop either until you can actually feel that the sauna is mostly gone.
Comment: I think my only option is to try to get a dehumidifier. It's an old apartment so no exhaust fans, and the window points into a corner with 3 sides, so not much ventilation.
Comment: Aaaaaah, there's the problem. Dehumidifier's don't work too quick from what I've seen, but better than nothing. However, just a hole through the wall is all a fan needs. And, a window's a window & you could put a fan there. If it's a double hung windows you can put it up on top so you don't even notice it. Make the filler out of rigid insulation, put a dryer vent outside & a small fan inside, centered or to 1-side & foam rubber the sash gap...like a window AC unit setup, slightly reversed. Wiremold Cable Raceway for easy electrical tie-in to the light's operation.
Comment: I just added a picture of the mosaic tile that I got as well as a layout of the bathroom. The window is pretty small, I would have to measure how much the width is but I think it may be below 20". Aside from that I would need to make the wire go along the ceiling into the only available outlet. The other option I am thinking is just simply having a fan available that's strong and just turn it to max.
Comment: Yeah, if you're touchy about the maintenance guys wiring it right. Then, still just a little fan is good or whatever you already have to put on the floor & shoot out into the rest of your place. Leave the window out of the equation. If you have a kitchen exhaust that actually goes outside then you can use that to remove excess humidity if needed, but the rest of the place should suck it all up with no problem at all.
Answer: This isn't really an answer to your question -- that's been done well by others.
My concern is about how the tub got that way in the first place. Either it was a terrible tile job initially (possible, especially if the tub was set out of level, which is terrible all by itself), or there's moisture/rot in the subfloor that's caused the tub to sink. Can you get any access underneath to see how it looks? Does the floor feel bouncy at the edge of the tub? Do you have cracked tiles in proximity?
If it does turn out that you've got rot/moisture issues, you're looking at a pretty complete bathroom gut, so it takes the pressure off fixing any of this minor grout/caulk stuff and starts you budgeting for the big fix.
Comment: there's no access to below the tub, it's a solid piece down to the floor. It doesn't feel bouncy at all, feels very solid actually. There have been some leaks few years ago, so it might be that there's an issue in the subfloor.


How to remove dual boot and assign the space to ubuntu?

Question: I am using Ubuntu 20.04LTS along with Linux Mint 19.3. I want to remove Mint and keep only Ubuntu.
Also, I want to assign the space of Linux Mint to Ubuntu.
How should I go with it?
Answer: Boot from the Ubuntu Live USB.
After running swapoff in a terminal to disable the swap files, run GParted to delete the Linux Mint partition. With GParted, you define a change, then commit the change with the green checkmark, before moving on to make the next chantge.
Then you can resize the partition for Ubuntu.
You may need to edit GRUB later to remove the entry for Linux Mint.
Comment: Got an error stating **bad usage** on using swapoff


What are the prerequisites for reading Generatingfunctionology?

Question: Which specific topics (e.g. calc 1, calc 2, linear algebra, etc.) do I need to study in order to be able to read and understand Wilf's Generatingfunctionology?
Comment: very basic, essentially calculus
Comment: take a look at the book and you will see. As far I remember basically simple derivatives and integrals in the real line
Comment: How much calculus do I need to know? calc 1? calc 2? multivariable calc?
Answer: Chapter 5: Analytic and Asymptotic Methods
this will require complex analysis
Of course you can omit that chapter.  But in the Preface we find:

To omit those parts of the subject, however, is like listening to a stereo recording of, say, Beethoven's Ninth Symphony, using only the left audio channel.

Amazon will show you a sample of the book, including the Preface.  Why not read that to see whether to study the book.
Comment: the book *generatingfunctionology* is free of charge, you can download directly from the official web (already linked by the OP)


Check is variable has this text

Question: $check = array("this", "that", "to be", "not to be");

$yes = $no = array();

I'm trying to check, is each item of array $check contains text "be".
If it is, then add it to $yes, otherwise add to $no.
Seems I have to use a regular expression, can you please help me to compose it?
Comment: Does it have to be the word be or will words like `believe` be accepted?
Answer: foreach($array as $arr)
{
   if(in_array('be', explode(' ', $arr)) == true)
      $yes[] = $arr;
   else
      $no[] = $arr;
}

Comment: This will get text like `believe` as well as the word `be`. Just thought that that should be pointed out.
Answer: If you want to look for the complete word be and not be as a substring you can use:
$check = array("this", "that", "to be", "not to be");
$yes = $no = array();
foreach($check as $v) {
        if(preg_match('/\bbe\b/',$v)) {
                $yes[] = $v;
        } else {
                $no[] = $v;
        }
}

Check is variable has this text


Blinking moon of death since SSD upgrade on standby

Question: I own a Lenovo SL510 (4G RAM) and I just upgraded it with a Samsung 840 Evo 120G.
Previously I was using Ubuntu. Later on I switched to Linux Mint Nadia. At the very beginning (Ubuntu 10.10 I guess) I remember having problems getting my system into suspend to RAM. But this vanished with 11.04. I am using 14.04 now.
After the SSD upgrade the problem occurs again. I set my notebook to standby using either FN + F4, sudo pm-suspend or the menu. All three fail with the same symptom:

LCD goes black (even backlight)
Fan stays powered
Power-LED blinks ("blinking moon of death")

I cannot recover the Notebook from standby. I have to kill it by pressing 5s the Power button.
The weird thing is that it doesn't occur always. In about 20% of cases standby works as expected. Patterns observed:

immediately after power-up a standby never works
if after standby-ing the logon-screen appears, standby always works
but sometimes standby works also without a visible logon-screen
after standby worked first time during a session, it's not guaranteed but more likely to work again

So to all the Sherlock Holmes out there: I'm sure the problem can be fixed!
There are many forum entries for this very particular topic but none had a working solution. I already tried debugging and fixing this on various ways but I was not fortunate. What I want to do now is a focused search for the error.
I will start with posting log-messages and debugging steps in the comments.
Comment: Successful standby (notebook ran already some hours)

syslog: http://paste.ubuntu.com/7758148/

pm-suspend-log: http://paste.ubuntu.com/7758151/

running applications: chromium, terminal
Comment: Another Succesful standby (notebook ran already some hours) syslog: http://paste.ubuntu.com/7758172/ pm-suspend-log: http://paste.ubuntu.com/7758175/ running applications: chromium, terminal. I can go on and on in this session, standby always works, also with different running applications. Going to restart now.
Comment: unsuccesful standby (immediately after startup) syslog: http://paste.ubuntu.com/7758183/ pm-suspend-log: http://paste.ubuntu.com/7758186/ I recognized in the syslog that not all startup-processes were finished (e.g. cups)
Comment: succesful standby (3min after startup, locked the screen, wait until black, unlock screen, enter standby). syslog: http://paste.ubuntu.com/7758203/ pm-suspend-log: http://paste.ubuntu.com/7758205/
Comment: things that did not work: "quirk-mode standby" as suggested here: http://forums.debian.net/viewtopic.php?f=6&t=65818
Answer: It seems like this solution is working:

install uswsusp using: sudo apt-get install uswsusp
start standby using sudo s2ram -f -a 1

Solution found here (similar problem): https://unix.stackexchange.com/questions/94735/linuxmint15-suspend-to-ram-not-working
Disk encryption is also in use here, so perhaps this is the crucial thing.
I am interested in making this my default suspend application on all shortcuts (closing the lid, fn + f4 etc) - still searching on a solution for this one (the /etc/pm/config.d/anything-stuff doesn't work)
edit: even this solution won't work in any case :-( I am frustrated.


opengles view switching problem

Question: I´m trying to make simple game using OpenGLES.
I have two EAGLViews(menu and game view).
Each view has its own viewController. Initializing of the views is done by initWithNIBName method of the viewController.
And when I want to show the view, I simply use addSubview method of the main window.
The game view is initialized only once at the launch time. Menu view is initialized only if it´s needed. Problem is, that when I go from game view to menu and then back, and then I redraw the game view, something goes wrong. (I'm setting EAGLContext in drawView method before drawing, so the context may be right).
Don´t you know where is the problem?
Or if the whole switching is managed wrong, gimme and advice please.
Thanks for replies.
Answer: I guess you are having a trouble with texture not showing correctly?
I don't know the real thing behind OpenGL, but this is my hypothesis:
Each time you came back to the EAGLView, The EAGLContext of EAGLView is changed. (if you have been copying and pasting from the OpenGLES template) The textures can only be loaded after the context is in its correct state, or else you cannot load any texture. Now, by leaving the EAGLView, and coming back, you are instantiating a new EAGLContext from initWithCoder:(NSCoder*)coder :
<code>    context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];

    if (!context || ![EAGLContext setCurrentContext:context]) {
        [self release];
        return nil;
    }
</code>
So how can we preserve this context? I make it global. Simple as that. And when EAGLView is to be instantiated once again, have it check that whether the "global" EAGLContext is nil or not. If it's nil, just instantiate it, else do nothing. And never ever release or dealloc this global EAGLContext unless you want to quit your program.
This works for me, but again, my hypothesis above may not be correct. If anybody knows the real thing, please lecture me. I am also humbly in need of guidance. I want to truly know why this occurs and why do we have to do this as well.
And by the way, does this answer your question, Jenicek?
Comment: When you switch views and a different OpenGL view is onscreen, you need to call [EAGLContext setCurrentContext:context] with the correct OpenGL context. Otherwise, gl* calls still modify the contents of the other OpenGL view.

opengles view switching problem


How can I optimize searching and matching through multi-dimensional arrays?

Question: I'm trying to match up the elements in 2 different arrays. Array_A is a 3d map of A_Clouds, Array_B is a 3d map of B_Clouds. Each "cloud" is continuous, i.e. any isolated pixels would define a new cloud. The values of the pixels are a single, unique integer for each cloud. Non-cloud values are 0. Here's a 2D example:
[[0 0 0 0 0 0 0 0 0]
 [0 0 0 1 1 1 0 0 0]
 [0 0 1 1 1 1 1 1 0]
 [0 0 0 1 1 1 1 1 0]
 [0 0 0 0 0 1 0 0 0]
 [0 0 0 0 0 0 0 0 0]]

The output I need is simply the IDs (for both clouds) of each A_Cloud which is overlapping with a B_Cloud, and the number (locations not needed) of pixels which are overlapping between those clouds.
The problem is that these are both very large 3 dimensional arrays (~2000x2000x200, both are the same size). I'm basically doing a bunch of nested for loops, which is of course very slow. Is there a faster way that I could approach this problem? Thanks in advance.
This is what I have right now (simplified to 2d):
final_matches = []
for Acloud_id in ACloud_list:
    Acloud_locs = list(set([(i,j) for j, line in enumerate(Array_A) for i,pix in enumerate(line) if pix == Acloud_id]))

    matches = []
    for loc in Acloud_locs:
        Bcloud_pix = Array_B[loc[0]][loc[1]]
        if Bcloud_pix:
            matches.append(Bcloud_pix)

counter=collections.Counter(matches)
final_matches.append([Acloud_id, counter])

Thanks in advance!
Comment: The arrays are quite sparse (~80% zeros). There are a total of ~500 clouds in the 3d cubes, with a maximum of ~100 in a single 2d slice. Each cloud is ~20 pixels.
Comment: Are the arrays sparse? (i.e. high % of values will be zero) And are there a large number of clouds?
Answer: Some considerations here:
for Acloud_id in ACloud_list:
    Acloud_locs = list(set([(i,j) for j, line in enumerate(Array_A) for i,pix in enumerate(line) if pix == Acloud_id]))

If I've read that right, this needs to check every pixel in the array in order to generate the set, and it repeats that for every cloud in A. So if you have 500 clouds, you're checking every pixel 500 times. This is not going to scale well!
Might be more efficient to store the overlap counts in a dict, and just go through the arrays once:
overlaps=dict()
for i in possible_x_coords: # define these however you like
    for j in possible_y_coords:
        if (Array_A[i][j] and Array_B[i][j]):
            overlaps[(Array_A[i][j],Array_B[i][j])] = 1 + overlaps.get((Array_A[i][j],Array_B[i][j]),0)

(apologies for any errors, I'm on the road and can't test my code)
update: You've clarified that the arrays are about 80% sparse. If that figure was a lot higher, and if you had control over the format of your inputs, I'd suggest looking into sparse array formats - if your input only stores the non-zero values for A, this can save you the trouble of checking for zero values in A. However, for something that's only 80% sparse, I'm not sure how much efficiency this would add.
Comment: Thank you, this works great! Only change is that instead of overlaps.get(..., default=0) I need to use overlaps.get(..., 0).


How to find the URL of a site in IIS?

Question: How do I found the external URL for a site in IIS 8.5 that doesn't list a host name in the bindings?
I've got a client who has given me access to their web server and asked me to find the URL for their live and test sites. The live site is called Default Web Site in IIS.  It has two site bindings: one for port 80, one for 443; neither have a host name.  The one for 443 has a security certificate that mentions the URL www.companyname.com.  If I go to that URL from my computer, I can get to it fine.  The problem is the test site.  It's set up in IIS as a site called Test with two bindings: one for port 8080, one for port 8081.  The binding for port 8081 has the same security certificate as the live site.  Of course, that URL takes me to the live site.  How do I find the URL for the test site?
Here's what I'm seeing in IIS for the test site:
Comment: generally speaking - there are could be multiple names for the same IIS server and IIS server will not know any of them, read how DNS system works. in your case - I suggest you to look for external IP address and use it
Comment: Thanks.  How do I look for an external IP address?  If not in IIS, where do I find this?
Answer: Figured it out through trial and error.  The main site uses the URL in the security certificate: www.companyname.com.  The test site uses the same URL with the port specified in IIS: www.companyname.com:8081.
Answer: There's really no 'correct' answer, as the server in question could have multiple network interfaces, each with it's own IP address and thus URL.
Not only that, the IP address could go through a firewall that does a selective forward of the packets. In other words, the firewall "is" www.companyname.com, not your server. If a request for port 80 or 443 hits the firewall, it forwards it to server1. If a request for 8080 or 8081 hits the firewall, it forwards to server2.
Now, you mention:

Of course, that URL takes me to the live site

Does it? My guess is, you don't have a firewall, and the cert is used simply for an HTTPS certificate, but if you hit www.companyname.com:8081 you're hitting your test site; this is, of course, assuming the test site is identical to the live site. If it is not, then there's really no good way to find out the IP. You'll need to do some sleuthing at the hardware level on the server and determine what IP ranges it has, and how the hosting facility maps external IP's to those ranges. That's not hard, but it varies dramatically from site to site.
On a cloud provider, you look at the virtual networking. On a co-location site, you check with the local infrastructure. On a cable modem, you check the firewall, etc.

Thanks. How do I look for an external IP address?

The easiest way is to do a tracert from the server to say 18.104.22.168.
You then look for an IP address that isn't in the private IP ranges. (wherever this server his hosted almost certainly uses private IP ranges in it's internal system.)
The easiest way is https://www.whatismyip.com/
Most cloud centers now will do this to you:
<code>Tracing route to dns.google [126.96.36.199]
over a maximum of 30 hops:

  1     *        *        *     Request timed out.
  2     *        *        *     Request timed out.
  3     *        *        *     Request timed out.
  4     *        *        *     Request timed out.
  5     *        *        *     Request timed out.
  6     *        *        *     Request timed out.
  7     *        *        *     Request timed out.
  8     *        *        *     Request timed out.
</code>
More than twenty years ago, most Unix systems had a bug with malformed PING's, that could crash the O/S. Windows itself had a problem SENDING the malformed PING, but not receiving. (it's not a security problem if you're suicidal). As a result, everyone has this general idea that "pings are bad". (You can use PINGS to conduct a denial of service attack). So many, many hosts will block PING's. I'm not convinced with any modern O/S that's patched that there's a problem, and pings can be an important diagnostic tool.
If you're on such a cloud, 'whatismyip' is about the only way to go, and even that's not guaranteed.

How to find the URL of a site in IIS?


A problem on the optimal estimate $|f''(\xi)|\geq \frac{4}{(b-a)^2}|f(b)-f(a)|$.

Question: Let $f$ be twice differentiable on $[a,b]$. $f'(\frac{a+b}{2})=0$. Then it is easy to deduce $|f''(\xi)|\geq \frac{4}{(b-a)^2}|f(b)-f(a)|$ for some $\xi\in (a,b)$ by the Taylor expansion of $f$ at $\frac{a+b}{2}$, with points $a,b$; that is, $f(b)=f(\frac{a+b}{2})+f'(\frac{a+b}{2})(b-\frac{a+b}{2})+\frac{f''(\eta)}{2}(b-\frac{a+b}{2})^2$; $f(a)=f(\frac{a+b}{2})+f'(\frac{a+b}{2})(a-\frac{a+b}{2})+\frac{f''(\zeta)}{2}(a-\frac{a+b}{2})^2$. We substract to get the desired result by letting $\xi=\eta$ or $\zeta$ depending on the amplitide of $|f''(\eta)|,|f''(\zeta)|$.
Now my question is as follows:
(1) the constant $4$ is optimal in the sense that for any $M>4$, we can find $a,b$ and a function $f$ satisfying the assumptions that for all $x\in [a,b]$, $|f''(x)|< \frac{4}{(b-a)^2}|f(b)-f(a)|$.
(2) If $f$ is not constant, then $\exists\ \eta\in (a,b)$, such that $|f''(\eta)|>\frac{4}{(b-a)^2}|f(b)-f(a)|.$
On these two problems, I have no idea.
On (1), a possible idea is to consider $f(x)$ as a modifincaiton of $x$ over $[-\epsilon,\epsilon]$.
Answer: (1) You want $M$, not $4$, in the last formula of this part.  Try an $f$ for which $f''$ is constant.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/817976)
Comment: @Oussama Boussif: I would say that this does in fact provide an answer to the question.
Comment: @carmichael561 I flagged it because it is too short for answer and fits as a comment.


Unable to convert RPYC netref of a dataframe to local variable

Question: I am currently generating a dataframe on a RPYC server and what to send this to the client when requested. When I send it across the server it is sent as a netref object. I want to be able to store this as a local variable on the client-side and not as a reference. It seems that RPYC has a built-in pickle protocol which I have tried to use with little success. The end goal is to be able to plot this dataframe on the client-side. The data acquisition for the dataframe is hardware-specific and for the sake of the current question have just loaded the sample data in as a csv.
Here is the server code
import rpyc
from rpyc.utils.server import ThreadedServer # or ForkingServer
import pandas as pd

class MyService(rpyc.Service):

    def exposed_Dataframe_send(self):

        resultsDF = pd.read_csv("Shared/PMBUS_Logging.csv")
        print(type(resultsDF))
        return resultsDF

if __name__ == "__main__":
    server = ThreadedServer(MyService, port=18861, protocol_config={
    'allow_public_attrs': True, "allow_pickle":True
})
server.start()

The client code
import rpyc
c = rpyc.connect("localhost", 18861, config={"allow_public_attrs": True, "allow_pickle":True})

x = c.root.Dataframe_send()
print(x)
print(type(x))

x.plot(figsize=[20,15])

Any help is appreciated
Answer: On the client you get not the real object but a netref of the dataframe which works almost exactly as the real dataframe.
I tried it and on the client I can do:
obj = x.iloc[10]

Which gives me the proper result. If you want to re-create native dataframe on the client, you can get the data and convert:
import pandas as pd
...
x = c.root.Dataframe_send()
js = x.to_json(orient='split')
df = pd.read_json(js, orient='split')
df.plot(figsize=[20,15])

Then if it still does not work, the problem is elsewhere.


How do I add the value_counts for two columns, on each row of a DataFrame?

Question: I have this DataFrame that I have taken from another DataFrame. It has the start station for a bike trip and an end station. I plan to add them to a network using networkx and from_pandas_dataframe(). I just need to make another Series/column for the weights.
I want for each row to find the value_counts for each start station and end station and add them together as a weight.
So for first entry I would find the occurrences for stations 3058 and 3082, add them and place the result on the weights column like this.
EDIT: Adding code as requested:
df = data[['start_station','end_station']]
a = df.start_station.value_counts()
b = df.end_station.value_counts()
pd.options.display.max_rows=300
c = a + b

And here's the dataset: https://ufile.io/cxbov
Comment: Hey and welcome to SO. Please try to post your actual code here instead of images. You can check out [ask] for more guidance.
Comment: Also it would be nice if you could add small input data sample and the expected output.
Answer: You could do it like this:
df = pd.read_csv('metro.csv')

s = df[['start_station','end_station']].apply(pd.value_counts).sum(1)

df_out = df[['start_station','end_station']].assign(weight = df['start_station'].map(s) + df['end_station'].map(s))

print(df_out.head())

Output:
   start_station  end_station  weight
0           3058         3082    6248
1           3058         3082    6248
2           4147         4174     496
3           4157         4162     903
4           3013         3013     100


issues related to the copy of vector with pointer item

Question: I want to ask whether there are some problems with the copy for the vector of pointer items. Do I need to strcpy or memcpy because there may be depth copy problem?
For instance:
Class B;

Class A

{
   ....

private:
   std::vector bvec;

public:

   void setB(std::vector& value)

   {

      this->bvec = value;

   }

};

void main()

{

   ....

   std::vector<const B*> value; // and already has values

   A a;

   a.setB(value);

}

This example only assign the value to the class variable bvec inside A class. Do I need to use memcpy since I found that std::vector bvec; has pointer items?  I am confused with the depth copy in C++, could you make me clear about that? Thank you.
Answer: Think about this, if you remove and delete an item from the vector value after you call setB, then the vector in A will have a pointer that is no longer valid.
So either you need to do a "deep copy", have guarantees that the above scenario will never happen, or use shared smart pointers like std::shared_ptr instead of raw pointers. If you need pointers, I would recommend the last.
There is another alternative, and that is to store the vector in A as a reference to the real vector. However, this has other problems, like the real vector needs to be valid through the lifetime of the object. But here too you can use smart pointers, and allocate the vector dynamically.
Answer: It is unlikely you need strcpy or memcpy to solve your problem.  However, I'm not sure what your problem is.
I will try to explain copying as it relates to std::vector.
When you assign bvev to value in setB you are making a deep copy.  This means all of the elements in the vector are copied from value to bvec.  If you have a vector of objects, each object is copied.  If you have a vector of pointers, each pointer is copied.
Another option is to simply copy the pointer to the vector if you wish to reference the elements later on.  Just be careful to manage the lifetimes properly!
I hope that helps!
Comment: @forester2012 Copying a vector of pointers copies the _pointers_, not the actual objects they point to.
Comment: You mean that the std::vector operator=()  has already solved this depth copy problem in the low-level?
Comment: I mean that "this->bvec = value;" copies every item in the "value" vector individually to the "bvec" vector.  If you are storing pointers however, only the pointers themselves will be copied.  If you wish to copy the objects you'll need to write a loop like this:

`for (std::vector::iterator i = value.begin; i != value.end; ++i)
{
    this->bvec.insert(*(*i));
}`

where bvec is a std::vector
Comment: Your answer:  "If you wish to copy the objects you'll need to write a loop like this: for (std::vector::iterator i = value.begin; i != value.end; ++i) { this->bvec.insert(*(*i)); } where bvec is a std::vector"  make me confused again.   I think that in the lower-level std::vector has already solved the deep copy problem since my problem is just copy a vector of pointers to another vector.
Comment: Now I understand, and if that is the case, I think I can still use these pointers to refer to the actual objects.
Answer: You probably want to define your copy constructor for class A to ensure the problem your asking about is handled correctly (though not by using memcpy or strcpy).  Always follow the rule of three here.  I'm pretty sure with std::vector your good, but if not, then use a for loop instead of memcpy


Question on Gauss map - application of Birkhoff's ergodic theorem

Question: Take a Gauss map $G: [0,1] \longrightarrow [0,1]$ which is
$$G(x) = \frac{1}{x} \mod 1, 0<x<1$$ and $0$ if $x=0$. Let $\mu$ be the Gauss measure. For $x \in [0,1]$ let $[a_{1}(x), a_{2}(x),...]$ denote the continued fraction expansion of $x$. I would like to show that for any $\gamma>0$ we have for $\mu$-almost all $x \in [0,1]$ $$\lim_{n \longrightarrow \infty} \frac{a_{n}(x)}{n^{1+\gamma}} = 0.$$
Obviously, an application of Birkhoff's ergodic theorem is needed. I think we need to use the fact that for an ergodic measure preserving transformation $T$, with a measure $\mu$ and a function $f \in L^{1}$ we have $ \lim _{n \longrightarrow \infty} \frac{f(T^{n}(x)}{n} = 0$ for almost all $x \in \mu$. (This can be proved by considering partial sums of the form $\sum_{k=0}^{n-1} f(T^{k}(x)$).
But I don't know how to feel in the missing details - what function $f$ to choose, that this holds for all $\gamma >0$, etc. It looks like since we know $a_{n+1} = [\frac{1}{G^{n}(x)}]$ (where the square brackets denotes the integer part), we have to choose $f = \frac{[\frac{1}{x}]}{x^{\gamma}}$.
Is this right? I would appreciate any help and advice on how to make this rigorous.
Answer: Let $a(x) := \lfloor 1/x \rfloor$. As you noticed, we can't use Birkhoff theorem with the function $a$, as it is not integrable. We'll have to be more cunning. Since $a$ has a singularity in (essentially) $1/x$, note that $a^\alpha$ is integrable for all $\alpha \in [0,1)$. What does this gives us ?
First, note that for all $\alpha \in [0,1)$, the fonction $x \mapsto x^\alpha$ is concave and is $0$ at $0$. Hence, for all nonnegative $(a_0, \cdots, a_{n-1})$,
$$\sum_{k=0}^{n-1} (a_k^\alpha) \geq \left( \sum_{k=0}^{n-1} a_k \right)^\alpha,$$
or, if we put $1+\gamma/2 := 1/\alpha$, for all $\gamma >0$ :
$$\left( \frac{1}{n} \sum_{k=0}^{n-1} a_k^{\frac{1}{1+\gamma/2}} \right)^{1+\gamma/2} \geq \frac{1}{n^{1+\gamma/2}} \sum_{k=0}^{n-1} a_k \geq 0.$$
Let's apply this to $a_k := a \circ G^k$. We get:
$$\left( \frac{1}{n} \sum_{k=0}^{n-1} a^{\frac{1}{1+\gamma/2}} \circ G^k \right)^{1+\gamma/2} \geq \frac{1}{n^{1+\gamma/2}} \sum_{k=0}^{n-1} a \circ G^k \geq 0.$$
Thus, by Birkhoff's ergodic theorem, the sequence $\frac{1}{n^{1+\gamma/2}} \sum_{k=0}^{n-1} a \circ G^k$ is almost surely bounded. If we divide by $n^{\gamma/2}$, we get that, almost surely,
$$\lim_{n \to + \infty} \frac{1}{n^{1+\gamma}} \sum_{k=0}^{n-1} a \circ G^k = 0,$$
which is actually a stronger result than what you're looking for.
Comment: @A.P. : One the one hand, $a(x) = \lfloor 1/x \rfloor$. One the other hand, the Gauss measure $\mu$ is absolutely continuous, with density $1/(1+x)$ (up to a $\ln (2)$ factor), so bounded above and below. So we get something like, respectively, a singularity in $1/x$ and the Lebesgue measure. Hence, $a$ is not $\mu$-integrable, although $a^\alpha$ is $\mu$-integrable for all $\alpha \in [0,1)$.
Comment: Could you please explain why $a(x)$ is not integrable?


nhibernate: Class Mapping with no table

Question: I have an entity class that I use to represent the results of an sql-query. The mapping for the class shown below. Yet as far as I can tell nhiberate treats the mapping as if there is a real database table - when in fact there is not. In this case there is nothing in the database that represents this entity at all. I am using this to map a query through, but the same would be true of a view. Is there no way to indicate to nhibernate that there isn't a table represented by the mapping?
<class name="Models.UserTransaction">
  <id name="Id">
    <column name="Id" not-null="true" unique="true" />
    <generator class="native" />
  </id>
  <property name="TransType" />
  <property name="Date" />
  <property name="Amount" />
  <property name="Balance" />
</class>

This is the query I am mapping, which uses a user defined table. I couldn't get it working without having a mapping even though the example I copied appeared to.
  <sql-query name="UserTransactions">
    <query-param name="userId" type="string" />
    <return class="Models.UserTransaction" alias="userTx">
      <return-property name="TransType" column="TransType" />
      <return-property name="Id" column="Id" />
      <return-property name="Date" column="TransDate" />
      <return-property name="Amount" column="Amount" />
      <return-property name="Balance" column="Balance" />
    </return>
    <![CDATA[
      SELECT userTx.[Type] as TransType, userTx.[Id] as Id, userTx.[Date] as TransDate, userTx.[Amount] as Amount, userTx.[Balance] as Balance
      FROM dbo.User_AccountStatement(:userId) userTx
    ]]>
  </sql-query>

Comment: If you don't want to map your class to the database, then.. why are you mapping it? :) just remove the mapping completely, tell nHib to not map it, and that's it
Comment: As the question says I want to map it to the results of a query, like a report, so a one way (i.e. database to application) mapping. Just seems wrong for nhibernate to think treat it like a two way mapping when its not.
Comment: Looking at another query issue, I thought once again about your problem. Are you in fact searching for some ResultTransformer for SQL query and DTO ? http://relation.to/Bloggers/Hibernate32TransformersForHQLAndSQL#H-SQLTransformers
Comment: @DaleBurrell: I'm running into this exact problem right now. It makes perfect sense to have a one way mapping. An ORM is an Object Relational **Mapper**. That doesn't imply that inserts, updates and deletes are supported. It's a mapping tool for relational data to object oriented data. I really wish NHibernate would allow read/select only mappings for query results. We need to load data from many other tables, and creating a view for generating a report is overkill for our scenario.
Answer: If you have a db view, you can use nhibernate to map to that, but if all you are doing is storing the projection fields of the query there doesn't need to be a map at all.
How are you querying this data?
if you are using the criteria API, you can use the resultstransformer to map the returned object array to your class.  the types have to match between your class that the projection.
If you are using the LINQ provider you can project directly into your class.  so you'd have something like this
from s in Session.Query<some-type>
where s.some-property== "some-value"
select new your-type
{
some-property-on-your-type = s.some-property,
some-other-property-on-your-type = s.some-other-property
}

There is no need to write a mapping to the database since you aren't mapping to an object in the database.
Comment: OK, I've edited my question to show that I'm using an sql-query, I couldn't get it to work without a mapping, but maybe that is where I went wrong?
Answer: I guess you should at least specify a view as the tablename of your mapping.
The view should have the same resulting columns as your query (and hopefully return any row that your query could return)
Then you will be able to :

map your properties to your view/SQL query result columns
set your class as mutable="false"
declare your query as a named query (see : http://ayende.com/blog/3948/nhibernate-mapping-named-queries-query-and-sql-query )
Comment: It matter not whether you name it, because the default is the entity name. Otherwise you're correct, and thats exactly what I've done, but my question is, is there any way to tell nhibernate that its a one way mapping (see my comment on my question) as it seems wrong to be that nhibernate thinks its two way when its not. I watched in the log file as it generated an insert statement for it. Initially it also generated an update, but that was fixed by setting mutable=false which was suggested in an answer that appears to have been deleted.
Comment: @DaleBurrell : have you tried turning your id mapping  to a simple property with a column mapping, keeping unique constraint, with an insert=false and update=false (and repeat the update and insert parts for all your other properties) ?

nhibernate: Class Mapping with no table


How to get results from a query which is inside of a function

Question: I'm trying to make an "AdminCheck" system which will check if the user is admin and return user's admin level based on information gathered from database
I've did some research and realized my problem is with query being asynchronous, but I couldn't find more
<code>function isAdmin(varr){
    let queryCheck = "SELECT AdminLVL FROM accounts WHERE username = ?"
    pool.query(queryCheck, [varr], (err,results) => {
        console.log(results[0].AdminLVL) // This gives me results
        if(err){
            console.log(err)
        }
        else {
            return results[0].AdminLVL
        }
    })
}
</code>
right where I commented "This gives me results" everything works fine, but I wanna be able to use the result, which let's think its "300", somewhere else.
Comment: so, if you call `var admin = isAdmin('something')` from wherever in your code, what does return?
Answer: The problem is that the function calling isAdmin is running asynchronously, and not waiting for results. Change isAdmin to return a promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Then you can write the rest of your code in isAdmin(varr).then(res => { // your code })
Or you can use async await.
edit to add some code:
Do something along these lines (view the docs to get it to work exactly as you need it to)
<code>  isAdmin(varr) {
    return new Promise((resolve, reject) => {
        let queryCheck = "SELECT AdminLVL FROM accounts WHERE username = ?"
        pool.query(queryCheck, [varr], (err,results) => {
            console.log(results[0].AdminLVL) // This gives me results
            if(err){
                reject(err);
            }
            else {
                resolve(results[0].AdminLVL);
            }
        });
  });
</code>
Comment: now when I try to `console.log(isAdmin(varr))` I get `Promise {  }` and my console.log within my query doesn't seem to work anymore
Comment: do isAdmin(varr).then(res => {console.log(res)} if res contains the information you want, then you're good to go. Write all of your code that depends on the result inside of the then callback function.
Comment: I strongly recommend learning more about how asynchronous javascript works, then learn a bit more about promises and how they work. It might take a bit to wrap your head around, but once you've got it it will open up a whole new world for you, and might even just blow your mind. Then learn about async/ await. These concepts are crucial in both front and back end JS development.