Well, although this code belongs to Codereview@stackexchenge, but as nobody cares to follow any rules here - so I would.

There are too much problems with your code, ut to outline most:

It seems you don't quite understand what singleton is and why use it.
There is no point in extending application class from database handler class.
trigger_error('Unknown Method ') is apparently redundant. PHP can handle absent methods as well.
Never use die() in production code.
This whole class makes very little sense as it don't help you to handle mysqli even a bit.

Frankly, exactly the same result you can have without any "singleton" class but just by creating mysqli instance and making it

public function __construct() {
    global $mysqli;
    $this->mysqli = $mysqli;
}


Resource-leak: you neither close the statement nor the result set. Depending on the database driver, this can lead to system resource leaks, blocked OS handles, etc. Always close database objects ASAP (apart from connections, which you can hold for a longer time.)

Multiple looping over metadata: you reiterate over result set metadata for each row in the result set. As you do not know the underlying implementation, this may be quite an expensive operation, there's no way to be sure. Thus, better do this once and cache the information you need.

Error handling: you catch everything, log it, and let the application continue running without any indication of an error, eventually based on incomplete data. Bad idea. Do not catch exceptions here, declare the method as "throws SQLException" (or maybe re-wrap it in MyOwnApplicationException or whatever) - just don't continue running in error conditions.

Multithreading: connections normally cannot be shared amongst multiple threads (eventually invalidating their underlying objects and doing all kinds of funny things.) I see no precautions to avoid multi-threaded access in the code.

General utility: ask yourself, what are you going to do with this map? Create objects from the contents? Create excel reports? Is your application code written to handle each and every funny datatype a driver implementor may be inclined to return via getObject()? I sincerely doubt this is really useful. For object mapping, have a look at various ORM frameworks / JPA, for reporting there are other frameworks. This looks like the re-invention of a wheel to me.


You can overload your SetUniform method with the different types of value:

public void SetUniform(int value)
{

}
public void SetUniform(Vertex2f value)
{

}
public void SetUniform(Vertex3f value)
{

}
...

You could also try using the Null Object Pattern to avoid the null checks or define some default behaviour.


A quick and easy way would be to use a HashSet<T> and check the return of the Add() method. If it returns false you will know that you need to create a new filename. So let's start by extracting the creation  of the filename like so

private string CreateFileName(string original, ref int counter)
{
    counter += 1;
    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(original) + "(" + counter + ")";
    string fileExtension = Path.GetExtension(original);
    return fileNameWithoutExtension + fileExtension;
}

Next we iterate over all of the items of the array and try to add it to the HashSet<T>. If we can't add it, we create the new filename and try to add it again until we succeed.

private string[] ChangingDuplicateNames(string[] files)
{
    var hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
    foreach (var file in files)
    {
        var currentFile = file;
        int counter = 0;
        while (!hashSet.Add(currentFile))
        {
            currentFile = CreateFileName(file, ref counter);
        }
    }

    return hashSet.ToArray();
}


Format the output of Color.ToString() to RGB values

The code in question is using the wrong tool (Regex) to achieve what you want. Using the string representation of a Color to get a string back is not a good way.

If one would pass a predefined color like Color.Red into that method it would fail by returning R = , G = , B = because the Color.ToString() returns

  A string that is the name of this Color, if the Color is created from
  a predefined color by using either the FromName(String) method or the
  FromKnownColor(KnownColor) method; otherwise, a string that consists
  of the ARGB component names and their values.

If this is just for learning Regex you could change

string colorText = color.ToString();

to

string colorText = Color.FromArgb(color.R, color.G, color.B).ToString();

otherwise it would be better to just write

static string SimpleColorOutput(Color color)
{
    return $"R = {color.R}, G = {color.G}, B = {color.B}";
}


First, a general consideration about your project. I cannot see any unit test. I'd strongly encourage you to write some, as I think that unit tests can help you coming up with a better design. I haven't looked at the code in details so unfortunately I don't have other comments on that.

Looking at the example main you posted I see you should try to rewrite your code so that you do dependency injection and in a way that you don't have to violate the law of Demeter to setup the simulation.

What about changing the constructor of SimulationSystem to SimulationSystem(IEnumerable<SimulationThread> simulationThreads, IEnumerable<SimulationGroup> simulationGroups)? If you do that you make it clear what you need to run your simulation and you can avoid doing the very ugly operations involving system.World.Objects.

I am not sure what you want to do with all that calls to DateTime.Now, but they don't look quite right to me. I think that the idea of having system.Update take a TimeSpan as a parameter is good, but I would not expect it to be called in that way. What about this:

var currentDateTime = /* compute it somehow */
var endDateTime = /* compute it somehow */
var simulationTimespan = /* compute it somehow */
while(currentDateTime < endDateTime)
{
    system.Update(simulationTimespan);
    currentDateTime = currentDateTime.Add(simulationTimespan);
}


AT&T assembly - Basic loop & write - follow-up

This is much better.

Since this is v2, let me introduce you a couple more slightly advanced concepts.

First: The second time you execute write, what will be in (most of) those registers (rdi, rsi, rdx)?

It's easy to think in terms of C (or practically every other high level language), and how variables have 'scope.'  But asm's registers (even when used with call) don't work that way.

The is nothing 'wrong' with using macros like this.  It makes reading / maintaining much easier.  And in more complex examples, you probably wouldn't be able to assume that these registers haven't been modified since the last write.  But since we are critiquing this particular case, be aware that the code is slightly less efficient than it could be (since it re-assigns values that are already there 3 * 9 times).

Second (follows from the first):

write modifies a LOT of registers (as a percentage of how many registers there are).  In addition to the ones you see (rax, rdi, rsi, rdx), there are also the registers 'clobbered' by using syscall (rcx, r11).  It's going to be difficult to compose complex code if every time you want to write something, that many registers get destroyed.

This leads us to the concept of 'calling conventions' (something I've written about before).  In short, you come up with (or use an existing) standard set of rules about what registers your macros/routines are allow to modify, then avoid using those 'volatile' registers in the routines that call them (or save the contents of the registers yourself before making the call).  And if the macros/routines need more registers than your 'rules' allow, they must push/pop all the additional registers to preserve their contents.

Yes, this is starting to get a bit deeper.  But register handling is something you need to start thinking about if you want to read/write asm.  Additionally, it starts to explain some of the 'junk' you see when you disassemble your C code.  Those push/pops you see around the calls and at the top of functions?  This is why they are there.

I could talk about the cost/benefits of macros vs routines, but this is probably enough

A few more thoughts:

Add a comment at the top of the file.  Even something simple like The code loops to display "Hello, World!" ten times.
Stylistically, perhaps . - hello?  Negative hello seems weird.

Yes, nitpicky.  But that's what you get when you ask for code reviews on such basic code.

Edit1:

Hmm.  You haven't accepted an answer yet.  Were you looking for something else?  Or perhaps I wasn't clear about what I was trying to explain?  Let me take a shot at explaining this again:

Using macros isn't the same as defining routines.  Instead of defining the code in one place and calling it from other places, it pastes the entire macro in where ever it is invoked.

So your code basically expands to:

movq $10, %r8
l:
  movq $1, %rax
  movq $1, %rdi
  movq $hello, %rsi
  movq $15, %rdx
  syscall
  dec %r8
  jnz l

movq $60, %rax
movq $0, %rdi
syscall

If you were to call write twice in a row, you'd get:

movq $10, %r8
l:
  movq $1, %rax
  movq $1, %rdi
  movq $hello, %rsi
  movq $15, %rdx
  syscall
  movq $1, %rax
  movq $1, %rdi
  movq $hello, %rsi
  movq $15, %rdx
  syscall
  dec %r8
  jnz l

movq $60, %rax
movq $0, %rdi
syscall

Now, if I'm not mistaken, the syscall you are using overwrites rax (uses it as a return value), but leaves the other parameters alone.  Such being the case, it would be slightly more efficient to write:

movq $1, %rdi
movq $hello, %rsi
movq $15, %rdx
movq $10, %r8
l:
  movq $1, %rax # or perhaps movq %rdi, %rax?
  syscall
  dec %r8
  jnz l

movq $60, %rax
movq $0, %rdi
syscall

This doesn't lend itself well to macros.  But if performance was more important to you than "maintainability," this would be (slightly) better.

Alternately, you could do this as a routine.  The existing code for write uses 6 of the 15 x64 registers, stomping on their existing values in order to make the call.  Registers are a precious and limited resource.  If you were doing anything much more complex, you would start to run out.  Using routines allows you to bundle code in such a way that only a limited number of registers get modified, causing a minimum amount of disruption in the code that calls it.

For example, if you were to use the Microsoft x86 'fastcall' calling convention (a poor choice for 64bit linux, but useful as an illustration), then the first parameter gets placed in rcx, the second in rdx, and the return value (if any) goes in rax.  rcx, rdx and rax can all be changed by the routine, but all other registers must be returned unchanged.

So, re-working write with this in mind, we get something like this:

# On entry:
#   rcx points to the string to print
#   rdx contains the length of the string

push %rsi  # Save the non-volatile registers we modify
push %rdi
push %r11

movq %rcx, %rsi # Move the string pointer to the correct register

movq $WRITE, %rax
movq $STDOUT, %rdi
syscall

# At this point:
#   rax contains the return value from the call
#   rcx/r11 have been clobbered

pop %r11 # Restore the registers and return
pop %rdi
pop %rsi
ret

You can call it like this:

mov $hello, rcx
mov $len, rdx
call write
# At this point, the contents of rcx and rdx are undefined.

Note that when I say "rcx and rdx are undefined," I mean they are undefined by definition.  Yes, you can look at write and see what they would contain, but you pretend like you don't.  This way someone can modify write to work slightly differently, and every place that calls it will still work correctly.  As long as everybody follows the agreed-upon 'rules.'

The implications here define a lot of how registers actually get used, both by compilers when they generate asm and by people who write their own.  If you know how registers will be treated when you make a call, that helps you choose which registers to use for what.  For example, write needs the length in rdx.  So if you needed to count how many bytes were in a string before passing it to write,  then using rdx when doing the count suddenly makes a lot more sense.  And using rcx to hold your 1-10 loop counter would obviously be a poor choice, since it gets wiped out during each write.

To sum up:

Using the write macro allows for easy-to-read code.  It also allows you to call the macro (somewhat) generically.  However, it has some limitations that may make it a bad choice for more complicated code, or if performance it a primary consideration.

That's what I see when I read this code.


Sum of primes program is taking too long

I don't believe it is actually the specific Lne A that is the problem, but everything that is happening inside that loop, and most importantly, the line: primes.remove(...). From this StackOverflow answer you can see that remove(...) is an O(n) operation, thus it's performance is relative to the amount of data in the array. In this case, there's a lot.... and you are doing a lot of removes() since you are essentially removing all even values except 2.

What you should be doing is using a more efficient algorithm. You should read up on the Sieve of Eratosthenes, and introduce that algorithm here.

it will be much faster because it does not do any array-size changes. There are a number of posts here on CodeReview that have this problem solved quite nicely:

Sieve of Eratosthenes: making it quicker
Project Euler: primes in Python

(Primes in Python...)

(Sieve in other languages)


Perhaps I'm missing something, but it seems that the Video objects don't really need to know about what playlists they belong to, do they?

A playlist is a collection of videos.  You don't need a playlist index object.  You just need an array on each playlist that keeps track of what videos are on its playlist and in what order.  A simple array does all this for you.

It seems to me that the only reason a video would need to know what playlists it belonged to is if you wanted to provide some functionality for a video to quickly find all playlists it belonged to.  And when I say this, I mean a request where it's important for this information to be returned near instantly.

Even without the video knowing any information about the playlists, your code could still iterate through every playlist asking it whether or not it contained a given video and get the answer to what all playlists the video belongs to.  This might be a little time consuming, but I think it's a rare request.

But it seems what's most likely is that a user will either want to play an individual video, or play a playlist.  The request to play all playlists that contain this particular video seems an odd one to me.


Dual rewrite rules (WWW prefix and HTTPS)

Redirecting twice does cause a slight performance impact, but if you are looking to use HSTS then you should use two redirects, as there are some situations where going direct from http://example.com to https://www.example.com would cause issues.

An example is the HSTS preload list, where you must:

2) Redirect from HTTP to HTTPS on the same host, if you are listening on port 80.
https://hstspreload.org/

So you will need to make sure the redirect chain goes:

http://example.com -> https://example.com -> https://www.example.com


Using pointers and type cast to break up integers into byte array

If the buffer size is not divisible by 4, the remaining bytes are not set. This is a bug and should be corrected.

If you just need random values in the bytes, Random.NextBytes() does what you are trying to do and will likely be faster than both of your current implementation. It's up to you to decide if you care that the values were technically int32's before being written to the buffer.

When writing a benchmark, Stopwatch will provide more precision than DateTime.Now. I also thing 100 is not a large enough number of iterations to get a good average. As you pointed out, there were outliers that took almost twice as long as the majority of values.

It is probably best to take the seed from a command line argument. This will allow you to remove one more variable between the two implementation. While I don't expect Random's execution time to change significantly based on the seed, it is best to keep everything else equal when comparing two things.

Arrays have a Length property, so you shouldn't be dealing with the buffer size independently.

As for if it is worth it to make this optimization, that isn't something we can tell you. Have you profiled the execution of the actual program? Is this where your code if spending the majority of it's time? If it's actually IO bound, ~12ms doesn't mean anything. Where as, if this chunk of code is running millions of times each time your program does a single task, ~12ms is huge and well worth optimizing.


I'd implement this function like this:

from itertools import count

def palindromes():
    """Generate numbers that are palindromes in base 10."""
    yield 0
    for digits in count(1):
        first = 10 ** ((digits - 1) // 2)
        for s in map(str, range(first, 10 * first)):
            yield int(s + s[-(digits % 2)-1::-1])

(In Python 2, you should replace range with xrange and map with itertools.imap.)

The insight is that instead of building an odd-length palindrome from the parts prefix + middle + xiferp, we can build it as prefix + iferp: that is, with the middle digit being supplied by the last digit of the prefix.
In your main loop, you arrange to generate the first 501 palindromes:

for i, palindromeNumber in enumerate(palindromGenerator):
    ...
    if i >= 500:
        break

but it would be simpler to use itertools.islice:

for i, palindrome in islice(enumerate(palindromeGenerator), 501):
    ...

As for your question about efficiency, it is impossible to answer without knowing the purpose of this code. If all you are going to do is to print the first 501 palindromes, then your code is fine: the runtime will be dominated by printing the output.


https://gtmetrix.com/ notes that redirects are the largest culprit in slowing down my page loads

gtmetrix.com's "suggestion" in this regard is arguably "incorrect" (or rather, not nearly as serious as it implies), assuming you are already consistently linking to the canonical URL*1 throughout your site (and you have no other redirects in your application code). These redirects are only likely to affect a "very small fraction" of your site visitors on their very first visit.
(*1 Canonical URL being HTTPS + non-www + no .html extension.)
You have 3 external redirects in the .htaccess code you posted:

#REDIRECT TO SECURE HTTPS CONNECTION
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

#URL EXTENSION REMOVAL
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

If you have implemented HSTS then you need to redirect from HTTP to HTTPS on the same host, before canonicalising the www subdomain - which is what you are doing above in the first rule. This is a requirement of HSTS and the "preload list". So you cannot avoid having at least 2 redirects (worst case) in this scenario.
However, if you have no intention of implementing HSTS then you can combine the first two redirects into one. Which you can do by simply reversing the order of the first two rules. For example:
#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]

#REDIRECT TO SECURE HTTPS CONNECTION
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The first rule, that redirects www to non-www, also redirects to HTTPS, so there is never a need to execute the 2nd redirect as well. So, there is only ever 1 redirect to canonicalise HTTPS and non-www.
I also removed the redundant capturing subpattern (ie. (.*)) in the "HTTP to HTTPS" RewriteRule pattern, since you are using the REQUEST_URI server variable instead. And changed the other "www to non-www" redirect to be consistent. Note that the REQUEST_URI server variable contains the full URL-path, including the slash prefix, whereas the captured backreference omits the slash prefix.
The above two rules could be combined into a single (marginally more complex) rule, but there is no benefit in doing so.
The rules could also be made more "generic", without having to explicitly state the canonical hostname. However, how you implement this and whether this is easily possible is dependent on whether you have other subdomains or not. But again, this serves no "benefit", other than being more copy/pastable. Generally, it is preferable to be explicit here - less prone to error.

#URL EXTENSION REMOVAL
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

You can also avoid the .html "extension removal redirect" from triggering an additional redirect by including this redirect first (before the above two canonical redirects) and redirecting directly to HTTPS and non-www (the canonical scheme+hostname) as part of the redirect.
UPDATE: This should also be a 301 (permanent) redirect, not a 302 (temporary) redirect that it is currently. A 301 redirect is cached by the browser by default, so it avoids unnecessary round trips to the server. When you don't explicitly include the status code with the R flag, it defaults to a 302.
The NC flag is also not required on the RewriteRule directive, since you are not matching anything here that is case-sensitive.
This rule to remove the .html extension probably works OK for your URLs, however, it's not necessarily correct and could possibly be made more efficient. The reason for checking against THE_REQUEST server variable, as opposed to the RewriteRule pattern or REQUEST_URI server variable is to avoid a potential redirect loop by preventing rewritten requests from being redirected. This is because THE_REQUEST does not change after the request is rewritten - it contains the first line of the HTTP request headers. However, THE_REQUEST also contains the query string, so it's possible for a legitimate request that contains .html as part of the query string to be incorrectly redirected.
For example, request example.com/?p1=foo.html&p2=bar (the homepage with a query string and URL parameters containing the value foo.html) and this will be incorrectly redirected to example.com/?p1=foo, truncating the query string.
The regex /([^.]+)\.html will also fail to match any URL that contains dots as part of the URL-path in places other than the file extension. eg. A request for /foo.bar.html would not be redirected. Although this may be perfectly OK for the URLs on your site.
To avoid these "incorrect" redirects you could capture the URL-path from the RewriteRule pattern instead and either use a simpler condition and check against THE_REQUEST (to avoid a loop) or use the REDIRECT_STATUS environment variable instead, which is always empty on direct requests.
For example:
#URL EXTENSION REMOVAL
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule (.+)\.html$ https://example.com/$1 [NC,R=301,L]

This captures the URL-path before the .html file extension using the RewriteRule pattern (which naturally excludes the query string). The simple condition that checks the REDIRECT_STATUS env var prevents a redirect loop.
Bringing the above points together we have:
#URL EXTENSION REMOVAL
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule (.+)\.html$ https://example.com/$1 [NC,R=301,L]

#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]

#REDIRECT TO SECURE HTTPS CONNECTION
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The NC flag was not required in the "URL extension removal" redirect.
This now triggers at most 1 redirect regardless of whether a request comes in for HTTP, www or includes the .html extension. However, as noted, this is at the expense of not satisfying the requirements for HSTS.
And it should be noted, that in real terms, there may not be a perceivable difference between 1, 2 or even 3 redirects here. Particularly since it will not affect the vast majority of visitors anyway.

Additional:

#REDIRECT FOR DATE PAGE
Redirect /date /storage/date-202010

#REDIRECT FOR HOME PAGE
Redirect /home /

Generally, you should avoid mixing redirects from both mod_alias (Redirect / RedirectMatch) and mod_rewrite (RewriteRule). The two modules run independently and at different times during the request, despite the apparent order of the directives in the .htaccess file.  mod_rewrite runs first. So, you can get unexpected conflicts.
Note also that Redirect is prefix-matching and everything after the match is appended on to the end of the target URL. eg. /date/foo would get redirected to /storage/date-202010/foo by the first rule. These particular redirects are also 302 (temporary) redirects. It looks like they should be 301 (permanent)?
However, in this case it probably does not matter whether you use Redirect or RewriteRule, but as a general rule, if you are using mod_rewrite for some redirects, then use mod_rewrite for all redirects. For example:
#REDIRECT FOR DATE PAGE
RewriteRule ^date$ /storage/date-202010 [R=301,L]

#REDIRECT FOR HOME PAGE
RewriteRule ^home$ / [R=301,L]

#BLOCKS FILE TYPES FOR USERS
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|inc|bak)$">
Order Allow,Deny
Deny from all
</FilesMatch>

You stated in comments that you are using Apache 2.4, however Order, Allow and Deny are Apache 2.2 directives and are formerly deprecated on Apache 2.4. They still work, but for backwards compatibility only and should be updated as soon as.
Note that you need to update all instances on your system since the newer directives don't necessarily mix well.
On Apache 2.4 you would use the Require directive instead:
#BLOCKS FILE TYPES FOR USERS
<FilesMatch "\.(ht[ap]|ini|log|sh|inc|bak)$">
Require all denied
</FilesMatch>

Note that the Apache server config "should" already be blocking direct access to .htaccess and .htpasswd files, but better to be safe I guess.

ErrorDocument 500 /allerror.php

Defining the 500 ErrorDocument late in .htaccess is probably too late to catch most 500 (Internal Server Error) responses (that result from misconfigurations). There's probably not much you can do about this, but it would be preferable to define this earlier in the server config (or <VirtualHost> container) in order to be more "useful".


Debugging:

When running your code in Firefox, I get the following error:

  TypeError: Argument 1 of Window.getComputedStyle does not implement
  interface Element.

This is because button.nextSibling() is a text node. Use nextElementSibling() instead.

Suggestions:

I recommend attaching an "active" class to the dropdown itself instead of its content. The semantics are clearer and it provides you with more flexibility. E.g. you could style an active toggle button differently.
Also, instead of querying the computed display style (slow!) of the button in order to infer whether a dropdown is active or inactive via

if (getComputedStyle(this.nextSibling).display === 'none') {
  ...
}

you could simply check for the dropdown's "active" class via

if (dropdown.classList.contains('.active') {
  ...
}

which is faster and agnostic to the specific CSS properties of an "active" dropdown button.
Additionally, instead of relying on a fixed order of dropdown toggle button and dropdown content by querying for the dropdown button first and then getting the content via nextSibling() or nextElementSibling(), I recommend querying for the dropdown first and then separately querying its children for a dropdown-toggle and the dropdown-content.
Finally, I recommend simplifying the deeply nested structure of your code by moving the reusable deeply nested code into  a toggleDropdown function.

Style:

While some people consider the following idiomatic:

[].forEach.call(document.querySelectorAll('...'), function(element) {
  ...
});

I prefer using the simpler for ... of iteration:

for (let element of document.querySelectorAll('...')) {
  ...
}

Assigning the query results to a variable with a self-documenting name might improve readability:

let elements = document.querySelectorAll('...');
for (let element of elements) {
  ...
}

Enhancements:

You might want to listen to the "blur" event and deactivate the dropdown when its focus is transferred to an outside element.

function toggleDropdown(dropdown) {
  if (dropdown.classList.contains('active')) {
    dropdown.classList.remove('active');
  } else {
    let activeDropdowns = document.querySelectorAll('.dropdown.active');
    for (let activeDropdown of activeDropdowns) {
      activeDropdown.classList.remove('active');
    }
    dropdown.classList.add('active');
  }
}

let dropdowns = document.querySelectorAll('.dropdown');
for (let dropdown of dropdowns) {

  // Toggle when dropdown toggle clicked:
  let toggle = dropdown.querySelector('.dropdown-toggle');
  toggle.addEventListener('click', function() {
    toggleDropdown(dropdown);
  });

  // Deactivate when focus leaves dropdown:
  dropdown.addEventListener('blur', function(event) {
    if (!this.contains(event.relatedTarget)) {
      this.classList.remove('active')
    }
  }, true);
}
.dropdown {
  display: inline-block;
}

.dropdown .dropdown-toggle {
  background-color: #fff;
  border: 0;
  color: #424242;
  cursor: pointer;
  padding: 5px 0 5px 0;
}

.dropdown .dropdown-content {
  display: none;
}

.dropdown.active .dropdown-content {
  margin-top: 5px;
  display: block;
  background-color: #fff;
  border: 1px solid #eee;
  box-shadow: 0 0 2px 1px #dcdcdc;
  position: absolute;
  border-radius: 3px;
  z-index: 10;
}

.dropdown .dropdown-content a {
  display: block;
  width: 100%;
  text-decoration: none;
  color: #3d3d3d;
  padding: 4px;
  box-sizing: border-box;
  font-size: 0.9em;
}

.dropdown .dropdown-content a:hover {
  background-color: #f0f0f0;
}

.dropdown.menu1,
.dropdown.menu2 {
  margin: 0 0 0 20px;
}

.dropdown.menu1 .dropdown-toggle {
  border-bottom: 2px solid #00BCD4;
}

.dropdown.menu2 .dropdown-toggle {
  border-bottom: 2px solid #4CAF50;
}

.dropdown.menu3 .dropdown-toggle {
  border-bottom: 2px solid #9FA8DA;
}

    <button class="dropdown-toggle">Menu 1</button>

        Option 1
        Option 2

    <button class="dropdown-toggle">Menu 2</button>

        Option 1

    <button class="dropdown-toggle">Menu 3</button>

        Option 1
        Option 2
        Option 3

Edit:

You could move the declaration of both event listeners out of the loop body. However, the dropdown toggle's 'click' event listener needs access to the dropdown element it belongs to. So you would still need a closure or alternatively bind the event listener's this to the dropdown:

function onDropdownBlur(event) {
  if (!this.contains(event.relatedTarget)) {
    this.classList.remove('active')
  }
}

function onDropdownToggle(event) {
  toggleDropdown(this);
}

let dropdowns = document.querySelectorAll('.dropdown');
for (let dropdown of dropdowns) {

  // Toggle when dropdown toggle clicked:
  let toggle = dropdown.querySelector('.dropdown-toggle');
  toggle.addEventListener('click', onDropdownToggle.bind(dropdown));

  // Deactivate when focus leaves dropdown:
  dropdown.addEventListener('blur', onDropdownBlur, true);
}


Two suggestions for improvement. First, there's no need to keep track of all those possible words in a list list_possible. You could create and check them on the fly instead, saving memory and a bunch of append calls:

for item in perm_words:
    word = "".join(item).lower()
    if dictionary.check(word):
        if word not in list_words_print:
            list_words_print.append(word)

EDIT There's a sneaky bug preventing this, as pointed out by OP. Due to perm_words generating the combinations with a length as determined by range(3, len(word)), word is not a variable that should be overwritten in this loop. Or, rename the user input.

Second, having a list to keep the dictionary words in is unnecessarily slow. For every new word found, it's being compared to each word in that list. A faster option would be to store them in a set. Sets can't contain duplicates, so you could simply add each word without having to worry if you've seen it before:

found_words = set()
for item in perm_words:
    word = "".join(item).lower()
    if dictionary.check(word):
        found_words.add(word)


Executive summary:

please_use_very_readable_names insteadOfUnreadableOneslikeInJava.
Use higher-order predicates.
Always consider using DCGs when describing lists. pass1 and pass2 can be simplified a lot with DCGS.
Use format/2 instead of multiple write/1 calls.

Examples:

Higher order predicate maplist/2, replacing 4 almost identical member/2 calls:

make_guess(Guess) :-
    length(Guess, 4),
    Colours = [red, blue, green, yellow, orange, purple, pink],
    maplist(list_member(Colours), Guess).

list_member(Ls, M) :- member(M, Ls).

Sample query and its result:

?- make_guess(Gs).
Gs = [red, red, red, red] ;
Gs = [red, red, red, blue] ;
Gs = [red, red, red, green].

Further example, for counting the number if white elements with the higher-order predicate include/3:

list_num_white(Ls, N) :-
    include(=(white), Ls, Ws),
    length(Ws, N).

Sample query and its result:

?- list_num_white([white,black,white], N).
N = 2

Exercise: Generalize this by parametrizing the element, so that you can use list_element_count(Ls, black, N) and list_element_count(Ls, white, N).

Example for format/2: Instead of:

write(Guess), write(' '), write(ThisScore),nl

you can write:

format("~w ~w\n", [Guess,ThisScore])


In my experience idiomatic Haskell does not use if/else very much. Guards are definitely the preferred approach. The idea is to have the core of your logic in a function and let the checks and edge cases be handled at the edges. This also tends to end up with cleaner, more open code. Using the guard lets the reader see exactly what is happening without having to look inside the if/else branches.

insert' :: (Ord a) => a -> [a] -> [a]
insert' x []         = [x]
insert' x yys@(y:ys)
  | x <= y           = x : yys
  | otherwise        = y : insert' x ys

If you are concerned about speed, the compiler transforms the guards and the if/else into the same case structure internally. I made a simple main:

main = putStrLn $ show $ insert' 2 $ insert' 4 [3,2,1]

Below is the relevant section from ghc -O2 -ddump-simpl insert.hs. I added comments to shows where your original code is to help you read it.

Rec {
Main.main_$sinsert' [Occ=LoopBreaker]
  :: GHC.Integer.Type.Integer
     -> [GHC.Integer.Type.Integer] -> [GHC.Integer.Type.Integer]
[GblId, Arity=2, Caf=NoCafRefs, Str=DmdType LS]
Main.main_$sinsert' =
  \ (x_akb :: GHC.Integer.Type.Integer)
    (ds_dxR :: [GHC.Integer.Type.Integer]) ->
    case ds_dxR of wild_X8 {
      [] ->
        GHC.Types.:
          @ GHC.Integer.Type.Integer
          x_akb
          (GHC.Types.[] @ GHC.Integer.Type.Integer);  {- [x] case -}
      : y_ake ys_akf ->
        case GHC.Integer.Type.leInteger x_akb y_ake of _ {
          GHC.Types.False ->
            GHC.Types.:
              @ GHC.Integer.Type.Integer
              y_ake
              (Main.main_$sinsert' x_akb ys_akf); {- recurse -}
          GHC.Types.True ->
            GHC.Types.: @ GHC.Integer.Type.Integer x_akb wild_X8 {- return of final list -}
        }
    }
end Rec }


Adding extension methods to IServiceCollection in ASP.NET Core

Instead of doing

services.AddThemes(options => {
    options = Configuration.GetSection("Themes").Get<ThemesOptions>();
});

you could  use

services.AddThemes(options => {
    Configuration.GetSection("Themes").Bind(options);
});

which will programatically set each value of options based on what's in the configuration.


Modularize more efficiently in an if/else setup

There are some code smells in your code.

Duplicated Code:

fraction = stdin.next(); // Get the fraction read
thisFract = new Fraction(fraction);
list.add(thisFract);

fraction = stdin.next();
thisFract = new Fraction(fraction);
inList = list.delete(thisFract);

These lines do (almost) the same thing. It is commonly practice in software development to hold solutions at one place. In this case a method which reads the next fraction and another method which add a fraction to a list. This is meant by modularization. Divide your solution in little subsolutions which can be changed at one place and used at different places.

This code optimization is called Refactoring.
There a lots of patterns for code refactoring.

Replace Conditional with Polymorphism:

You could think about using a switch-statement instead of the if-else blocks but it is highly recommended to use Polymorphism instead of conditional checks in object oriented programming languages.

Clean Code:

I would recommend also to read the book Clean Code written by Robert "Uncle Bob" C. Martin which explains lots of patterns to write well organized code.

For Example you can modularize your code like this:

move the if-else in one method
find code clones in the condition blocks and separate into methods
refactor methods top-down

public void run() throws java.io.IOException {
    stdin = new Scanner(System.in);
    String input;
    input = nextFraction();

    while (!input.equalsIgnoreCase("Q")) {
        handleInput(input);
    }
}

private void handleInput(String input) {
    String fraction;
    int numPerLine;
    boolean inList = false;

    if (input.equalsIgnoreCase("A")) {
        handleA();
    } else if (input.equalsIgnoreCase("D")) {
        handleD();
    } else if (input.equalsIgnoreCase("S")) {
        handleS();
    }
}

private void handleA() {
    assignNextFraction();
    addFractionToList();
    outputFractionAdded();
}

private void handleD() {
    assignNextFraction();
    inList = deleteFractionFromList();
    if (inList) {
        outputFractionRemoved();
    } else {
        outputFractionNotInList();
    }
}

private void handleS() {
    outputListSum();
}

private boolean deleteFractionFromList() {
    boolean inList;
    inList = list.delete(thisFract);
    return inList;
}

private void addFractionToList() {
    list.add(thisFract);
}

private void assignNextFraction() {
    String fraction;
    fraction = nextFraction();
    thisFract = createFraction(fraction);
}

private void outputFractionAdded() {
    output(thisFract.toString() + " was added " + "to the list.");
}

private void outputFractionRemoved() {
    output(thisFract.toString() + " was removed " + "from the list.");
}

private Fraction createFraction(String fraction) {
    return new Fraction(fraction);
}

private String nextFraction() {
    String fraction;
    fraction = stdin.next(); // Get the fraction read
    return fraction;
}

private void outputFractionNotInList() {
    output(thisFract.toString() + " is not in the" + " list.");
}

private void outputListSum() {
    output("The sum of the list is: " + list.sum());
}

protected void output(String s) {
    System.out.println(s);
}


One small thing is during the last iteration of the loop, the last element is swapped with itself.

Why not just use the Collections.shuffle as a guide?

public static void shuffle(List<?> list, Random rnd) {
    int size = list.size();
    if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
        for (int i=size; i>1; i--)
            swap(list, i-1, rnd.nextInt(i));
    } else {
        Object arr[] = list.toArray();

        // Shuffle array
        for (int i=size; i>1; i--)
            swap(arr, i-1, rnd.nextInt(i));

        // Dump array back into list
        ListIterator it = list.listIterator();
        for (int i=0; i<arr.length; i++) {
            it.next();
            it.set(arr[i]);
        }
    }
}

private static void swap(Object[] arr, int i, int j) {
    Object tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

This could be altered to:

public static void shuffleArray(Object[] arr, Random rnd) {
    for (int i=arr.length; i>1; i--) {
        int j = rnd.nextInt(i);
        Object tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}


No need for any loops with Java 8 streams.

Get a DoubleStream from the array with Arrays.stream(double[] array) so that you can
get the distinct() elements from that
which you can count() to retrieve your result.

public static long numUnique(double[] list)
{
    return Arrays.stream(list).distinct().count();
}

As count() returns a long, I modified the signature of your method to return long, too. It's within the responsibility of the user of your method then to perform any cast on the result.

Full example program:

import java.util.Arrays;

public class UniqueDoubles
{
    public static void main(String[] args)
    {
        double[] doubles = {1, 2, 3.5, 3.5, 2, 345345.345345};

        System.out.println(numUnique(doubles));
    }

    public static long numUnique(double[] list)
    {
        return Arrays.stream(list).distinct().count();
    }
}


Simple GUI using tabs to separate application windows

Is using a constructor to pass a JPanel, and then adding elements in the new class considered bad coding?

Not necessarily. However, if you only create an instance of the other class just to do things in the constructor, then you don't need the new class - and in that case it is considered bad coding.

If that's all you do in the constructor, then move the code from the constructor to a method (which you can place more or less anywhere, but I'd recommend having it in the original class unless you feel that the original class gets too big).

private void createEntityTab(JPanel panel) {
   ...
   panel.add(...);
   ...
}

Actually, it might be even better to let this method return the JPanel, so that you can use this code:

createPane.addTab("Create Entity", null, createEntityTab());

And use the method:

private JPanel createEntityTab() {
   JPanel panel = new JPanel();
   panel.setLayout(null);
   ...
   panel.add(...);
   ...
   return panel;
}


Working with Locales in Swing (with change at runtime)?

Consider applyComponentOrientation(), which recursively "Sets the ComponentOrientation property of this component and all components contained within it." Examples may be found here.


Let's get the security aspect out of the way first.

The idea of the XKCD password is a set of characters that is hard to guess, but easy to remember (in the form of words that only you know). This code fails on both one criteria.

The word list trims possibilities to a known set of words. See discussion in comments.
Random words doesn't mean easy to remember.

Your code did conform to the concept. I just wouldn't use it to generate my password. It would be a good password suggestion tool though.

Now over to your code.

$.ajax({ url: '../xkcd_wordlist.txt',
  async: false,
  success: function(data) {
    wordlist = data.split('\n');
  }
});

You gain nothing from making this request synchronous. This will make the UI freeze while waiting. If your goal was to prevent that input from being updated while loading, you could just set the readonly property until the request succeeds.

In addition, I suggest you use promises and the method then instead of the success option to set the callback. It's better practice as promises are standard. Even if you don't use native promises, getting used to using then will just reinforce your muscle memory when using promises.

The jQuery function also doubles as $(document).ready() when given a function. Also, since you're just doing a GET request, just use the $.get shorthand.

Consider splitting off the password generator into its own function so that it becomes reusable as well as split from the UI logic that is updating the password field. Also, since I suggested async fetching of the word list, this means your UI logic can be called with an empty word list. Make the code throw an error when the word list is empty and handle it accordingly.

$(function(){

  var wordList = [];
  var passwordInput = $('#password-input');
  var stepsInput = $('#word-count');

  function generatePassword(wordList, words){
    var password = '';

    for(var i = 0; i < words; i++){
      password += wordList[Math.floor(Math.random() * wordlist.length)];
    }

    return password;
  }

  function updatePasswordField(){
    if(!wordList.length) throw new Error('Word list not populated');
    passwordInput.val(generatePassword(wordlist, stepsInput.val()));
  }

  passwordInput.prop('readonly', true);

  $.get('../xkcd_wordlist.txt').then(function(data){
    wordList = data.split('\n');
    passwordInput.prop('readonly', false);
    updatePasswordField();
  });

});


Rails 5 helpers to fetch tasks with different filters

One possible improvement is using scopes:

def get_projects_owed
  current_user.projects.owed.recent_first.pluck(:name, :start_date, :end_date)
end

def get_all_projects
  current_user.projects.recent_first.pluck(:name, :start_date, :end_date)
end

def get_last_task_owed
  get_owed_tasks.last.task_end_date.strftime("%B %d, %Y")
end

def get_first_task_owed
  get_owed_tasks.first.task_end_date.strftime("%B %d, %Y")
end

def get_owed_tasks
  tasks = @project.tasks
  tasks.owed.order('task_end_date DESC')
end

helper_method :get_owed_tasks

class Project
  scope :owed, -> { where('end_date > ?', Date.today) }
  scope :recent_first, -> { order(:start_date) }
end

class Task
  scope :owed, -> { where('task_end_date >= ?', Date.today) }
end


Style
PEP8 is the Python style guide and is worth a read to keep your code clear and understandable.
Naming
You're not using your loop indicies, t and i, it's customary to replace them with _ to indicate this.
The name func for a function doesn't tell you what it does. Names should be as descriptive as possible, in this case sin seems sensible
def sin(x):
    return math.sin(x)

Functions
The function sin doesn't actually give you anything, as is now clearer, and I'd remove it altogether.
The calculation of you integration is discrete, and might be used separately. I would put that inside a function
def monte_carlo(n):
    resf = 0
    for _ in range(n):
        uniform_rand_no = random.uniform(0, math.pi)
        resf += math.sin(uniform_rand_no)
    return math.pi * resf / 10000

Note that I've:

Allowed you to pick the number of iterations
Added spaces around operators

I'm not really sure what resf means, otherwise I would have renamed that too.
Main
All your code will execute when you import your file. If you use the following you can gate execution solely to when the file is run:
if __name__ == "__main__":
    for _ in range(10):
        ...

Everything
Putting all this together you would get:
import random
import math

def monte_carlo(n):
    resf = 0
    for _ in range(n):
        uniform_rand_no = random.uniform(0, math.pi)
        resf += math.sin(uniform_rand_no)
    return math.pi * resf / 10000

if __name__ == "__main__":

    integral = 0
    n = 10000

    for _ in range(10):
        integral += math.pi * monte_carlo(n) / n

    print(integral / 10)


import *

Since you only need sqrt and log10 from math, I would change this:

from math import *

to:

from math import sqrt, log10

pep8

Use descriptive method names. I have no idea what dl or c mean
Valiable (and argument) names should be descriptive. It is very hard to determine what Omo is.
use lower_case for arguments and variable names
Spacing between operators

unused arguments

def dl(n, Om, Od, M):
    Od = 1 - Om

Why pass in Od if you overwrite it immediately afterwards?

In fact, Od is only used in ant, so why not just calculate it there and omit it for the rest?

global variables

dl uses xx while it's not in the argument list. It also only uses n to index xx, why not pass in the relevant value from xx as argument immediately?

Using this global variable makes it harder to use this method for other values

inner functions

Functions delta and L gets defined all 2000 iterations of the for-loop. This is unnecessary

L uses global state, and is calculated multiple times , why not just do

l = np.exp(-0.5 * (c(Omn, Odn, Mn) - c(Omo, Odo, M)))

making it a variable instead of a function?

Seperate the functions

Even in a simple script, you can seperate the production of the results from the presentation of the input

use if __name__ == '__main'__:

so your program can be run a script, but also imported as a module

R3

Why generate a new random number with the same name? Either it's the same number, so no need to generate it, or it's a different number, so give it a new name

Besides that, if L() is larger than a number between 0 and 1, it will be larger than 1, so if .. elif is unnecessary

Magic numbers

Where come the 0.000001 in c and the 0.04 in delta come from? If these a constants, better name them so

avoid repetition

The way your program is setup, Cov is converted to a numpy array a lot, and c(Omn, Odn, Mn) and c(Omo, Odo, M) are calculated over and over without any change in arguments, better to do those things once

f_list

instead of appending,  I would use a list comprehension.

One step further, since you need it as a np.array anyway, why not use np.fromiter and a generator expression?
Why are you taking the determinant from a two-dimensional array, instead of doing the calculations on a one-dimensional array?

All in all, I would end up with something like this:

import numpy as np
import emcee
import matplotlib.pyplot as plt
from math import sqrt, log10
from scipy.integrate import quad
from scipy.integrate import odeint
from io import StringIO

def ant(z, Om):
    Od = 1 - Om
    return 1 / sqrt(((1 + z) ** 2) * (1 + Om * z) - z * (2 + z) * Od)

def dl(x, y, Om, M):
    q = quad(ant, 0, x, args=(Om,))[0]
    h = 5 * log10((1 + x) * q)
    return y - M - h

def c(xx, yy, cov, Om, M):
    f_list = np.fromiter(
    (dl(x, y, Om, M) for x, y in zip(xx, yy)),
    dtype=float,
    count=len(xx),
    )
    a = np.dot(f_list, cov)
    b = np.dot(a, f_list.T)
    return b * 0.000001

def delta(r1, r2):
    sig = 0.04
    return sig * (np.sqrt(-2 * np.log(r1)) * np.cos(np.radians(r2)))

def calculation(xx, yy, cov, M, Omo, N):

    c0 = c(xx, yy, cov, Omo, M)
    for i in range(1, N):
        R1 = np.random.uniform(0, 1)
        R2 = np.random.uniform(0, 1)
        R3 = np.random.uniform(0, 1)
        R4 = np.random.uniform(0, 1)
        R5 = np.random.uniform(0, 1)

        Omn = Omo + delta(R1, R2)
        Mn = M + delta(R3, R4)

        c_ = c(xx, yy, cov, Omn, Mn)
        l = np.exp(-0.5 * (c_ - c0))

        if l > R5:
            O_m = Omn
            chi = c_

        yield chi, O_m

def main(filehandle):
    temp = 1e5
    z0 = 0
    M = 2
    Omo = 0.3
    H0 = 70

    N = 2000
    xx = np.array([0.01,0.012])
    yy = np.array([32.95388698,33.87900347])
    cov = np.array([[137,168],[28155,-2217]])

    for chi, O_m in calculation(xx, yy, cov, M, Omo, N):
        filehandle.write("{0}\t{1}\n".format(chi, O_m))

    if chi < temp:
        temp = chi
        chimin = temp
    return chimin

if __name__ == '__main__':
    # with StringIO() as filehandle:
    with open('txtfile.txt', 'w') as filehandle:
        chimin = main(filehandle)
        # print(filehandle.getvalue())
        print("Minimum of chi squre is")

        print(chimin)
        print(input("Press any key to exit... "))

I don't know whether this will spectacularly speed up your algorithm, but it will help, especially the more simple c. For this simple input, it needed about 33% less time on my machine

Larger gains will be made by vectorizing more, but for that I would need to have a better mathematical understanding of what's going on


Change $devicesArray to $devices.  It is obvious enough that each device would contain an array of information.
Change $namesArray to $deviceFields it is more meaningful.
Change $deviceName to $deviceType. $deviceName seems to be misleading.
Use $device instead of $d in the foreach loop, it is more meaningful.
'Device' is a field and should be the first field in $deviceFields. This is required for the following improvement.
Use array functions to combine the arrays:
array('Device Type' => $deviceType]) + array_combine($deviceFields, $device).

The function then becomes:

function convert($deviceType, $deviceFields, $devices) {
    $result = [];

    foreach ($devices as $device) {
        $result[] =
            ['Device Type' => $deviceType] +
            array_combine($deviceFields, $device);
    }

    return $result;
}


Correctness

In

let mut x: u8 = 0;
let mut y: u8 = 0;

while x < width {
    while y < height {
        println!("{}, {}", x, y);
        func(x, y);

        y += 1;
    }

    x += 1;
}

y increments up to height, but then never gets reset. That means that the inner loop only runs once. To fix this, move the initialization of y inside the loop, or use a "normal loop" (see below).

Formatting and convention

Right now, it looks like you're trying to write Rust in a different language. Whenever possible, use the conventions suggested by the Rust compiler and the linter clippy (run cargo clippy). In particular, using #![allow(non_snake_case)] to set your own convention is discouraged.

A few other things:

Use /// for documentation. /* */ comments are fairly rare and /// comments will automatically be included in the documentation produced by cargo doc.
Keep lines fairly short. It's OK to go over the traditional limit of 80 characters sometimes, but whenever possible, break up lines for readability. For example, with a function signature or call, the arguments can be placed on separate lines. cargo fmt will do this automatically to the best of its ability.
Vec<T> is itself a pointer (and length and capacity), so &Vec<T> has no advantage over &[T]. In fact, due to automatic deref coercion, using the latter in a function signature allows that function to take either kind of argument. See this question for more.

Use for loops.

When iterating over a collection, for loops are usually the best way. There's no need to keep track of mutating variables. If an index is needed, the enumerate method in the Iterator trait can be used.

Here's how I'd rewrite your loop.

for (x, col) in arr.iter().enumerate() {
    for (y, &elem) in col.iter().enumerate() {
        new_arr[y][new_height - x - 1] = elem
    }
}

Add tests

Before I even touched your code, I made sure to add at least one test case. That alone caught the bug that I mentioned above. Adding more was very helpful when figuring out how the width and height worked (see the first item in Miscellaneous below). Just as a template, you can use

#[cfg(test)]
mod tests {
    use super::*;

    fn my_test() {
        // Use things like `assert!` and `assert_eq!` to verify the output of your functions
        // ...
    }
}

Tests can be run with cargo test.

Miscellaneous

This may just be personal preference, but when I see a 2-dimensional array like

vec![
    vec![1, 2, 3],
    vec![4, 5, 6],
]

I think of this has having a width of 3 and a height of 2. That is, the first row is [1, 2, 3] and the second row is [4, 5, 6]. Indexing at (x, y) is arr[y][x] (first access yth row, then xth column). From what I can tell, you've reversed this. For example, vec![vec![filler; height as usize]; width as usize] would have a height of width and a width of height in my convention.

Note that rotating the vector switches the role of height and width, so new_width is the height of the original and new_height is the width of the original.

The u8/usize problems were largely solved by rewriting the loop, but in general, I'd suggest just sticking with one type. There's no reason for create_new_filled_2d_vec or for_each_xy to take u8 arguments. That just leads to unnecessary conversions. Since the length of a vector is always usize, it makes sense to just use usize everywhere.

If you want to use arrays, you'll eventually be able to use const generics to accomplish this. For now, they'll need to be dynamically allocated as Box<[T]>. You can produce a Box<[T]> from a Vec<T> using the as_boxed_slice method. Since the only difference between this and Vec<T> is the capacity field, Box<[T]> is fairly rare in practice. The benefit isn't very large.


Quality of random numbers

You are generating a random integer in a range with the method

private int generateRandomInRange(int min, int max) {
  return new Random().nextInt((max - min) + 1) + min;
}

This method creates a new Random object each time it is called. This is not a good idea. A random number generator should only be instantiated once and be reused throughout the application.

There is a FindBugs warning for exactly that (emphasis mine):

  This code creates a java.util.Random object, uses it to generate one random number, and then discards the Random object. This produces mediocre quality random numbers and is inefficient.

What you want instead is to have a single Random object. You could create it as a constant and then reuse it, like this:

private static final Random RANDOM = new Random();

private int generateRandomInRange(int min, int max) {
    return RANDOM.nextInt((max - min) + 1) + min;
}

But, in this case, since you're using it to return a random integer in a range, it would be even simpler to use the built-in ThreadLocalRandom class:

private int generateRandomInRange(int min, int max) {
    return ThreadLocalRandom.current().nextInt(min, max + 1);
}

This will directly return a random integer in the range [min, max].

Pre-allocating the StringBuilder

Small nit-pick, but you're using

StringBuilder builder = new StringBuilder();

to instantiate the StringBuilder. Since we know that the result will have 5 characters, we might as well initialize it with that:

StringBuilder builder = new StringBuilder(5);

It will create in memory an array of 5 characters instead of 16 (which is the default). As commented by Insane, you could extract that 5 (along with the 2 and 3 in the for loop) into a constant (named, for example, ROBOT_NAME_LENGTH).

Variable scope

In your generateName method, you have:

int i;
for (i = 0; i < 2; i++) {
  builder.append(ALPHABETS.charAt(generateRandomInRange(0, 25)));
}
for (i = 0; i < 3; i++) {
  builder.append(generateRandomInRange(0, 9));
}

which first declares i and uses it afterwards. There is no need to do that and it is a lot clearer to just have

for (int i = 0; i < 2; i++) {
  builder.append(ALPHABETS.charAt(generateRandomInRange(0, 25)));
}
for (int i = 0; i < 3; i++) {
  builder.append(generateRandomInRange(0, 9));
}

About the unicity of the names

Currently, you are storing all the generated names inside a Set. This is great because you can then check in constant-time if a given name was already generated. The small hiccup is that you will keep generating names until you find one that hasn't been generated before.

I don't see an easy way to optimize that or do better. The brute-force solution of generating all possible names up-front is possible in this case (since there are "only" 26 * 26 * 10 * 10 * 10 = 676000 possibilites) but not very pretty, and it wouldn't scale well at all.

Your solution is the best with regard to difficulty to write / understand versus the time it takes to generate the name. I tested with by generating a name for all the 676000 possible robots and it did it in a couple of seconds.

However, it leads to a possible bug.

Possible bug

There are only 676000 possible names. This means that if you want to name the robot 676001, your code will loop forever: it will try again and again to generate a name and will never terminate since they have all been generated.

A possible solution is to test whether all the names have been generated: if it is the case, you can simply clear the generated names set (remove all values). The problem description says:

  Your solution should not allow the use of the same name twice when avoidable.

In the case when they have all been generated, it is unavoidable, and one solution could be to decide to start again from 0. Another solution could also be to simply return one by one the already generated names (since we know they are unique) and not generate them again.

Oh, and also, generatedNames should be named GENERATED_NAMES since it is declared as static final.


Trying to grasp OOP Rock, Paper, Scissors program

Your Player and ComputerPlayer are good, with a very sensible use of inheritance. The NewGame is a bit of a mess, though; you have a tight coupling between the class and some sort-of-separate functions, with global variables (traditionally a bad sign), and the players aren't really related to the game.

Here's one alternative:

from random import randrange

class Game(object):

    OUTCOMES = {(1, 1): 0, (2, 2): 0, (3, 3): 0, # tie
                (1, 2): -1, (2, 3): -1, (3, 1): -1, # p1 lose
                (2, 1): 1, (3, 2): 1, (1, 3): 1} # p1 win

    def __init__(self, num_rounds):
        self.num_rounds = num_rounds
        self.human_player = Player()
        self.comp_player = ComputerPlayer()

    def play(self):
        for _ in self.num_rounds:
            outcome = self.OUTCOMES((self.human_player.choose(),
                                     self.comp_player.choose()))
            if outcome == 1:
                self.human_player.score += 1
            elif outcome == -1:
                self.comp_player.score += 1
        if self.human_player.score > self.comp_player.score:
            print "You won."
        elif self.human_player.score < self.comp_player.score:
            print "The computer won."
        else:
            print "It was a tie."

class Player(object):

    def __init__(self):
        self.score = 0

    def choose(self):
        while True:
            try:
                i = int(raw_input("Rock [1] Paper [2] Scissors [3]"))
            except ValueError:
                print "Must be an integer."
            else:
                if i in range(1, 4):
                    return i
                print "Must be between one and three."

class ComputerPlayer(Player):

    def choose(self):
        return randrange(1, 4)

if __name__ == '__main__':
    while True:
        try:
            num_rounds = int(raw_input("How many rounds? "))
        except ValueError:
            print "Must be an integer."
        else:
            break
    Game(num_rounds).play()

Note the following:

No more global - we play the Game directly and both Players belong to it, so everything is accessible within the instance methods;
All Games use the same OUTCOMES, so I've made that a class attribute, and the dictionary lookup makes working out who won much easier;
Input validation for the number of rounds and the human player's choice, so the program doesn't crash if they type 'foo';
No need for special methods to increment a player's score, you can access it directly; and
All the logic for playing is now in the Game itself.

A few places for further improvement (so you can have some of the fun):

The choose instance methods don't use any class or instance attributes, so perhaps they should be static methods instead;
The Players now seem too closely coupled to the Game - if choose took a choices argument (e.g. {1: 'rock', 2: 'paper', 3: 'scissors'}, which could be another Game class attribute) the coupling would be reduced; and
It doesn't tell you much about the outcome now - if OUTCOMES included e.g. {(1, 2): (-1, "paper wraps rock"), ...} you could add more feedback to the user.

Once those changes are made, you should be able to define e.g.:

class HarderGame(Game):

    CHOICES = {1: 'rock', 2: 'paper', 3: 'scissors'
               4: 'lizard', 5: 'Spock'}

    OUTCOMES = {(4, 5): (1, "lizard poisons Spock"), ...}

with everything else inherited (if you don't know the outcomes, see e.g. Wikipedia), and play it exactly the same:

HarderGame(num_rounds).play()


Checking if an array element exists in a JS object

First of all, don't use for-in on arrays. for-in will loop over all enumerable properties, including non-index properties. Also, for-in order is not guaranteed. If you need a loop to go over array items only and in order, use for/while. Alternatively you can use array.forEach.

There's no way (that I know of) to remove that second loop, since you need to go over each selected property for each person in data. What you could do though is use native array methods. This way, you avoid the extra boilerplate that comes with loops like not going over the actual number of items.

What you really want is array.map. It's primary purpose is to create a new array based on another array, essentially a 1:1 transformation. In your case, you need to create an array that contains the same items but only selected properties.

For the inner loop, I suggest array.reduce. One use case for reduce is to condense an array of values into a single value. In this case, the selected keys into an object only containing the selected keys and their values.

var selectedColumns = ['first', 'last', 'city'];

var data = [{
    first: "Mike",
    last: "Ross",
    dob: "05/26/1978",
    city: "Washington DC",
    state: "DC",
    zip: 22904
  },
  {
    first: "John",
    last: "Henderson",
    dob: "11/06/1988",
    city: "Iowa City",
    state: "IA",
    zip: 52401
  },
  {
    first: "Nina",
    last: "Barkley",
    dob: "01/16/1968",
    city: "New York",
    state: "NY",
    zip: 11308
  },
  {
    first: "Jessie",
    last: "Kuch",
    dob: "02/02/1956",
    city: "Des Moines",
    state: "IA",
    zip: 55432
  },
  {
    first: "Jenny",
    last: "Terry",
    dob: "012/28/1988",
    city: "Miami",
    state: "FL",
    zip: 83943
  }
];

const onlySelected = data.map(person => {
  return selectedColumns.reduce((c, key) => {
    return { ...c, [key]: person[key] }
  }, {})
})

console.log(onlySelected)


Is this an appropriate use of abstract classes and inheritance?

Is this a decent use of abstract classes and inheritance?

Yes, it's decent. My personal preference is, rather than using ABC, simply

def process(self):
    # Method to process frames.
    # Method will be overwritten by subclasses
    raise NotImplementedError()

You can also simplify this somewhat by

Renaming Video to ColorVideo
Deleting the class that is now called ColorVideo
Rather than making process abstract, make it "virtual" (in C++ parlance): make it take the contents of what is now get_raw_frame and delete get_raw_frame
In the child GrayVideo, override process to call its super().process and convert the results

If you're concerned that this more minimal representation is confusing (i.e. why is a GrayVideo a ColorVideo?) then you can keep Video as a conceptually abstract class, and simply

class ColorVideo(Video):
    pass

Other stuff:

end should actually be the __exit__ of a context manager;
it looks like your source argument should take a default of 0;
make a main function called by standard __name__ guard.


Shortening Oracle SQL containing several unions

Found a possibility employing UNPIVOT
WITH
x(id, yr, more_info) AS
    (SELECT 1, 2020, 'info1' FROM DUAL UNION
     SELECT 2, 2021, 'info2' FROM DUAL UNION
     SELECT 3, 2021, 'info3' FROM DUAL UNION
     SELECT 4, 2020, 'info4' FROM DUAL )
,
n(n_id, n_id2, n_year) AS
    (SELECT 1, 3, 2021 FROM DUAL UNION
     SELECT 2, 4, 2021 FROM DUAL )

SELECT * FROM x
UNION
SELECT id2, n_year, more_info
FROM (SELECT *
      FROM x
      WHERE (id, yr) IN (SELECT id, MAX(yr)
                         FROM x
                         GROUP BY id) ) t1,
     (SELECT * FROM n
      UNPIVOT(
          id2
          FOR id_type
          IN (n_id, n_id2) ) ) t2
WHERE t1.id = t2.id2


Calls one column of a dataframe, turns it into an array and plots it

I added a "for" loop. :)

#Code to create fake data
df = pd.DataFrame(np.random.rand(10,5), columns=list('abcde'),
index=list('nopqrstuvw'))
df.columns.name = 'level_0'
df.index.name = 'level_1'

#I load an array of shape (10, 2)
sensors_pos = sio.loadmat('/home/Coord_Slp_2D.mat')['Cor']

# I extract each column. From "a" to "e"
df1=df['Total Acc'].round(4)*100
df2=df1.reset_index().pivot('level_1', 'level_0', 'Total Acc')

for column in df2:
    data=df2[column].values
    fig = plt.figure(figsize = (8,5))
    ax,_ = plot_topomap(data, sensors_pos, cmap='viridis', show=False)
    fig.colorbar(ax)
    fig.show()


The page you linked to has pseudocode, and it does s = ((s × s) − 2) mod M. And right below the pseudocode it says:

Performing the mod M at each iteration ensures that all intermediate results are at most p bits (otherwise the number of bits would double each iteration).

Do that and it'll be much faster.
And better use the same variable names as in the page you referenced, don't make up new ones, that just obfuscates the connection.


Automate the Boring Stuff - Collatz Exercise

A few simple observations:

    if n % 2 == 0:
        ...
    elif n % 2 == 1:
        ...

Here, we know that if n % 2 isn't 0, it must be 1, since n is an integer.  So that elif can be simply else, making it simpler to read.  More experienced programmers will reverse the test, knowing that 1 is the only truthy result of n % 2, so write if n % 2: ... ; else ....

    if ...:
        ...
        print (n)
    else:
        ...
        print (n)

The print that's present in both branches could be placed after the if/else, since it doesn't depend on the condition.
The results of the arithmetic expressions are already int, so no conversion is necessary.
The if/else could be reduced to a single line:

n = 3 * n + 1 if n % 2 else n // 2

but to me, that looks less clear, so I don't recommend that level of terseness here.

Modified code

Applying the observations above, I get a simpler version of the function:

def collatz(n):
    while n > 1:
        if n % 2:
            n = 3 * n + 1
        else:
            n = n // 2
        print(n)


Function dependence on iteration variable of another function

This largely depends on your use case. If there are situations that call for only calculating based off of certain values or subsets of values, then the second version should be preferred, but if you are always going be calculating all values, then the first should be preferred.


Frequency form to case form - unexpected values in table

The behavior seems to be due to a bug in the expand.dft function. I created a simple function myfun that allows you to create a matrix similar to the one created by expand.dft.

myfun <- function(x, freq = "Freq") {
  # repeat the row indices according to `freq`
  idx <- rep(seq(nrow(x)), as.integer(x[, freq]))
  # expand matrix and ignore `freq` column
  x[idx, colnames(x) != freq]
}

Note that is function is not meant to replace expand.dft but works for simple cases only.

Try it with your data set rtable:

rtablecase <- myfun(rtable, freq = "freq")

The result:

head(rtablecase)
#   Race    Party
# a "White" "Dem"
# a "White" "Dem"
# a "White" "Dem"
# a "White" "Dem"
# a "White" "Dem"
# a "White" "Dem"


Finding ways to achieve a target sum using recursion

A couple of quick notes:

Methods in C# should be named PascalCase.
mainfunction isn't a great name. It should be named by what it does
mainfunction_slave is also a bad name, you shouldn't use underscores in method names in C#

You need to plan your recursion:

What's the base case?
What can you make smaller/approach the base case as you go?

The base case is fairly trivial:

If the array has 1 element, return whether that element matches the target.

static int CalculateCombinations(int[] numbers, int target)
{
    // trivial solution:
    if (numbers.Length == 0)
    {
        return 0;
    }

    // base case:
    if (numbers.Length == 1)
    {
        return numbers[0] == target ? 1 : 0;
    }
}

Cool, we could now (or even before this) write a test or two:

[TestMethod]
public void CaclculateCombinationsWithSingleElement()
{
    var numbers = new[] { 1 };
    var target = 1;

    var result = YourClass.CalculateCombinations(numbers, target);

     Assert.AreEqual(1, result);
}

(I don't use MSTest myself so not sure if the above is 100% correct).

Now you need to think about how to split the problem up. Recursion on a list is almost always making the list smaller at each step.

The number of combinations is:

var count = 0;
for (var i = 0; i < numbers.Length; i++)
{
    // are we at a solution ?
    if (numbers[i] == target)
    {
        count++;
    }

    // find solutions that sum to the current target - the current number
    // on remainder of the array
    var subArray = numbers.Skip(i + 1).ToArray();
    count += CalculateCombinations(subArray, target - numbers[i]);
 }
 return count;

If you only consider positive integers, it looks like target is getting smaller too but actually only the numbers array is getting 'smaller' as negative numbers or 0s don't make target closer to 0.

That makes the whole solution something like:

static int CalculateCombinations(int[] numbers, int target)
{
    if (numbers.Length == 0)
    {
        return 0;
    }
    if (numbers.Length == 1)
    {
        return numbers[0] == target ? 1 : 0;
    }

    var count = 0;
    for (var i = 0; i < numbers.Length; i++)
    {
        if (numbers[i] == target)
        {
            count++;
        }
        var subArray = numbers.Skip(i + 1).ToArray();
        count += CalculateCombinations(subArray, target - numbers[i]);
    }
    return count;
}

Update:

On reflection, the base case can simply be an empty array. We don't need to worry about the length = 1 case because it would have been counted in the for loop anyway.

That means the code can be simplified to:

static int CalculateCombinations(int[] numbers, int target)
{
        if (numbers.Length == 0)
        {
            return 0;
        }

        var count = 0;
        for (var i = 0; i < numbers.Length; i++)
        {
            if (numbers[i] == target)
            {
                count++;
            }
            var subArray = numbers.Skip(i + 1).ToArray();
            count += CalculateCombinations(subArray, target - numbers[i]);
        }
        return count;
    }

I'd recommend The Little Schemer as a great introduction to recursion. One of the commandments is:

  Simplify only after the function is correct.

So I don't feel too bad about overcomplicating it the first time :)


Repetitive jQuery click functions for changing multiple elements

As far as I can tell, the code simplifies as follows :

$("#timeframe_pills_container li a").click(function(e) {
  var $li = $(this).closest("li");
  var index = $li.index();
  var $dropdown = $("#timeframe_dropdown_container");
  $li.addClass("active").siblings().removeClass("active");
  $dropdown.find("li").eq(index).addClass("active").siblings().removeClass("active");
  $dropdown.find(".dropdown-toggle p").text($(this).text());
}).eq(0).click();

$("#timeframe_dropdown_container li a").click(function(e) {
  var index = $(this).closest("li").index();
  $("#timeframe_pills_container li a").eq(index).click();
});

.eq(0).click() establishes the intial state, so you don't need to set class="active" (twice) or the button text, in HTML.


Structuring code that shells out to an external script

Overall looks like a good start, some thoughts I had:

If I were implementing this class I probably wouldn't just store the output as a string, I'd parse it in a way that callers would be able to use it effectively.  For example, does it output total time, data transferred, files copied, etc.?  If you're going to try to use this data, I think this class (or a class used by this class) should have the responsibility to process that data, not the caller.
Some prefer the system() method over in-line backticks, for readability, but that's preference.
Never raise Exception, either raise RuntimeError by omitting the first parameter to raise or fail, or create a new exception class (with RuntimeError as a parent) for your purpose.  Similarly you should (in almost all cases) never rescue Exception.
In one of the codebases I work on were have an entire class dedicated to executing commands locally.  One reason we do this is that you can't isolate stdout from stderror using backticks or system(), so we use the popen4 library and generate a Result class that has the exit code, stdout and stderr.  The stderr may be useful if you're trying to relay to the caller what failed exactly.  The caller may want to retry a timeout, but not an authentication issue, for example.

I don't know how widely used or important this class is for your company, so feel free to file any of these under "over-engineering" as appropriate :-).


Creating objects and putting them into std::list

If Item has subclasses, then make the ~Item() destructor virtual.

If Item has a copy constructor, and is not a superclass of a subclass, then you can store a copy of the item (not pointer to the item) in the list:

list<Item> listOfItems;

Item item;
item.id = itemCrowbar;
listOfItems.push_back(item);

In that case, you won't need to delete Item pointers before the list is destroyed.

However, if Item has subclasses, then this might be legal but a bug (called 'object slicing'):

list<Item> listOfItems;

SubclassOfItem item;
item.id = itemCrowbar;
item.extra = "hello";
listOfItems.push_back(item);

Or you can create a list of 'smart pointers' (std::unique_ptr) to items: which behave like pointers to Items except that you don't need to delete the Item (the Item is deleted when the smart pointer which contains it is destroyed).


The easiest way would be to define a constant integer array holding the ids:

private static final int[] ids = { R.id.kn1_radio_group, R.id.kn2_radio_group, R.id.pr1_radio_group, /* and so on... */};

And then using the same method as in my answer to your previous question.

However, your naming of these RadioGroups tells me that there might be another structure here. And I also suspect that there is more to your application than what we see here. So what you really should do is to think about the structure of your variables; Should a kn be a class? Should kn4 be an array on it's own, or should perhaps kn be a two-dimensional array (one dimension for the number and one for the letter. These are questions that none of us currently can answer considering the lack of context we have about your application. If you would explain a bit more about What your application is for and what a kn / ap RadioGroup is, then we might help you more. You probably have some reasons for naming the radio groups the way that you do, in which case a different structure than an array might be more useful.

Also, I would like to add something: Why not let the fragment take care of it's own initialization of the RadioGroups? Is perhaps the RadioGroups a part of the fragment's view already? If so, then there is no need to use all these setter methods for it.


I'm unsure what you mean by saying "improve the user interface". AFAIK Game of life doesn't have much of a user interface as it's a simulation that only displays the grid and whatever happens on it.
However there are some other things that can definitely be improved.

Don't use using namespace std
Generally functions in C++ are lowercase
Think about better variable names.
x and y might be acceptable but t and z are probably not the best names.
Prefer using \n over std::endl
Prefer prefix over postfix operator
Don't compare to booleans. Instead do if (condition) and
if (!condition).
You might want to use vectors for your board instead of arrays.
Don't use global variables (which you don't need when you're using vectors)
There is another way to write an endless loop which is a for loop without conditions for (;;) (read as forever).
Which one is better is highly opinion based however.
Your cluster of for loops is quite hard to grasp. It would improve readability and understanding if you break it up into smaller parts. For example you could write a function to iterate over the cells and for every cell call another function that checks the adjacent ones for live cells.


Determine hour in other countries with generated random time

DateTime london = DateTime.Now;

DateTime timeInLondon = london.AddMinutes(generator.Next());

This can be rewritten as

var timeInLondon = DateTime.Now.AddMinutes(generator.Next());

You can use var on the other lines as well.

Removing the london variable makes it less likely you make mistakes like this:

Console.WriteLine("London: " +london.ToShortTimeString()...

Where you actually output DateTime.Now as it was at the start of your program, but not, as you probably wanted, the randomized timeInLondon!

Now about your random time.

Your seconds will obviously not be random. Apart from that, you only add a positive random number, with a maximum of around 4085 years. As such, I guess that is enough to make the resulting time more or less random as far as hours and minutes are concerned. I would opt for adding seconds though. You still would add anything up to 68 years to the current time, still probably ending up with a random-enough distribution over the 24-hour clock, including seconds:

var timeInLondon = DateTime.Now.AddSeconds(generator.Next());

Finally, if you want to nitpick, it would be better to use time zone information instead of hard-coding magic numbers like 5 or -8. Time zones do not at all times have the same number of hours difference between them(*).

You could use TimeZoneInfo.ConvertTime Method (DateTime, TimeZoneInfo, TimeZoneInfo)

Keep in mind that if you opt for that, you might need to rethink randomisation of your time, since the date comes into play to determine the time in other places.

(*)Not all countries start and end DST on the same dates, some countries do not even use DST, and on the southern hemisphere, DST goes "the other way around". This may all be irrelevant for the locations you picked, though.


You can simplify your code to this:

var palindromesCopy = palindromes.ToList();
palindromes.RemoveAll(x => palindromesCopy.Any(y => x != y &&
                                               y.Contains(x)));

If you want to remove duplicated strings as said by @MoonKnight in comments, just call Distinct on palindromes after removing.


Winning shouldn't be considered an error.  If you want a way to exit from the for-loop, use #:break.  But for and set! aren't really idiomatic in Lisp-like languages.  Instead, it is more common to use recursion and let, which conform to the functional programming paradigm.

In num_message, you can use a cond instead of nested ifs.

I'm not happy about the use of a string comparison to detect the winning condition: the number-guessing-game function needs to know what congratulatory message to expect from num_message.  You've worked around that problem by defining some string constants, which gives them more importance than one would expect.

It would be more elegant for num_message not to have NUM fixed, and for number-guessing-game not to have NUM and TRIES fixed.

The number-guessing-game function would be clearer if it were broken up, because it is actually doing two things: play one guess, and conditionally repeat.

The print calls should probably be displayln instead, to also write a trailing newline.

Conventionally, words in identifiers are separated-by-hyphens rather than underscores.  Closing parentheses don't get their own line.

#lang racket

(define NUM 12)
(define TRIES 6)

(define (num-message delta)
  (cond [(< delta 0) "... Too low ..."]
        [(> delta 0) "... Too high ..."]
        [else        "Correct! Well guessed!"]))

(define (guess-number target)
  (let ([delta (- (read) target)])
       (displayln (num-message delta))
       (zero? delta)))

(define (number-guessing-game target tries)
  (cond [(zero? tries)         (displayln "Too many attempts")]
        [(guess-number target) (displayln "You won")]
        [else                  (number-guessing-game target (- tries 1))]))

(number-guessing-game NUM TRIES)


Your code is good, but I have some suggestion to improve it.

HTML

You used semantic HTML for the header and footer, but for the main content you did not use any semantic html. If you use semantic HTML tags for your main content like main tag and section tag, it will be more interesting.

In the below picture you can see you followed everything except the main content.

CSS

You can order your CSS code. I would order by layout; first your body CSS, then your header CSS and then finally your footer CSS.
Alternately you can order by other things like alphabet.

body{
  position: relative;
  text-align: center;
  font-size: 14px;
}

a{
  color: black;
  text-decoration: none;
}

div{
  word-spacing: 40px;
  display: inline-block;
}

.right{
  float: right;
}

.left{
  float: left;
}

#signin{
  background-color: blue;
  color: white;
  border-radius: 3px;
  border: 1px solid blue;
}

.middle{
  margin-left: 130px;
  padding-top: 200px;
}

 #userinput{
  height: 30px;
  width: 500px;
  border-radius: 24px;
  box-shadow:5px 10ox;
}

button{
  line-height: 28px;
}

#searchbutton{
  margin-top: 20px;
  opacity: .60;
  padding: 0 12px;
}

footer{
  padding-top: 200px;
}


For the css part, I started from the updated fiddle @cimmanon provided. I basically agree with all the things he added. I also went ahead and turned your markup into a ul as he (or she) correctly suggested. I would like to provide my own insights as well:

You are closing your img tags, however they can never contain any content so the closing tags are redundant (and perhaps even invalid). You can either make them self-closing (<img ... />) or just omit them in html5.
You are using a lot of different classes in your markup. There is no real need for that; all it does is make your code longer and harder to read. I would go for selectors like .image-gallery img instead of .gallery_image. I admit that in theory this is slightly less performant, but I doubt you'll be able to see, or even measure, the difference. And it makes your markup a lot easier to maintain (less code when adding slides, and less chance of making typos in all those class names).
I would definitely not animate the left property, but go for a transform: translate3d in stead. It is a lot better for performance as explained here.
I would use css transitions, instead of the jQuery animate. It is again better for performance, and it I believe it makes your code a lot better structured. If you decide to change anything in your animation, you just have to update your css and you don't have to start digging into your javascript. I'm a big fan of only using Javascript for thing that can't be done through css.

I went ahead and applied my suggestions to the fiddle, which you can find here: http://jsfiddle.net/eL0vaL44/3/


Converting a list of integers into a two-dimensional array in Java

You can use streams:

Object[][] data = studentList.stream()
        .map(studentId -> new Object[]{studentId})
        .toArray(Object[][]::new);


Usage of lens for concise update of records

updateWorld of @Changaco can still be improved. I'll show it gradually so you can see what's going on.

Firstly, we can eliminate duplication in case statement and use lens composition to eliminate second over:

quantity Polymorph = quantityPolymorph
quantity TeamPlayer = quantityTeamPlayer
quantity LoneWolf = quantityLoneWolf

updateWorld :: Fighter -> World -> World
updateWorld fighter w = increment (quantity fighter) w where
        increment field = over (quantities . field) (+1)

Then we can go pointfree. Pointfree is all about readability so don't do it whenever you feel readability is harmed. With coding experience more and more code will become readable for you.

updateWorld = increment . quantity where
    increment field = over (quantities . field) (+1)

Then we replace over with a more specialized version of it from Control.Lens.Setter:

updateWorld = increment . quantity where
    increment field = (quantities . field) +~ 1

Now it seems beneficial to inline increment. I'll do in 2 steps. First, I make the actual parameter of increment explicit:

updateWorld field = increment $ quantity field where
    increment field = (quantities . field) +~ 1

Then I inline:

updateWorld :: Fighter -> World -> World
updateWorld field = (quantities . quantity field) +~ 1

Another way to improve could be to use a Map or an Array for QuantityHolder:

data World = World { _quantities :: M.Map Fighter Quantity }

Below is full source using Map:

{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

import Control.Lens
import System.Random
import qualified Data.Map as M
import Data.Maybe

newtype Quantity = Quantity Integer
    deriving (Eq,Num,Ord,Random,Show)

data Fighter = TeamPlayer
             | LoneWolf
             | Polymorph
               deriving (Eq,Ord,Show)

data World = World { _quantities :: M.Map Fighter Quantity }
    deriving (Show)
$(makeLenses ''World)

atFighter i = at i . iso fromJust Just

updateWorld :: Fighter -> World -> World
updateWorld field = (quantities . atFighter field) +~ 1

But it really depends on the usage scenarios you plan for World.

Also note that lens interact with state monad transformer pretty well, so you may consider

updateWorldS :: Fighter -> State World Quantity
updateWorldS field = (quantities . atFighter field) <+= 1

Note that World is not passed in explicitly any more. And the type is more general than that, so you can combine state with IO and other monads should you wish:

updateWorldS :: MonadState World m => Fighter -> m Quantity

If you want to be able to report any extra value from updateWorld you can use the existing state monad:

updateWorldS :: Fighter -> State World Bool
updateWorldS field = (quantities . atFighter field) <+= 1 >> return errorBool where
      errorBool = False -- or True

Or MonadPlus if you don't want to just report failure without extra info:

updateWorldS field = (quantities . atFighter field) <+= 1 >> when errorBool mzero where
      errorBool = False

Or MonadError if you want to supply an error value (of any type):

updateWorldS4 field = (quantities . atFighter field) <+= 1 >> when errorBool (throwError "Game over")


constexpr Precalculate size of serialized data with templates and C++20 concepts

Stick with supporting the lowest common denominator
I don't see a difference in functionality in the GCC and MSVC version of your code, so I wouldn't bother writing two implementations. That is just repeating yourself in a way.
Also note that it's not really GCC vs MSVC, it is some version of GCC and some version of MSVC that you checked, that doesn't mean all versions of those compilers have the same difference. Older versions of GCC might also not support some C++20 features that you used, and newer versions of MSVC will likely support those at some point.
Also, what about Clang, ICC and all the other compilers out there?
Use feature testing macros
If possible, use feature testing macros instead of testing for compiler brand to check whether you can use a given feature.
You can't serialize all containers by just looking at their contents
Containers can be more than just their contents. The ordered STL containers for example allow you to provide them with a functor that tells them how the elements are to be ordered. And if you go outside the STL, consider what happens if you have for example a class that implements a binary tree, and that provides begin() and end() functions to traverse the tree in-order. If you serialize just the elements, you miss the way the nodes in the tree are linked together, which might be significant information.


I'd like to see if this is a reasonable solution, or is just plain terrible.

I wouldn't say it is "terrible" - mostly because it works and doesn't appear to be very inefficient. However, there are some improvements that can be made.

use strict equality comparison - i.e. === when comparing values. That way it won't need to convert the types.

Style Guide Consider following a style guide. Many common style guides advise separating keywords with a space - e.g. if ( instead of if(.

Use consistent indentation The first and last lines within the for loop are not indented, while the other lines between them are, though maybe it was the case that your code was indented properly but when you pasted here it was thrown off because of the markdown formatting...

Abstract logic into a function As Paul's answer suggests: you can put the core logic into a function that returns the output but doesn't handle outputting the value (e.g. to the console). This allows such code to be atomic and testable - congruent with the Single Responsibility Principle. Also, the return statement can eliminate the need for else keywords within a function. One drawback is that calling a function on each iteration may slow down operations but should be negligible for a set of numbers 1 through 100.

Updated Code
Consider the modified code below, utilizing the feedback above. I also used this code in the code contained in my recent question: Fizzbuzz with dynamic height container
Note: the inline console in the snippets is truncated to ~50 lines, but the complete console log should be visible in your browser console.

function fizzBuzz(value) {
    if (value % 15 === 0) { return "FizzBuzz"; }
    if (value % 3 === 0) { return "Fizz"; }
    if (value % 5 === 0) { return "Buzz"; }
    return value;
}
for (let i = 1; i <= 100; i++) {
    console.log(fizzBuzz(i));
}

One option I did consider is to minimize the number of modulo operations, append to the output string instead of outputting it. If you are trying to optimize for speed, this might not be the approach to take because appending to the string may be much slower than doing an extra couple modulo operations. Try a comparison in this jsPerf test.

function fizzBuzz(value) {
    let output = "";
    if (value % 3 === 0) { output += "Fizz"; }
    if (value % 5 === 0) { output += "Buzz"; }
    return output || value;
}
for (let i = 1; i <= 100; i++) {
    console.log(fizzBuzz(i));
}


The system you have in place is efficient in the sense that it offloads the network-based work on to an AsyncTask, and the callback updates the wallpaper.

You don't give the details of your ImageLoader AsyncTask, but you could neaten a few things up by putting them in to there... and it would look something like:

public ImageLoader extends AsyncTask<String, Void, BitMap> {

    private final Context context;

    ImageLoader(Context context) {
        this.context = context;
    }

    public BitMap doInBackground(String urlpath) {
        // set the bitmap... do the work.
        return bitmap;
    }

    public void PostExecute(BitMap result) {
        try {
            WallpaperManager.getInstance(context).setBitmap(result);
        } catch (....) {
            ....
        }
    }

}

With the above task, it becomes a simple thing to do in the onCreate of the MainActivity:

new ImageDownloader(getApplicationContext()).execute(url);

That's the way to make it neat....


Just looking over the two functions, I would probably say the first function is a better practice.  It's shorter (meaning it's more maintainable), it uses fewer variables (which can cause less confusion), and does the same thing as the second function. Overall the advantage is that the first function is just shorter.

In terms of speed/efficiency (if I had to guess), it looks like the first function would also be a bit faster as well (though not by very much at all). To know for sure which one is faster, test the function calls with OpenCV's methods double getTickCount() and double getTickFrequency().

getTickCount gives you the number of clock cycles after a certain event, e.g., after machine is switched on.

A = getTickCount()  // number of clock cycles from beginning (for example, 100)
getY(image)      // do whatever process you want
B = getTickCount()  // number of clock cycles from beginning (for example, 150)

C = B - A           // number of clock cycles for processing (150-100 = 50)

Now you want to know how many seconds are these clock cycles. For that, you want to know how many seconds a single clock takes, i.e. clock_time_period. If you find that, simply multiply by 50 to get total time taken.

For that, OpenCV gives second function, getTickFrequency(). It gives you frequency, i.e. how many clock cycles per second. You take its reciprocal to get time period of clock.

time_period = 1/frequency.

Now you have time_period of one clock cycle, multiply it with 50 to get total time taken in seconds.