I'm skeptical of the value of this design pattern, for two reasons:

The Repository class is basically just a Python dictionary.  You never use Repository.all() anyway.
Repository is actually a glorified namespace.  It's a disguised mechanism for you to make a bunch of global variables.

Additionally, I see some puzzling aspects to the code:

Why would UserRepo() make its .validator configurable?  And why would it default to None?
Since UserRepo and CompanyRepo contain nearly identical code, why not consolidate them?  At the least they should have a common base class.  Maybe they could even be handled by one class.
The WorkerAdder object seems contrived.  Why split the work between a WorkerAdder() constructor and an .add() method?  Why is the company name and address hard-coded?

Some minor remarks:

It's customary to chain to the superclass constructor first, not as the last statement in the subclass's constructor.
Serialization means turning an object into a string representation; your User.serialize() returns a dictionary instead.  The string representation needs to  contain enough detail to reconstruct the object exactly; your User.serialize() omits the .created_at and .update_at timestamps.

In summary, Repository is just a dictionary that serves as a namespace for global variables.  There's not much point to it, since symbol tables in Python are also dictionaries.  UserRepo and CompanyRepo do serve a purpose, but you would have to reinvent the wheel (implementing the persistence mechanism, for example) to make them useful.  You might as well use a real database (which could be as simple as sqlite) with an ORM.


Achieving a never-ending loop of game tasks

I just want to say that I review C# code style a lot on this site, and this code made me very happy for many seconds, until I spotted this:

public async Task Start(Table t)

So close!

t should, of course, have a much more descriptive name here. You've even done that elsewhere, so it is most likely an oversight on your part.

I don't like underscore notation personally as it smells strongly Hungarian, but it's a commonly-accepted system in C# so I don't have a leg to stand on.


Your code looks OK to me, very clear and organised.

It's more important to minify your code to decrease load time. There's a whole bunch of minification tools on the Internet.


Regarding the desire to make an implementation of the $q service, it is useful to consider that angular's $q is a stripped down version of the excellent promise library q by, kriskowal which you can leverage independently of angular. You can also achieve it through other promise implementations such as bluebird and with native ES2015 promises where available.

As for the implementation itself, I strongly recommend removing the serialOrParallel and doing one of the following.

Turn you function into an object which exposes a parallel and a sequential property. Ex:

var forEach = {
    parallel: function () {...},
    sequential: function() {...}
}

Create 2 separate functions, one that traverses sequentially and one that traverses in parallel.

The reasoning behind this is that it makes the code clearer, removes the need for an exception, and makes it easier for consumers to do the right thing.

As @Roamer-1888 noted, In the serial case, it should be possible to construct returnValues in its entirety in the forEach loop without post-processing it.


Counting the total number of characters in an std::set

You should make the parameter to TotalLength const, so you can use it on constant sets. Since TotalLength does not modify its argument, there is no reason not to use a const reference.

Also this is a small thing, but I'd change the name of SumLength to AddLength as Sum to me suggests that it operates on multiple strings.

Other than that your code looks perfectly fine and straight forward.


Change UI display order of an ObservableCollection

To sort your ObservableCollection you should be using data-binding and let WPF do the work.

First let's fix the ComboBox that you currently populate manually. For the sake of this review I assume you use your code-behind file as a data-source that is bound to the Window via:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Next you need to tell the ComboBox where to find the items and how to display them:

<ComboBox
    ItemsSource="{Binding OrderOptions}"
    DisplayMemberPath="Description"
    SelectedValuePath="OrderBy"
    SelectionChanged="Selector_OnSelectionChanged">
</ComboBox>

It receives the values from the code-behind property (you of course would read the descriptions here with your reflection helpers):

public IEnumerable<OrderOption> OrderOptions
{
    get
    {
        return
            Enum
                .GetValues(typeof(OrderBy))
                .Cast<OrderBy>()
                .Select(x => new OrderOption { OrderBy = x, Description = x.ToString() });
    }
}

I created a helper object for this combo-box that looks like this:

public class OrderOption
{
    public OrderBy OrderBy { get; set; }

    public string Description { get; set; }
}

Now we need a list of videos:

private ObservableCollection<Video> _videos = new ObservableCollection<Video>(new[]
{
    new Video { Name = "Rambo", Rating = 3},
    new Video { Name = "Rocky", Rating = 8},
    new Video { Name = "Turbo Interceptor", Rating = 1}
});

where the Video is implemented as:

public class Video
{
    public string Name { get; set; }

    public int Rating { get; set; }
}

and the code-behind file has this property:

public ObservableCollection<Video> Videos => _videos;

Now comes the tricky part. You need to add a new resource to the resource-dictionary. This is a CollectionViewSource that initially will sort the items by Name.

<Window.Resources>
    <ResourceDictionary>
        <CollectionViewSource x:Key="SortedVideos" Source="{Binding Videos}">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="Name"></scm:SortDescription>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </ResourceDictionary>
</Window.Resources>

In order for this to work you need to add a new namespace:

xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"

Now you can bind a ListView to it:

<ListView
    ItemsSource="{Binding Source={StaticResource SortedVideos}}"
    DisplayMemberPath="Name">
</ListView>

You have probably noticed the combo-box has this Selector_OnSelectionChanged event handler that in code-behind is implemented like this to get the currently select OrderBy, then the switch is used to change the sorting by first clearing the current settings and adding a new one that changes the property of the Video object that is used for sorting. In this example I only used the Name and the Rating. Now each time you change the selection WPF will update the ListView and if you add or delete an item it will use the current setting to re-order it.

private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var colView = Resources["SortedVideos"] as CollectionViewSource;
    switch (((sender as ComboBox).SelectedItem as OrderOption).OrderBy)
    {
        case OrderBy.Name:
            colView.SortDescriptions.Clear();
            colView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
            break;
        case OrderBy.Rating:
            colView.SortDescriptions.Clear();
            colView.SortDescriptions.Add(new SortDescription("Rating", ListSortDirection.Ascending));
            break;
    }
}


Is my code fine in the areas of read and write?

for (int i = 0; i < package.size(); ++i)

I'd use for (auto& p : package) instead if the index (i) is not used for anything.

outFile << package[i].getPartId() << "," << endl;

Remember that std::endl flushes the stream. This is very minor, but I'd use a manual '\n' and then flush when the whole object is written.

bOutFile.write((char*)&package[i], sizeof(package[i]));

This is I do not like at all. Copying objects like this is problematic when you have objects with more complex data. I.e. pointers or dynamically allocated memory.

Take a look at serialization/deserialization, I found this read quite good concerning the topic: https://rubentorresbonet.wordpress.com/2014/08/25/an-overview-of-data-serialization-techniques-in-c/

Packet(int partId, string description, double price, int partCount

Make the passed arguments const references instead! (Otherwise an extra copy will be done)


Javascript filter class to hide and show content on data-attributes

The usefulness of creating a class is that you can have private variables.

Simply placing every thing in an object defeats that point.  Instead you should define everything in the protected part of the function and simply expose an external API with the return.

http://codr.cc/s/9b31baa5/js


Quaternion and Vector3 transfomation Math

If you want DRY the KISS way, I suggest substituting the if-chain..

if (movement == Vector3.left)
    transformModel.rotation = Quaternion.Euler(0, 270, 0);
else if (movement == Vector3.right)
    transformModel.rotation = Quaternion.Euler(0, 90, 0);
else if (movement == Vector3.back)
    transformModel.rotation = Quaternion.Euler(0, 180, 0);
else if (movement == Vector3.forward)
    transformModel.rotation = Quaternion.Euler(0, 0, 0);

..with a lookup map:

var rotationsEulerY = new Dictionary<Vector3, int>
{
    {Vector3.left, 270}, {Vector3.right, 90}, {Vector3.back, 180}, {Vector3.forward, 0}
};

void ChangeDirection()
{
    transformModel.rotation = Quaternion.Euler(0, rotationsEulerY[movement], 0);
}

You could do something similar for CorrectPosition using a predefined map of guard conditions and assignor actions.


Optimize printing massive strings to System.out with respect to time

Are you sure the bottleneck is the printing, as opposed to whatever new ClassThatBuildsOnBuilder(builder); is doing?
Is coordinates always going to have a width of four?
It appears you're building the whole string in memory, and then printing all your output at once at the end. While printing each line to standard-out individually may be slower, it also may take better advantages of the built-in output buffering. (Printing each word individually as you describe having originally done probably isn't a great idea.

Would something like this work?

  private void printRow(){
    System.out.format("#%.3f #%.3f #%.3f #%.3f%n",
      coordinates[0],
      coordinates[1],
      coordinates[2],
      coordinates[3]);

You could also try a Formatter, which would let you use a StringBuilder as you already are, but also use printf syntax.

Finally, I don't know how to take manual control of System.out's buffering behavior, but it's probably possible and may help.


Your implementation will not produce correct results in general because your recursive definitions are erroneous.

One should note that in case n = 0, result is 1.  In case of even n (or n = 2 i), one may write b ^ n = (b * b) ^ i.  In case of odd n (or n = 2 i + 1), one may write b ^ n = b * (b * b) ^ i.  Here's an implementation (using if's instead of cond and folding the two recursive steps into one):

(define (fast-expt b n)
  (if (= n 0) 1
      (* (if (= (remainder n 2) 0) 1 b) (fast-expt (* b b) (quotient n 2)))))

To make this definition iterative, use the accumulator, a, that is initially 1.  When n is even (n = 2 i), square b but keep a unchanged.  This maintains the property b ^ n = a * (b ^ 2) ^ i.  When n is odd (n = 2 i + 1), square b and multiply a by b.  This maintains the property b ^ n = (a * b) * (b ^ 2) ^ i.  Thus, we have:

(define (fast-expt b n)
  (fast-expt-iter 1 b n))

(define (fast-expt-iter a b n)
  (if (= n 0) a
      (fast-expt-iter (* a (if (= (remainder n 2) 0) 1 b)) (* b b) (quotient n 2))))


PLEASE do not do anything to the password prior to hashing it. Do not escape it. Do not trim() it. Just pass it directly to password_hash.

Secondly, you never fetch the hash from the database. That looks weird that you have a magic $dbpassword variable...

Third: Please use prepared statements. Escaping can be secure, but prepared statements are so much easier to verify and work with.

Fourth: Don't close the connection all over the place like that. Let it get closed for you by the script end, that way you don't need to reconnect multiple times in the same script.

Fifth: Please use consistent indentation. It will make your life a LOT easier.


There isn't much (that I see) to say about this code; it is mostly straightforward and easy to understand. Therefore, my review will be fairly short.

Refactoring

Take a look at your upDown and downUp functions. These are very similar. The only differences are:

function downUp() {
    $('.downUp').animate({'top': 500}, {        <-- x2
        duration: 1500,
        complete: function() {
            $('.downUp').animate({'top': 0}, {  <--
                duration: 1500,
                complete: downUp                <--
            });
        }
    });
}

To simplify your code, you can combine these two functions and simply add an extra parameter: reversed.

function downUp(reversed) {
    var elements = $(reversed ? ".upDown" : ".downUp");
    var to = reversed ? 0 : 500; // the 'top' value to go *to*
    var back = reversed ? 500 : 0; // the 'top' value to go back to

    elements.animate({'top': to}, {
        duration: 1500,
        complete: function() {
            elements.animate({'top': back}, {
                duration: 1500,
                complete: function() { downUp(reversed) }
            });
        }
    });
}

A few other changes I made:
- Stored the $('...') elements in a variable (faster)
- Also store the 'top' values in variables (cleaner)

Now, your code is simpler since you don't have two functions that look almost the same, yet are doing opposite tasks. Now, in the $(document).ready(), you have:

downUp();
downUp(true);
spin();

Taking spin for a spin

Your spin function looks good for the most part. As I am not that familiar with jQuery, I don't know any other way to spin an element other than to use CSS animations (like you did).

I've made some minor changes to this function:

function spin() {
    var degree = 0, elements = $('.spin');
    rotate();
    function rotate() {
        setTimeout(function() {
            elements.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
            elements.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
            elements.css({ '-ms-transform' : 'rotate(' + degree + 'deg)'});
            elements.css({ 'transform'     : 'rotate(' + degree + 'deg)'});

            ++degree;
            rotate();
        },5);
    }
}

Here are some things that I changed:

Fixed indentation (cleaner).
Stored $('.spin') in a variable (faster). Note that DOM interaction functions like these where you are grabbing elements can be costly (especially the $() function because not only does it try to parse potentially complex parameters, it also attempts to wrap all the return elements).
Removed the timer variable since it is not needed (you don't use it at all).

Also, about the CSS animation properties that you are adding/changing, I believe that there are quite a few more than the ones you have listed. For one, I know that there is just a plain 'transform' property (which I added above).

I don't know how necessary these other transform types are (type as in webkit, moz, etc), but I think it would be best to find a list of them and to include them to make sure that your code is as compatible as possible with other browsers.


This doesn't help with your primary concern of disk space, but you've got a high amount of unnecessary duplication in your code, as well as what appears to be some unnecessary checking and duplication.

We effectively see this block of code three times:

if(loopCount == [copyEventArray count]){ // when done looping, save it all
    NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
    [userData setObject:archiveArray forKey:@"events"];
    NSLog(@"save is done");
}

Moreover, as a result of your approach, there's actually a bug that could cause the entire method to be a wasted effort.  If the last object in copyEventArray is a PFFile object, but it has an error being fetched, your array won't save to user defaults at all.

And ultimately, this is code is probably a little bit hard to follow (even for you perhaps?)  In a background thread, we're iterating through an array and dispatching other background threads out (presuming getDataInBackgroundWithBlock actually does what it suggests it does).

The problem is, we're trying to asynchronously load a ton of images into the same array but then wait until we're completely done loading them all into the same array before we save that single array into NSUserDefaults.

So, with all of that said, I've got a few recommendations.

Have you tried storing your images purely as NSData objects?  Have you compared the size of NSData versus UIImage?
Consider as an option compressing your downloaded images.  Perhaps, realistically, it might be better if the version stored on the server is more compressed, but certainly a mobile device could compress the image.  Once you have a UIImage object, you can get an NSData object for the .png representation of that image, or you could get an NSData object for the .jpg representation of that image.  A .png will compress the image as much as possible without any loss.  A .jpg, you can specify the compression rate.
I highly recommend looking into Core Data.  This would greatly simplify the downloading and archiving process.  You could greatly improve the rate at which you pull the images back off the disk to display.  And it's probably more efficient than using NSUserDefaults.


Binding a keyboard key to a Tkinter button

TL;DR: Yes, binding the keyboard key and button to the same function is a proper solution.

How to bind a keyboard key to a tkinter button

There are two ways to share a function between a bind keypress a command button.

Method 1: Use an optional event parameter

As you have already discovered yourself, you can use an optional event parameter that you don't depend on.

Since the parameter is unused, you can prefix it with an underscore (_event) to prevent warnings.

    self.button = Button(frame, text="Hello", command=self.func)
    master.bind('f', self.func)

def func(self, _event=None):
    print("Hello, world")

Full Example:

# from tkinter import Button, Frame, Tk  # Python 3
from Tkinter import Button, Frame, Tk    # Python 2

class MyClass:
    def __init__(self, master):
       frame = Frame(master)
       frame.pack()

       self.button = Button(frame, text="Hello", command=self.func)
       self.button.pack(side='left')

       master.bind('f', self.func)

    def func(self, _event=None):
        print("Hello, world")

root = Tk()
abc = MyClass(root)
root.mainloop()

Method 2: Use lambdas

If the event parameter isn't being used, you can discard it by binding your key to a lambda function.

    self.button = Button(frame, text="Hello", command=self.func)
    master.bind('f', lambda event: self.func())

def func(self):
    print("Hello, world")

Full Example:

# from tkinter import Button, Frame, Tk  # Python 3
from Tkinter import Button, Frame, Tk    # Python 2

class MyClass:
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.button = Button(frame, text="Hello", command=self.func)
        self.button.pack(side='left')

        master.bind('f', lambda event: self.func())

    def func(self):
        print("Hello, world!")

root = Tk()
abc = MyClass(root)
root.mainloop()

(See How do I make Bind and Command do the same thing in tkinter?)

Miscellaneous tips

Avoid using wildcard imports

You should try to be explicit whenever you import in Python.

Yes

from Tkinter import Tk, Button, Frame

Yes

import Tkinter as tk

No

from Tkinter import *

(See Why is “import *” bad?)

Switch to Python 3

As coal_'s answer mentioned, development on Python 2 is scheduled to end in 2020. To ensure continued support, you should transition to Python 3 or later.

Use strings when packing constants

This is more personal preference than a rule, but I usually try to use strings when packing in tkinter. It means you don't have to import as many things.

Yes

self.button.pack(side="left")

No

self.button.pack(side=LEFT)


Julia RPN calculator algorithm ported from Python version

In case you don't already know this ...

Here is what the line [max(len(y) for y in x) for x in zip(*rp)] is doing.

Say that

rp = [('a', 'b', 'c', 'd'), ('aa', 'bbb', 'cccc', 'ddddd')]
unzipped_rp = zip(*rp) # [('a', 'aa'), ('b', 'bbb'), ('c', 'cccc'), ('d', 'ddddd')]

This code does almost the same as what the line above does ...

max_lengths = []

for x in unzipped_rp:
    lengths = []
    for y in x:
        lengths.append(len(y))
    max_lengths.append(max(lengths))

print max_lengths

Output:
    [2, 3, 4, 5]


Improved minimal webcrawler - why is it so slow?

Edit:

Analysis of posted profile results

Of all the functions listed in the result, your code accounts for 0.041 seconds. However, the cumulative time for the entire execution is 14.169. This has your code accounting for .289% of the entire execution.

The function that takes the most time is the recv() calls on the underlying sockets. This one function is dominating the execution time compared to any of the other functions. From this we see that transferring files over the internet is very slow. Evaluating a boolean expression and manipulating a list is very fast.

Based on the analysis, we have learned that your program's bottleneck is the IO over the network. Every time your code reads a new html file, nothing else is happening in your application. What you can do to speed this is up is to execute code in parallel so that you a reading in multiple files at one time. You can look into threads to do this type of parallelization. However, by doing this you will also have to synchronize access ToCrawl and Crawled lists.

Original:

A review of the code independent of an performance considerations.

def hostname(link):
    hostname = urlparse.urlparse(link).hostname
    return hostname

Your variable is hiding the function name. Doing this in a function that is meant to be recursive would lead to an error. Instead you can return the value directly instead of creating a local variable.

There are a few other places you create a local variable and only reference them once. Sometimes giving a value a name can increase readability. However, most of the code in this post do not fit into this category.

def is_internal_link(url):
    if url.startswith("http"):
        return False
    return True

startswith() is already returning a boolean. You don't need the if statement to explicitly return the result.

def is_internal_link(url):
    return not url.startswith("http")

Another example if using an if statement to explicitly return a boolean.

def havent_visited(link):
    if link not in urls_Crawled and link not in urlsToCrawl_Parent and link not in urlsToCrawl_Child:
        return True
    else:
        return False

I point this out because it is done in a different style. This explicitly uses an else where as the first case used the implicit else as the true clause will always exit the function. Using a standard convention throughout the code base will improve readability. In this case, one style is not better, but you should be consistent.

crawl(urlsToCrawl_Parent[0])
urls_Crawled.append(urlsToCrawl_Parent[0])
urlsToCrawl_Parent.pop(0)

is equivalent to

target = urlsToCrawl_Parent.pop(0)
crawl(target)
urls_Crawled.append(target)

The second version is cleaner because the variable name gives you context. You also don't have to worry about indexing the list multiple times.

The elif block is also executing this same operation. You can more this repeated code into a function.

while (len(urls_Crawled) < 5):

5 is a magic number here. There is no context to why a number less than 5 is important. If there is another 5 somewhere else in the code, does it mean the same thing? Giving a constant a name will provide this context. Also, if you need to change it later, you will just have to change the code in one place. And you won't have to worry about that other 5 that had a different context.


Extract subarray of elements that appear after the last occurrence of "4"

I would use this:

public int[] post4(int[] arr) {
  for(int i = arr.length-1; i >= 0; --i) {
    if(arr[i] == 4) {
      return Arrays.copyOfRange(arr, i+1, arr.length);
    }
  }
  return new int[0]; // or null
}


I also suggest to use a better RegEx but stay with PowerShell.

Without exactly knowing your $testnames you can manually or automatically build a RegEx with a lookbehind and alternations and read the *.cs files only once.

## build some sample files
'foo','bar','baz'|ForEach-Object{"Resources.$_" > "$_.cs"}

$testnames = [RegEx]"(?<=Resources\.)(foo|bar|baz)"
# (zero length look behind assertion)(alternation)

$Result =  Get-ChildItem *.cs -Recurse -File |
  Select-String -Pattern $testnames|
    Select-Object @{n='UsedIcons';e={$_.Matches.Groups[0].Value}} -Unique

$Result

Sample output:

UsedIcons
---------
bar
baz
foo


Runs a MySQL query, returns Dictionary or false;

As you suspected, this code is pretty bad. You are returning three different types of data here. Just, don't.

1)

try
{
    conn.Open();
}
catch (MySqlException ex)
{
    return ex;
}

Don't return the exception, re-throw it and catch it in the caller.

try
{
    conn.Open();
}
catch (MySqlException ex)
{
    throw;
}

In this block, you are catching the exception, then returning the exception to the user as a piece of data. A better way to do this would be to just not catch the exception and let the caller catch it:

try
{
    return mysqlWrapper.RunSelectCommand(C, collection);
}
catch (Exception ex)
{
    return ex;
}

However, now you are exposing your call stack to the user, which you don't want to do. This information could provide hints to someone trying to break into your system, and is not allowed under some security protocols (SOC 2, for example). Instead of returning the whole exception, build a new piece of data and return just the relevant bits (or if they just need one piece, then just return that piece).

2)

Don't return false. Either return an empty object (if the caller doesn't care if there were no results), or throw an exception. Alternately, you could use a ValueTuple and return (bool success, Dictionary<string, string> data) from the method. The first successful path would return (true, {data}) and the second would return (false, null).

3)

You might have a SQL Injection attack going on here. Check out what happens if the client sends a request with the text parameter "test' or 1 = 1 --". It looks like the resulting query might be SELECT * FROM api WHERE apikey = 'test' or 1 = 1 --', but I don't know this well enough to be sure.


Product of all but one number in a sequence - Follow Up (2)

Proper scoping
int mult=1; //product of prefix or suffix elements

mult above is only used in the first loop. The one used in the second loop is defined there, and limited to that loop. This one should be the same.

Proper naming

j in the second loop is an unexpected name. As it is an outer loop, you should use i (again).

int size = sizeof(nums)/sizeof(nums[0]);

While size isn't really wrong, I would expect a different unit of measurement (namely bytes, as for sizeof, instead of elements) considering the name. I suggest going for count.

Check for failure
int *products = derive_products(nums, size); //get a new array

The above can fail, in which case it returns null. Don't just assume success.

Comments
//without division, with O(n) time, but extra space complexity as suggested
//return new array on the heap

Comments should be to the point, omit the obvious, and describe the motivation.
The above could be:
// without division in O(n) time
// free(result)

Yes, writing down the task as a comment is a good idea. But if you have test-data, just write a test.

Your comment after a line of code are pretty superfluous. Are you forced to sprinkle more comments?
See Guessing a number, but comments concerning

Whitespace

Your use of whitespace is inconsistent. Do you surround binary operators with single whitespace?
Sometimes you do, sometimes you don't. Imho, doing so looks better, so standardise on that. There are plenty automatic code formatters, so you don't even have to do the hard work yourself.


You could replace your function with:

file_names = (os.path.join(path, name) for path, _, filenames in os.walk(directory)
        for name in filenames)

file_sizes = ((name, os.path.getsize(name)) for name in file_names)

However, I'm not sure that really helps the clarity.

I found doing this:

big_files = heapq.nlargest(
        num_files, file_names, key=os.path.getsize)
print(*("{}\t{:>}".format(b, os.path.getsize(b)) for b in big_files))

Actually runs slightly quicker then your version.


doc strings

Good. I like seeing doc strings. But, let's take a closer look.

class ObjectPicker:
    """
    An object that stores other objects with weights, and is able to
    pick out one stored object, with a higher chance for higher weighted
    objects.
    """

Ok, that is a lot of text. Can we separate this out into two sections with a short title?

class ObjectPicker:
    """
    Choose a random element taking weights into account.

    Elements with a higher weight have a higher change of being chosen.
    """

On to the init.

    def __init__(self):
        """
        Initialize the Object Picker object. Create the instance variable
        bucket for storing objects.
        """
        ...

There are two things wrong with it. It is telling me the following:

It initialises the Object Picker object: That's what __init__ is supposed to do. Good. But that does not really warrant mentioning. So you can leave that portion out.
It creates an instance variable bucket for storing objects: That's an implementation detail. Where and when the bucket variable is initialized does not really matter. That it creates a variable bucket instead of storage or something else does not matter. Again, leave that out.

So we move to

    def __init__(self):
        ...

(That is, remove the doc string.)

add and pick can be given similar treatments. Importantly, add an extra empty line between the documentation, and the parameter description.

Comments

Look at the following code

if self.bucket:  # If there is anything in the bucket.
    total = self.bucket[-1][-1]  # Get the end number of the last item.
else:  # If the bucket is empty.
    total = 0  # End number is 0.

The comments for the if and else are really trivial. You can easily drop them. Please do.

Consider what your comments add to the code. If they detail how it's implemented, try very hard to find a way to remove them without reducing the clarity. The following is just as clear.

if self.bucket:
    total = self.bucket[-1][-1]  # Get the end number of the last item.
else:
    total = 0

You notice I left 1 comment in. That's because of the end number. If you follow the namedtuple advice below, you can replace that line with

total = self.bucket[-1].end

(without the comment). The code is just as clear.

Excessive commenting in general

Another comment I'd just like to point out. Somewhere in the code I see

return None  # Return None.

As an outsider, comments like this make me believe that you are a beginner in Python, or even programming in general. Probably even following a class where the lecturer dictates comments like that.

Commenting like this screams 'I know nothing'. However, when I read the code without the comments, it's very readable, and only a few comments remain that are actually necessary. Actually, just two:

# Get the end number of the last item.

and

# Start binary search in middle of storage object.

To remove them, you'd need to refactor your code. And later on I'll give you the ingredients needed in a bit more detail.

You might want to leave in some more comments, depending on how comfortable you are, but make sure that the comments add value. Commonly, that's done by explaining why a piece of code is written, not what it does.

Let me state the following a bit more clearly. It is the excessive commenting that makes me doubt your experience. Reading your code (and explanation) tells me a different story: You know how to handle a binary search (and from what I can see, correctly), you know something about complexity theory. This is somebody to be reckoned with.

Algorithm

Storing of elements.

You use a tuple to store the elements, leading to code such as

total = self.bucket[-1][-1]

and

start, end = storage[index][2:]

The tuple is always the same size, and the same form. So, why not make it a namedtuple? Put the following import at the top of your file:

from collections import namedtuple

RangedElement = namedtuple('RangedElement', ['value', 'length', 'start', 'end'])

(I cheated a bit, I moved from weights to lengths, because it somewhat makes more sense when talking about start and end.)

Then, instead of

self.bucket.append((item, weight, total, total + weight))

write

self.bucket.append(RangedElement(item, weight, total, total + weight))

Yes, it's more typing. But, instead of

total = storage[-1][-1]

you can now write

total = storage[-1].end

Which is much better.

Getting the (random) element.

Defaulting

You already mentioned you were not sure about the defaulting. Important should be the question 'why the defaulting'?

From what I can see, the only reason for the defaulting is the recursive algorithm you use, which is a recursive bisection algorithm (or binary search algorithm). It would be good to separate the bisecting from the choosing.

def _bisect(self, choice, storage):
    """
    Bisect to find the stored object.
    """
    # Bisection is currently done recursively

    # Start binary search in middle of storage object.
    index = len(storage) // 2
    start, end = storage[index][2:]

    # If the choice is lower, recursively search left half.
    if choice < start:
        return self._bisect(choice, storage[:index])
    # If the choice is higher, recursively search right half.
    elif choice > end:
        return self._bisect(choice, storage[index + 1:])
    # Otherwise, choice is in number spread and return object.
    else:
        return storage[index][0]

def pick(self):
    """
    Pick an object from the bucket recursively,
    taking weight into account.

    :param choice: Number of choice.
    :param storage: Storage Object to choose from.
    """
    if not self.bucket:  # If bucket is empty.
        return None  # Return None.
    else:
        storage = self.bucket  # Storage is bucket
        total = storage[-1][-1]  # Get final weight.

    # Randomly choose a number to represent the choice.
    choice = random.random() * total

    return self._bisect(choice, storage)

(Why I chose this: I saw that some arguments were recursion-specific, and were basically saying "Don't do this when you're already recursing". A clear pointer that we were mixing two concerns, which are now better separated).

Note that splitting like this can be somewhat dangerous when this method is called somewhere else as well with the extra parameters. Sufficient unit tests would detect it.

Bisecting

You probably saw I named the helper method _bisect. That is because it uses a fairly trivial bisection algorithm. The algorithm works recursively. Recursive algorithms are really nice, but Python has a recursion-limit, no tail-call optimisations, and you are also building subslices of bucket.

In fact, look at the following lines:

index = len(storage) // 2
....
    return self.pick(choice, storage[:index])
....
    return self.pick(choice, storage[index + 1:])
....

In the first call, you're copying exactly half the list. Slicing a list is linear in the length of the resulting slice. So this alone is O(n/2) = O(n). Due to recursion, you get O(n/2 + n/4 + n/8 + ...) (still O(n), though).

So your algorithm is actually linear due to copying. However, this is fixable. Instead of slicing storage, pass in offsets (hi/lo), calculate mid = lo + (hi - lo) // 2. Then recurse using hi = mid or lo = mid + 1.

However, instead of re-inventing the wheel, why not look at the Python bisect module?

https://hg.python.org/cpython/file/3.5/Lib/bisect.py

(I'm intentionally pointing at the source, because I'm going to copy the code, not call the module)

def _bisect(self, choice, storage):
   lo, hi = 0, len(storage)
    while True:
        mid = (lo + hi) // 2
        if storage[mid].end < choice:
            lo = mid + 1
        elif storage[mid].start > choice:
            hi = mid
        else:
            return storage[mid].value

Now I just hope I got my boundary conditions right (that's always a problem with a bisection algorithm). Just write plenty of unit tests for this specific part, please!

Choosing from an empty storage?

I'm specifically talking about the following lines:

if not self.bucket:  # If bucket is empty.
    return None  # Return None.

Is None also an allowed value in your buckets? If so, this could cause confusing bugs. Better:

if not self.bucket:
    raise EmptyBucketError("Can't pick from an empty bucket.")

or something similar. But this is something you need to decide yourself.

Conclusion

Great code, but it could use some (very) minor improvements with great benefits:

namedtuple
extract binary search from picking an element.
removing comments.


Probability that Three Pieces Form a Triangle

Direct boolean return

As @Grajdeanu Alex says, this:

if (ab > c and ac > b and bc > a):
    return True

return False

can simply be

return ab > c and ac > b and bc > a

Type hints

def can_form_triangle(a, b, c):

can be

def can_form_triangle(a: float, b: float, c: float) -> bool:

Sort unpack

first_point = random()
second_point = random()
sorted_points = sorted((first_point, second_point))

return can_form_triangle(sorted_points[0], sorted_points[1] - sorted_points[0], 1 - sorted_points[1])

can be

    first_point, second_point = sorted((random(), random()))

    return can_form_triangle(first_point, second_point - first_point, 1 - second_point)

Digit triples

10000000 is more easily read as 10_000_000.

Attempt looping

num_attempts will evaluate to 10_000_000 so it's not worth tracking unless you add an early-exit mechanism.

The whole loop can be replaced with

num_success = sum(
    1
    for _ in range(10_000_000)
    if try_one_triangle()
)

Redundant parentheses

print('Ratio:', num_success / (num_attempts))

does not need the inner parens.


You need to step away from programming and design your classes.
Pokemon stats aren't just one number. And so you should design for this.

First things first, Pokemon have multiple stats, the main ones are:

Each Pokemon of the same breed have the same base stats.
Say you have two Pikachu, their base stats are exactly the same.
And so you should define this on a Pokemon's class.
They have 'genes', better know as IVs - individual values.
These change for each and every Pokemon, two Pikachu are unlikely to have the same IVs.
They also don't change, ever. And so it'd be a good idea to make these immutable.
They learn things by fighting, and gain EVs - effort values.
These aren't immutable all the time, but have a limit, and become immutable at that point.
Pokemon have a nature, which also change a Pokemon's stats.

And so, if you want the program to be correct, you need to correctly handle the above.
But you need to handle all of them differently:

For base stats, you want to use Composition over inheritance.
For IVs, you want to use a namedtuple, or just a tuple.
For EVs, you want to have a user defined type.

And so you don't need to take 50 arguments in the creation of a Pokemon. You need 4 arguments, and if you want to pass the moves, 5.
To start you off you'd need something like:

from collections import namedtuple

Stats = namedtuple('Stats', 'hp attack defense sp_atk sp_def speed')

# TODO: add limits on input
class EV(object):
    def __init__(self, hp, attack, defense, sp_atk, sp_def, speed):
        self.hp = hp
        self.attack = attack
        self.defense = defense
        self.sp_atk = sp_atk
        self.sp_def = sp_def
        self.speed = speed

class Pokemon(object):
    _base_stats = Stats(0, 0, 0, 0, 0, 0)
    def __init__(self, iv, ev, nature, level):
        # TODO: check input is within correct bounds
        self._iv = Stats(*iv)
        self._ev = EV(*ev)
        self._nature = nature
        self.level = level
        # TODO: take more data, such as the pokemon's name.

    @property
    def max_hp(self):
        base = self._base_stats.hp
        iv = self._iv.hp
        ev = self._ev.hp
        level = self.level
        return int(((2 * base + iv + int(ev/4)) * level) / 100) + level + 10

    def _calculate_stat(self, stat):
        base = getattr(self._base_stats, stat)
        iv = getattr(self._iv, stat)
        ev = getattr(self._ev, stat)
        level = self.level
        # TODO: correct nature
        nature = 1
        return int((int(((2 * base + iv + int(ev/4)) * level) / 100) + 5) * nature)

    @property
    def attack(self):
        return self._calculate_stat('attack')

    @property
    def defense(self):
        return self._calculate_stat('defense')

class Pikachu(object):
    _base_stats = Stats(35, 55, 40, 50, 50, 90)

def pokemon(base, *args, **kwargs):
    return type('Pokemon', (base, Pokemon), dict())(*args, **kwargs)

pikachu = pokemon(Pikachu, [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], None, 100)
print(pikachu.max_hp)
print(pikachu.attack)

Even if you don't use the previous, then I'd still recommend that you move the data into smaller more logical datatypes.
But either way you should want to then change the way you're storing your moves.
Each move should be an object, it has a name, damage, type, miss chance, special animation. You need to contain all of this in each move.
But you also need to have an instance of each move, so that every move in the game doesn't share the same PP.
And so to create each move, you may want to do the same as above with the Pikachu class.
After this, it'd make more sense to store these instances in a list rather than a dictionary.

And so you should instead have something like:

class Tackle(object):
    name = 'tackle'
    damage = 70

pikachu = pokemon(..., [Tackle()])

Going further, if this is too static, then you can use type to define these classes. And allow you to off-load storing the data in a database.

You should want to take the moves in the constructor of the class as it normally makes saving and loading game state easier.
If you did want to keep your Moves function then you should change it to add_move and only take one move, not two.


You could just create one function, like this:

function add(x) {
    winnings += x;
    document.getElementById("winnings").innerHTML = winnings;
}

But if you need three different versions, you could always do this:

var winnings = 0;
function addX(x) {
    return function() {
        winnings += x;
        document.getElementById("winnings").innerHTML = winnings;
    }
}

var add20 = addX(20);
var add40 = addX(40);
var add60 = addX(60);

Or even more simply:

function add(x) {
    winnings += x;
    document.getElementById("winnings").innerHTML = winnings;
}
function add20() { add(20); }
function add40() { add(40); }
function add60() { add(60); }


Calling ElementAt() inside a loop will cause the IEnumerable to be called multiple times.  This code isn't deferring execution either.

Now if you think the previous code wasn't readable then hold on to your hats.  I'm going to post some code in hopes someone can build on it and maybe come up with something better.

public static class IEnumerableExtensions
{
    public static IEnumerable<TSource> Interweave<TSource>(this IEnumerable<TSource> source, params IEnumerable<TSource>[] weavers)
    {
        // Create a list of Enumerators but need to reverse it as will be removing from list and don't want o mess up indexer
        var enumerators = new[] { source }.Concat(weavers).Select(x => x.GetEnumerator()).Reverse().ToList();
        try
        {
            while (enumerators.Count > 0)
            {
                //  index backwards so we can remove from list and not mess up index
                for (var i = enumerators.Count - 1; i >= 0; i--)
                {
                    var currentEnumerator = enumerators[i];
                    if (currentEnumerator.MoveNext())
                    {
                        yield return currentEnumerator.Current;
                    }
                    else
                    {
                        currentEnumerator.Dispose();
                        enumerators.Remove(currentEnumerator);
                    }
                }
            }
        }
        finally
        {
            // finally block as we can't use "using" as have multiple disposables and don't know count ahead of time
            if (enumerators != null)
            {
                enumerators.ForEach(x => x.Dispose());
            }
        }
    }
}

This doesn't do Take, but you can just chain on the Take method.

Example of it in use:

static void Main(string[] args)
{
    var one = new[] { "aaa", "bb", "ccc", "ddd" };
    var two = new[] { "eee", "fff" };
    var threee = new[] { "ggg", "hhhhh", "iii", "jjj", "kkk" };
    var four = new[] { "lll" };
    var five = new[] { "1111", "22", "333", "444", "55555", "66666" };

    foreach (var item in one.Interweave(two, threee, four, five).Take(6))
    {
        Console.WriteLine(item);
    }
    Console.ReadLine();
}


I know the formal difference between returning value and throwing the exception, but still can not feel whether it's time to panic and throw an exception or the program should keep calm and just return the error code.

Simple Rules of thumb.

If you can not fix the issue locally then throw an exception.
You can not solve the problem of not having enough memory locally so throw an exception. This will allow the stack to unwind memory be released and you "May" get to a point where this can be solved (or if not let the application exit). An example of where it can be stopped is when you are creating independent task and one of these tasks fails. It does not mean that all tasks will fail. Log the fact that this task has failed allow the exception to release all the memory it used and then try the next task.

Error code should not cross interface boundaries.
Error codes are great if you check them. It allows a simple mechanism to pass information back one or two levels without complicating the code. So if you are writing a library and internally you use error codes that is fine (because you will be good and check all error codes). But you can not trust users of your library so if an error is going to propagate outside your library use an exception to force the user to explicitly get it.

User Input and streams. Don't use exceptions. User input is always going to be error prone and the code that handles user input is going to need to have lots of validation checks (if done correctly). They know this. So on stream operations simply set the stream to bad.

Is a proper way to handle bad_alloc exception?

Let it propagate to the top of your app. Log something to let the user know it happened. If this is an independent task drop the task and start the next one. If this is just a normal part of executing then let the application exit.

Any extra comments and suggestions :)

Don't use malloc()/free() in C++ code.
For every new there should be a delete.
Prefer to use make_unique() rather than new (to help with new/delete matching).

Code Review:
// Owned pointers are a bad idea.
struct MiserlinessClass{
    char  *   pMemory;          // This is an owned pointer.
                                // At lot of extra work needs to be done here
                                // You need to look up the rule of three/five

            std::bad_alloc exception;
            throw exception;

Easier to simply write:
             throw std::bad_alloc;

This is not a bad_alloc situation.
        if (len>max_size){
            std::cout<<"What a lavish lifestyle! Get out of my face! \n";
            std::bad_alloc exception;
            throw exception;
        }

bad_alloc means that the system failed to allocate memory because of memory pressure.
You should use: std::range_error the input parameter was out of range.

Don't use malloc use new here.
        pMemory = (char *)malloc(len*sizeof(char));

        // Better:
        pMemory = new char[len];

Note: You still need to implement the rule of three here.

Note: Yes you should be throwing an exception above. You do not want to allow the user to create invalid objects. This needs to be fixed before the application is allowed into production so forcing the unit test to fail with an exception is the correct solution.

There is no destructor to the class MiserlinessClass. So the memory allocated with malloc() is going to be leaked. Forcing you to run out of memory quicker.
See Rule of three.

Note: This will release the previous object. But only if the new object is successfully created. So you have a bunch of memory allocated. Then you try and allocate twice as much. If that allocation works then you release the old memory.
            objPtr.reset(new MiserlinessClass(len));

I would move the declaration:
   std::unique_ptr<MiserlinessClass> objPtr;

into the try block do the allocation there.
    try{
        std::cout<<"Trying to allocate "<<len<<" chars...\n";
        std::unique_ptr<MiserlinessClass> objPtr = std::make_unique<MiserlinessClass>(len);
        allocated = true;
    } catch (std::bad_alloc &e){
    ...

Now. The memory is allocated and then released at the end of the try. Next time around the loop you know that you have clean store to allocate from as everything was cleaned up from your last attempt.
You could go a step further and simply remove the unique_ptr.
    try{
        std::cout<<"Trying to allocate "<<len<<" chars...\n";
        MiserlinessClass       objPtr(len);
        allocated = true;
    } catch (std::bad_alloc &e){
    ...

Why not just multiply by 2.
            len = len >> 1;

Or is that divide by 2. Either way the intent is not clear. Use code that expresses your intent clearly.

Only prints if there is no exception.
    std::cout<< "Allocated " << objPtr->memory_len << " chars \n";


you should be using arrays to store your variable.
your coding if syntax are not indented and formatted well.
https://stackoverflow.com/questions/253030/best-way-to-format-if-statement-with-multiple-conditions
it is better to use

if ($_POST) { }

/** rather than **/

if ($_SERVER["REQUEST_METHOD"] == "POST") { }

in your case.

if anything else read about PSR1 or PSR2 coding standard.

http://www.php-fig.org/psr/psr-1/
http://www.php-fig.org/psr/psr-2/


Naming

You should consider renaming or removing Your memory_map() function, all functions from Your linkedlist library does have a prefix list_, and this one does not. Also, it's kind a misleading. For user of Your library it might look like something related to mmap().

What does p, k, x mean? Please, consider using proper names for Your variables.

Verbosity

Just returning false in case of error usually is not verbose enough. I'd suggest considering proper error codes and/or proper error logger, for example something like this:

#ifndef LLIST_LOG
#define LLIST_LOG(format, ...) \
    fprintf(stderr, "LLIST_LOG: %s(): " format "\n", \
          __FUNCTION__, ##__VA_ARGS__)
#endif /* LLIST_LOG */

Consistency

Spacing and indentation is inconsistent. You should decide, how many spaces do You put between functions, how and when You separate if() {}, while() {}, arithmetical operations, etc blocks from each other or other logical parts of Your code. Or even better, use already defined C coding style, for example Linux kernel one.

Input verification

Rule of thumb, user of Your library is going to be dumb. And/or it will get messy debugging bigger project with Your library included. So, really, verify ALL the inputs. For example, Your list_delete(NULL, 1) segfaults.

Generic practices

Back to memory_map(), in general it's quite common to provide iterator function which calls some callback with every single element of the structure as a parameter instead. It's way more versatile.

It's common to suffix include guards by some randomly generated gibberish or hash, especially for such a common names as LINKED_LIST. Also, for compatibility with some compilers it usually defines it to some specific value. For example:

#ifndef LINKED_LIST_H_093e74eeda79fcc4c29e9d2986f5b701
#define LINKED_LIST_H_093e74eeda79fcc4c29e9d2986f5b701 1

Also, You should consider adding function list_create() and list_destroy() for Your library user not to mess with malloc() and free() directly and handle errors properly there.

Generic rant

There is a memory leak in Your example ;)


Summing all numbers that can be formed from a list of integers

Imagine you had to do the same with 4 distinct digits, a, b, c and d, and lets forget for now about numbers with less than 4 digits. There are 4! arrangements of these 4 digits, of which 3! each will have the a in the first, second, third and fourth positions. So the contribution of the digit a to the overall sum will be a * 3! * 1111, and the total sum of all numbers generated from these four digits ends up being (a + b + c + d) * 3! * 1111. It is easy to check that this works comparing to a brute-force solution:

from itertools import  permutations

def sum_them_quick(a, b, c, d):
    return (a + b + c + d) * 3 * 2 * 1 * 1111

def sum_them_slow(a, b, c, d):
    total = 0
    for digits in permutations([a, b, c, d], 4):
        total += int(''.join(str(d) for d in digits))
    return total

If you test this, you will find that, while they both produce the same result, the performance is already 100x faster for this small example:

>>> sum_them_quick(4, 5, 6, 7) ==  sum_them_slow(4, 5, 6, 7)
True
>>> %timeit sum_them_quick(4, 5, 6, 7)
1000000 loops, best of 3: 349 ns per loop
>>> %timeit sum_them_slow(4, 5, 6, 7)
10000 loops, best of 3: 54.9 µs per loop

Your case is not that simple, because you have to handle the repeats, but it isn't that much harder either. If you have x 4's, y 5's and z 6's, there are (x + y + z)! / x! / y! / z! different arrangements of those digits to form unique numbers. And similarly to the previous case, a 4 will show up in any given position x / (x + y + z) of the times. So similarly, the following function will compute the total sum in constant time:

from math import factorial

def sum_them_456(x, y, z):
    total = 0
    for j in range(x + y + z):
        total *= 10
        total += 1
    print(total)
    total *= 4*x + 5*y + 6*z
    total *= factorial(x + y + z - 1)
    total //= factorial(x) * factorial(y) * factorial(z)
    return total

There are cleverer ways of computing a quotient of factorials, but that is left as exercise.

You also have to handle all the possible permutations with less than the full x + y + z possible digits. There may be a better way of not having to brute-force your way through this, but I'm out of cleverness right now, so I am going to go with something very unsophisticated:

def sum_them_all_456(x, y, z):
    n = x + y + z
    total = 0
    trials = set()
    trials.add((x, y, z))
    while n > 0:
        new_trials = set()
        for trial in trials:
            total += sum_them_456(*trial)
            for idx in range(len(trial)):
                if trial[idx] > 0:
                    new_trial = trial[:idx] + (trial[idx] - 1,) + trial[idx+1:]
                    new_trials.add(new_trial)
        trials = new_trials
        n -= 1
    return total

It still manages to handle values of x, y or z in the tenths in the blink of an eye, but there has to be a better way for this.


prime_sieve() isn't your code, so I won't review it (although I will express my opinion that it's in dire need of more commenting).

However, the choice to use it is firmly within the scope of this review, and frankly I can't understand it. The whole point of that particular implementation is to optimise memory use at the cost of considerable code complexity. But given that your goal is a fully cached list (i.e. optimising speed at the cost of memory usage), it would make far more sense to me to use a simpler implementation which directly accesses the cache.

        if vals[-1] >= end:
            hi = self.get_ind(end)
            yield from islice(vals, lo, hi)
            return
        else:
            while vals[-1] < end:
                if len(vals) > lo:
                    bound = len(vals)
                    yield from takewhile(lambda p: p <=end, islice(vals, lo, bound))
                    lo = bound
                vals.append(next(self.prime_gen))
        hi = self.get_ind(end)
        yield from islice(vals, lo, hi)

Taking a step back to look at the structure, we have

        if condition():
            foo()
            return
        else:
            while not condition():
                bar()
        foo()
        return # implicit because it's the end of the function

Firstly,

            return
        else:

can often be clearer without the else, which is unnecessary: the scope it defines is unreachable if the if block executed. That gives

        if condition():
            foo()
            return

        while not condition():
            bar()
        foo()
        return

which is semantically identical to

        while not condition():
            bar()
        foo()
        return

            while vals[-1] < end:
                if len(vals) > lo:
                    bound = len(vals)
                    yield from takewhile(lambda p: p <=end, islice(vals, lo, bound))
                    lo = bound
                vals.append(next(self.prime_gen))

The whole if clause in here seems dubious to me. Why can't it be removed entirely? (I figured out the reason, but IMO there should be a comment to save me the effort).

Given that all but the first time round it will yield from a slice containing precisely one value (the one appended the previous time round), it seems rather heavyweight. It would probably make sense to refactor as:

    yield from (something)
    while vals[-1] < end:
        extension = next(self.prime_gen)
        vals.append(extension)
        yield extension

Further modification to the final refactors implemented for the above points may come from the simpler replacement of prime_gen. Do you want a replacement with produces primes one at a time, or something like a paged sieve? The latter should be more efficient, but at the cost of slight complication.

    def get_ind(self, x):

If I had to guess without any contextual clues, I would assume that ind is short for independent. If it's necessary to abbreviate index then I consider idx to be the best option. But here there is a clear correct name for the method: index, for consistency with list.index.

(Of course, that's assuming you want it to be public. Given that it returns incorrect values for primes which haven't yet been reached by get, it would probably be better to call it _index).


I don't see the advantage of adding Seed and Knowledge into the prototype of World (unless you've got more code to tell me otherwise). If you don't need anything from the instance at all, then you don't need them in the instance. You can put them like static members instead.

With that, you can do what jQuery did. jQuery's jQuery and $ point to a constructor function that builds jQuery objects. That's why you can do jQuery() and $().

But in JS, functions are objects and like any other object, you can add properties. It's the same reason why you can also do jQuery.each or $.each. Basically they made their constructor their namespace as well.

So you can do the following to World:

(function(window){

  var World = window.World = function(){/*World constructor code*/};

  World.prototype.someFn = function(){/*...*/};

}(window));

And like how non-instance jQuery plugins extend (and yes, you can place this in another file. Just make sure the World library is loaded first):

(function(World){

  //This part would be synonymous to $.somePlugin = function(){...}
  var Seed = World.Seed = function(){/*Seed constructor code*/};

  Seed.prototype.someFn = function(){/*...*/};

}(World));

To use them:

var myWorld = new World();        //Using World as a constructor
var mangoSeed = new World.Seed(); //Using World to access the Seed constructor


Use a standard stream, and restore its settings afterwards

I agree with everything what @JiveDadson said in the comment. I believe there are some ways to improve current code.

 ## Syntax

To use the guard, people will need to introduce a scope. My desired syntax would be:

stream << session << settings << data;

I'll present solution with the syntax above later.

My solution seem to solve only a subset of problems which original code does. Thus my point about syntax is not valid. Example can be multiple statement prints, in which case my solution would do unnecessary work.

Naming

Would it be better to use stream_state_guard? The code uses name guard in the tests. It is funny that tests reflect what was actually intended to be written. I found that it is the case in my code too.

Alternative solution

To achieve the syntax above, I've used some of the new features of C++17. My thoughts are a mess more than usual, so watch out for potential nitpicks.

First of all, session needs to be object of some empty type, just like nullptr is to nullptr_t or nullopt is to nullopt_t.

struct session_t {};
static inline constexpr session_t session;

inline is used to deal with linker.

Now, the class itself.

#include <ios>
#include <iomanip>
#include <ostream>

class session_stream
{
    std::ostream& stream;
    std::ios_base::fmtflags flags;
    std::locale locale;
    std::streamsize precision;
    std::streamsize width;
    char fill;

    session_stream(std::ostream& stream)
        : stream{stream},
          flags{stream.flags()},
          locale{stream.getloc()},
          precision{stream.precision()},
          width{stream.width()},
          fill{stream.fill()}
    {}

public:
    friend session_stream operator<<(std::ostream& os, session_t);

    // deleting copy construction also prevents move
    session_stream(const session_stream&) = delete;
    void operator=(const session_stream&) = delete;

    template <typename T>
    std::ostream& operator<<(T&& value)
    {
        stream << std::forward<T>(value);
        return stream;
    }

    ~session_stream()
    {
        stream.flags(flags);
        stream.imbue(locale);
        stream.precision(precision);
        stream.width(width);
        stream.fill(fill);
    }
};

The code is just adjusted version from the question. Interesting things to note:

Constructor and copy semantics are private

Wrong usage is impossible through conventional means. People will need to be either too smart or cause undefined behavior.
Create an object only by using stream << session

This might look fishy. Especially this line:

return session_stream{os};

Since C++17 this is guaranteed copy elision, thus it works even if copy constructor is unavailable. I don't think that guarantees impossibility of prolonging lifetime of session_stream, but it will guard against unintentional wrong usages.
Uses its own operator<< only on the first call

I wasn't sure if overload resolution and ADL won't intervene, so I decided to return ostream& on operator<<.

Rewritten tests:

#include <iostream>

int main()
{
    auto test = []() {
        std::cout << std::setw(15) << "Foo" << ' '
                  << true << ' ' << 123456 << '\n';
    };
    {
        test();
        std::cout << session << std::setfill('_') << std::left << std::uppercase
                  << std::boolalpha << std::hex << std::showbase << std::setw(15)
                  << "Foo" << ' ' << true << ' ' << 123456 << '\n';
        test();
    } // stream restored here
    test();
    std::cout << std::endl;

}

Live on Wandbox.

And just for reference: sessions can be nested.


I think your code is - in general - good. Your algorithm is working correctly and I really like the idea of using a Hashmap to save the values of the roman numbers.

One thing I miss is the handling of edge cases. Especially you should think about the following edge cases:

letter == null
Empty String
Strings that aren't valid roman numbers (for example "IXI" or "MMMM" aren't valid)

The first two problems are pretty easy to solve:

if(letter == null || letter.equals("")) {
        return -1;
}

The third part is a bit more difficult to solve:

if(!letter.matches("M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$")) {
        return -1;
}

As you can see, you can use a regular expression to validate if the string letter contains a valid roman number (as explained for example here).

One thought about your testing-class: You are using JUnit, which is good, but I think you are testing much too little (remember the edge cases!).

I wrote a test myself with the following values:

String[] input = {null, "", "I", "V", "XXXIII", "DCCXLVII", "CMXXIX", "MCCXXXII", "MMMCMXCIX", "MMMMXI", "KMXI", "VX", "VL", "VC", "VD", "VM","LC", "LD", "LM", "DM", "IL", "IC", "ID", "IM", "XD", "XM", "CXLV", "MIXI", "IXI", "MXIII", "MMMM", "IIII"};

int[] expectedOutput = {-1, -1, 1, 5, 33, 747, 929, 1232, 3999, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 145, -1, -1, 1013, -1, -1};


You use the value of (@bucketSize + @bufferSize) inside of a where clause and to calculate a value in a select statement, I think if you took that and created it's own variable, that it might give you some performance increase.  as well as some of the other arithmetic that could be done from the start and not calculated during the actual query

len(@values)/(@bucketSize+@bufferSize)+1

could be declared from the beginning

DECLARE maxID
SET maxID = LEN(@values) / (@bucketSize + @bufferSize) + 1

After you do that it is a toss up whether or not to Declare another Variable for the Addition of the @bucketSize + @bufferSize, but it might be worth a try.

Also please use some spaces in your equations, you use plenty of white space everywhere else.

I have a minute or two so I will also say this...

since this is going over so many records and that simple Variable freed up a good 10 seconds, I think that it might be worth it to move as much static calculation out of the query as possible, I know this is less about what SQL was meant for, but I also think this is more about being Dynamic as well.

Maybe I am going a little too far here, but this should still do the same thing as the original

create function [dbo].[BucketString] (
    @values varchar(max),
    @bucketSize int,
    @bufferSize int = 1,
    @offset int = 0)

returns @result table (id int, item varchar(max))

begin

    DECLARE @bucketAndBufferSize
    DECLARE @maxID
    DECLARE @bufferMinusBufferMinusOne
    DECLARE @bufferMinusOne

    SET @bucketAndBufferSize = @bucketSize+@bufferSize
    SET @maxID = LEN(@values) / (@bucketAndBufferSize) + 1
    SET @bufferMinusBufferMinusOne = @bufferSize - (@bufferSize - 1)
    SET @bufferMinusOne = @bufferSize - 1

    with buckets as
    (
        select 1 id

        union all

        select t.id + 1
        from buckets t
        where id = t.id
            and t.id < @maxID
    )

    insert into @result
    select
        id,
        substring(@values, @offset + ((id - 1) * @bucketAndBufferSize + (case when @bufferMinusOne = 0 then 1 else @bufferMinusBufferMinusOne end)), @bucketSize) string
    from buckets
    option (maxrecursion 0)

    return;

end

I apologize for the mismatched casing, it's habit to capitalized those words...

When bufferSize is unchanged you want it to be 1 so let's just do that and take out the extra call to the variable.

I took out all the arithmetic that wasn't reliant on information from the query and made them their own variable, this isn't going to be a huge difference, but I think it will be faster than doing the arithmetic inside the query itself, it's like being distracted by that red ball all the time, it distracts you momentarily but you get the job done.


Well looking at this as a code review of the code you posted i can recommend a couple of things;

Security

The major flaw at the moment is the possibility for SQL injection. You put the $_GET values directly into the query without validation or escaping.

PHP.net has a page on SQL injection:  http://php.net/manual/en/security.database.sql-injection.php

Deprecated code

It is strongly recommend not to use the mysq_* functions. !!!

These functions are deprecated and will recieve no more support and will be removed in an upcoming version of PHP. See http://php.net/manual/en/function.mysql-connect.php and look at the big red box. This is potentially a huge security hazzard in the future as well.

User Content / Access levels

Currently you are not demonstrating any check on access level. If i am to guess your actions i could delete the entire content of your website without logging in!

Database connection

You seem to open the sql connection somewhere else. Please verify for yourself that you also close the connection when request ends, avoiding lingering MySQL connections.

Misc

Also, look into the SOLID principles and PSR-2 codestyle, your current code does not match it. These are best practices and provide a good base strategy for your coding. Also, making it more likely the open source community would accept/adopt your code.

Good luck in further development of your CMS!


Python script to extract columns from a CSV file

Here's how I would do it, without Pandas:
import csv

filename = 'Book2.csv'

with open(filename, 'r') as csvfile:
    reader = csv.reader(csvfile)
    fields = next(reader) # Reads header row as a list
    rows = list(reader)   # Reads all subsequent rows as a list of lists

for column_number, field in enumerate(fields): # (0, routers), (1, servers)
    print(field)
    for row in rows:
        print(row[column_number])
    print('\n')


public Users VerifyPassword(string userName, string password)
{
    //The ".FirstOrDefault()" method will return either the first matched
    //result or null
    Users myUser = SoccerEntities.Users
        .FirstOrDefault(u => u.UserName == userName
                     && u.password == password);

    if (myUser == null)    //User was not found
    {
        //Proceed with your login process...
        return myUser;
    }
    else    //User was  found
    {
        if (isPlayerdb(userName))
            isPlayer = true;
        if (isAdmindb(userName))
            isAdmin = true;

        return myUser;
        //Do something to let them know that their credentials were not valid
    }
}

The comments in this method don't serve any purpose an don't add any value to the code, so get rid of them. Comments should describe why something is done but shouldn't state the obvious.

A class named Users implies to hold a collections of User but in your case it seems to be singular so you should rename this class to User.

Not using braces {} will lead to error prone code. You should use them always although they might be optional.

The else part is redundant because if myUser == null it won't be reached, you should get rid of the else.

If for instance isAdmin had been true before this call it will stay that way which is bad. Just assign the returned value of isAdmindb to the variable. The same goes for isPlayer.

Applying this points except for Users vs User

public Users VerifyPassword(string userName, string password)
{

    Users user = SoccerEntities.Users
        .FirstOrDefault(u => u.UserName == userName
                     && u.password == password);

    if (user == null) { return null; }

    isPlayer = isPlayerdb(userName);

    isAdmin = isAdmindb(userName);

    return user;

}

looks much cleaner, doesn't it ? But hold on, we can do better.

If we take a look at isAdmindb() we notice at first, that the method name doesn't match the NET naming guidelines regarding the used case of the name. Method names should be named using PascalCase casing.

The next thing is that a user is considered an admin if its roleId matches a specific Guid. So let us take this Guid and use it in the VerifyPassword() method. But wait, this doesn't seem right because the responsibility of that method should be only to verify that the used username and password are correct. So there shouldn't be anything related like in the former method with the isAdmin stuff.

So let us change the isAdmindb() method to take a Users opject as a method argument and compare the user's roleId with the said Guid which we extract to a class member constant.

private const Guid adminRoleId = new Guid("ED85788D-72DA-4D0A-8D5E-B5378FC00592");
protected bool IsAdmin(Users user)
{
    return user.roleId == adminRoleId ;
}

now thats short and readable and doesn't need to hit the db.

Now we should take the VerifyPassword() and change it to GetUser() and remove all this stuff about the isAdmin and isPlayer leaving only this

public Users GetUser(string userName, string password)
{

    return SoccerEntities.Users
        .FirstOrDefault(u => u.UserName == userName
                     && u.password == password);
}

Now let us add a FormsAuthenticationTicket GetAuthenticationTicket(Users)  method which will do some of the work which had formerly been done by the eventhandler of that button.

private FormsAuthenticationTicket GetAuthenticationTicket(Users user)
{
    return new FormsAuthenticationTicket(
          version: 1,
          name: user.UserName,
          issueDate: DateTime.Now,
          expiration: DateTime.Now.AddMinutes(30),
          isPersistent: isPersistent,
          userData: user.ToString(),
          cookiePath: FormsAuthentication.FormsCookiePath);
}

as you see by using named arguments there is no need for any comment anymore.

Now the former eventhandler code will look like

protected void btnLogin_Click1(object sender, EventArgs e)
{
    Users user = GetUser(txtUserName.Text, txtPassword.Text);

    if (user == null)
    {
        lblerror.Text = "Invalid Login";
        return;
    }

    FormsAuthenticationTicket ticket = GetAuthenticationTicket(user);

    isAdmin = IsAdmin(user);
    isPlayer = IsPlayer(user); // should be implemented by you in a similiar way

    string encryptedTicket = FormsAuthentication.Encrypt(ticket);

    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    cookie.HttpOnly = true;
    Response.Cookies.Add(cookie);

    lblerror.Text = "Success!";

    Response.Redirect("default.aspx");

}


Scroll to top and addClass onClick - then removeClass on .mouseout

jQuery provides itself as first argument in the ready callback. You can assign it the $ name so you can use it shorthand inside the callback.

jQuery(function($){
  // Use jQuery as $ inside here
});

Also, you don't need multiple ready handlers. Whenever possible, just bunch them up into one.

jQuery(function($){
  // Click handler
  // Mouse handler
});

Next is that we don't know for certain how jquery.animate schedules animation. This might affect how sooner or later the callback for setTimeout is executed.

However, jquery.animate accepts a function as the last argument which is run when the animation is complete. Use that instead of doing a timeout.

$('html, body').animate({scrollTop:0}, 800, function(){
  // done animating
});


Dependency injection with asp.net identity and property injection with dbcontext

There is any specific need to register those per single request ?

IUserStore
IRoleStore
AppRoleManager
AppRoleManager
AppRoleManager

Weird implementations apart they should be fine as "per application" removing a lot of overhead

Also, you probably can add the sessioncontext to AppDbContext constructor and make a single registration


Parsing Addresses with GeoPanda's GeoDataFrame

Nomenclature

Function names should be snake_case per PEP8, i.e. address_parsing.

Type hinting

For function parameters and return values mainly, type hinting will help define your signatures. For example, delayseconds would probably become delay_seconds: float, and gdf_obj: dict if you don't know a lot about the structure of the dictionary. So:

def address_parsing(gdf_obj: dict, delay_seconds: float) -> dict:

Retries:

    try:
        return geocode_with_delay(address)
    except GeocoderTimedOut:
        return geocode_with_delay(address)

Effectively this will ignore up to one GeocoderTimedOut and retry, but if it occurs twice the exception will fall through. A saner way to represent this is:

TRIES = 2
# ...

for retry in range(TRIES):
  try:
    return geocode_with_delay(address)
  except GeocoderTimedOut as e:
    print('Geocoder timed out')
raise e

Temporary variables

The expression

round(delayseconds * gdf_obj.shape[0] / 60, 2)

is complex enough that it should be assigned to a variable. That said, you're better off using Python's actual time-handling features:

from datetime import timedelta
# ...

est_time = timedelta(seconds=delayseconds * gdf_obj.shape[0])
print(f'Estimated time: {est_time}')  # will do pretty formatting


string.Join(string, IEnumerable<T>)

Your method ArrayToString can be replaced with a single line :

public static string ArrayToString(int[] arr)
{
    return string.Join("", arr.Select(x => Chars[x]));
}

Your method PrintArray is never used but I assume it's just there for testing purpose.

Code style

Auto properties

You can use auto-properties to avoid explicitly creating a backing field for your variables :

private int _Length;

public int Length
{
    get
    {
        return _Length;
    }
}

Can be simplified to a single property :

public int Length { get; }

You can do the same for all of your properties.

Redundant this qualifier

You don't have to write this. everywhere e.g this.Range.Max as there are no variables with the same names there, the compiler will guess that you are referring to the container class.


Abbreviating and expanding IP v6 addresses with APL

I think using regular expressions is a perfectly sensible approach. What you're missing is probably that Dyalog APL allows setting a Match Limit with ⍠'ML' n where a positive n limits to the first n matches and a negative n limits to the (absolute value of) nth match. With this in mind, I'd use regular expressions extensively:

AbbreviateIPv6 ← {
    collapsed0s ← '\b0{1,3}' ⎕R '' ⊢ ⍵      ⍝ remove up to 3 leading 0s
    runsOf0s ← '\b(0:)*0\b'                 ⍝ 0:0:0:…:0
    nth ← - ⊃⍒ runsOf0s ⎕S 1 ⊢ collapsed0s  ⍝ 1: lengths, ⊃⍒: index of first max
    abbreviated ← runsOf0s ⎕R ':' ⍠'ML' nth ⊢ collapsed0s
    ':::' '^:$' ⎕R '::' ⊢ abbreviated       ⍝ exactly two
}

Try it online!

Notes:

The linked online IPv6 compressor gives wrong results, as do many others. This one seems to work, even though it misses the occasional shortening opportunity. I still have not found an online tool that compresses both fully and correctly.
If runsOf0s ⎕S 1 doesn't find any runs of 0s, it returns ⍬ so nth becomes 0, which is fine even though 'ML' 0 means "no limit" because there are no matches.


Here are two different ways of doing this, one using repeated calls to .indexOf() and one using repeated calls with a regex to .exec().  The regex solution requires the pattern argument to be a regex compatible string or an actual RegExp object with the g flag on it.

The .indexOf() option should be much faster than what you have since it avoids repeated .slice() operations and .indexOf() as a library function should be faster than your own variation.  The regex option is a lot more flexible since you can search for phrases that match a regular expression.

function find1(pattern,str) {
    var  arr = [];
    var i = 0;
    while ((i = str.indexOf(pattern, i)) > -1) {
        // got a match starting at i
        arr.push([i, i + pattern.length - 1]);
        i++;
    }
    return arr.length ? arr : false;
};

function find2(pattern,str) {
    var  arr = [], matches;
    if (typeof pattern === "string") {
     pattern = new RegExp(pattern, "g");
    } else if (!(pattern instanceof RegExp)) {
        throw new Error("pattern must be string or RegExp object");
    }

    while (matches = pattern.exec(str)) {
        arr.push([matches.index, matches.index + matches[0].length - 1]);
    }
    return arr.length ? arr : false;
};

document.getElementById("run1").addEventListener("click", function(e) {
    var results = find1('abfd','abfdffdabfdfaffab');
    log(results);
});

document.getElementById("run2").addEventListener("click", function(e) {
    var results = find2('abfd','abfdffdabfdfaffab');
    log(results);
});

function log(x) {
    var d = document.createElement("div");
    d.innerHTML = JSON.stringify(x) + "
";
    document.body.appendChild(d);
}
<button id="run1">Run .indexOf()</button>
<button id="run2">Run regex</button>


Returning search results based off checkboxes

Applying YCS's tutorial can't be dumbed down any further, so I suppose I'll write it out.

if (isset($_POST["action"])) {
    $query = "SELECT link FROM allpostdata WHERE sts = '1'";

    if (!empty($_POST["cate"])) {
        $query .= " AND sca IN (" . str_repeat("?,", count($_POST["cate"]) - 1) . "?)";
    } else {
        $_POST["cate"] = []; // in case it is not set
    }

    $stmt = $conn->prepare($query);
    $stmt->execute($_POST["cate"]);
    $result = $stmt->fetchAll();
    if (!$result) {
        exit('
No Data Found
');
    }
    foreach ($result as $row) {
        echo "{$row['link']}";
    }
}

I assume this will display your links side by side.  You may want to style them a bit to position the links in a user friendly fashion.

Additionally, $('.filter_data'); is doing nothing and can be removed.

I'd probably change the filter_data() declaration to something more brief:

function filter_data() {
    $.post(
       "fetch.php",
       {action: 'fetch_data', cate: get_filter('cate')}
    )
    .done(function(data) {
        $('.filter_data').html(data);
    });
}


Printing a score sheet for baseball batters

I would structure the code like this:

def input_players(total=11):
  players = []

  for index in range(total):
    player = raw_input('Name of Batsman {} > '.format(index + 1))
    players.append(player)

  return players

def print_score_sheet(batsmen, total_chars=56):
  for index, batsman in enumerate(batsmen, 1):
    print '{}. {} '.format(index, batsman).ljust(total_chars, fillchar='.')

if __name__ == '__main__':
  players = input_players(11)
  print_score_sheet(players)

Some tips:

If you use a set of variables like Player1, Player2, PlayerN, you should be using a list to store them.
Your functions should do what they say. input_players() should return a list of players, nothing more, nothing less.
Get into the habit of including the if __name__ == '__main__': block. The stuff inside of the block is executed only if you run the Python script directly, which is good if you have multiple modules.


Method that receives a hexadecimal string and returns a formatted matrix of those values

int columns = 16;

This should be a constant and defined outside the method.

public static final int MATRIX_WIDTH = 32;

I prefer singular names for scalar variables.  I use plural names for collections.

I'll explain the value change later.

    int row = 0;
    int column = 0;

These could be declared with their loops.

    rows = ( hex.length() / 32 ) + ( hex.length() % 32 );

This seems wrong.  Consider

    matrixHeight = ( hex.length() / MATRIX_WIDTH ) + (( hex.length() % MATRIX_WIDTH == 0 ) ? 0 : 1);

Does that do what you want?  Test it with a 224 character string to be sure.

But you could probably do without it.

    for (row = 0; row < rows; row++) {

        for (column = 0; column < columns; column++) {

            if (hex.length() > 0) {

I'd try

    while ( !hex.isEmpty() ) {

        for (int column = 2; column <= MATRIX_WIDTH && !hex.isEmpty(); column += 2) {

This way you don't keep looping after reaching the end of the string.  And you don't need row or rows at all.

I'll explain the 2 in a moment.

                hex = hex.substring(2,hex.length());

This could be just

                hex = hex.substring(2);

You don't need to specify the end of the string if that's how far you want to go.  It's the default in the one argument version.

                if ((column + 1) % 4 == 0) {

But if we start at 2, this could be just

                if (column % 8 == 0) {

Now you don't have to calculate every iteration.  You can just work off the variable directly.


Good news!  There's lots of room for improvement in your code!  (How's that for a positive spin?)
Counting Aces
    ace = [0 for card in group if card[0] == 'A']

This code creates a list (ace), which only contains 0 elements equal in number to the number of aces in group.  The contents of the list is never used, only the length.  Finally, the length of the list is queried twice.
That is a very heavy implementation for a simple count of the number of aces:
    aces = sum(card[0] == 'A' for card in group)

Or slightly less obliquely:
    aces = sum(1 for card in group if card[0] == 'A')

Decoding Cards
    run_vals = {"0": 10, "J": 11, "Q": 12, "K":13}
    ...
            if group[index+1][0] in run_vals:
                num1 = run_vals[group[index+1][0]]
            else:
                num1 = int(group[index+1][0])

            if group[index][0] in run_vals:
                num2 = run_vals[group[index][0]]
            else:
                num2 = int(group[index][0])
    ...
        range_limits = [run_vals[val[0]] if val[0] in run_vals else val[0] for val in range_limits]
        if ace_in_between + 1 == (int(range_limits[1]) - int(range_limits[0]) ):

I'm seeing a lot of in run_vals tests and int(...) casts.  Imagine how much cleaner your code could look if you simply filled in all of the run_vals?
    run_vals = {"A": 1,
                "2": 2, "3": 3, "4": 4, "5": 5,
                "6": 6, "7": 7, "8": 8, "9": 9,
                "0": 10, "J": 11, "Q": 12, "K":13}

I've added "A" mapping to 1 just for completeness.  It would allow you to test all(card[0] in run_vals for card in group) to check that all the cards have a valid rank, such that nobody sneaks in a "1 of Spades" for example.
For that matter, you could check for valid suits too, such as all(card[1] in {'C', 'D', 'H', 'S'} for card in group), to avoid someone sneaking in the "7 of Pentacles".
A Straight
The problem would be dead simple if there was no wild cards.  You could write:
    rank = [run_vals[card[0]] for card in group]
    start = rank[0]
    for idx in range(len(rank)):
        if rank[idx] != start + idx:
            return False
    return True

Supporting wild cards would be easy too, if we knew the first card was not an ace.  We could just add an exception for the aces:
    for idx in range(len(rank)):
        if rank[idx] != start + idx and rank[idx] != 1:
            return False

Starting Value
What happens if the ace is the first card?  Well, the second card (assume it was not an ace) would dictate the start was one rank lower.  Or if that was an ace, then the third card would, and so on:
    for idx in range(len(rank)):
        if rank[idx] == 1:
            start = rank[idx] - idx
            break
    else:
        return False     # Only aces exist!

Functions!
Your code is one complex script without any functions.  If you haven't learned how to write them yet, learn.  If you have learned, use them!
Reworked Code
The following code is a reimplementation of some of the above ideas.  However, the loops like for idx in len(range(list)) have been replaced with more Pythonic for idx, value in enumerate(list) loops.  Loops which return a False if one iteration produces a False result have been replaced with an all(...) statement with a generator expression.  It also demonstrates some type-hints, """docstrings""" (including the use of (doctest) to help write code which is more understandable to others, and contain built-in unit tests.
Another improvement is the problem statement states there must be at least 2 "natural" cards.  Instead of testing for the number of aces is less than or equal to 6 -- a number which appears nowhere in the problem statement -- it directly tests against the given value 2.
RANK = dict(zip("A234567890JQK", range(1, 14)))
WILD = RANK['A']

def straight_of_eight(card_string: str) -> bool:
    """
    Determine if a string of cards is an ascending straight,
    with at least 2 natural cards.

    >>> straight_of_eight("4H,5S,AC,7C,8H,AH,0S,JC")
    True

    >>> straight_of_eight("4H,5S,AC,8H,7C,AH,0S,JC")
    False
    """

    ranks = [RANK[card[0]] for card in card_string.split(',')]

    if len(ranks) != 8:
        return False   # Were not given exactly 8 cards

    if sum(rank != WILD for rank in ranks) < 2:
        return False   # Not enough natural cards

    # Determine starting rank for the straight
    start = next(rank - idx for idx, rank in enumerate(ranks) if rank != WILD)

    return 2 <= start <= 6 and all(rank == idx or rank == WILD
                                   for idx, rank in enumerate(ranks, start))

if __name__ == '__main__':
    import doctest
    doctest.testmod()

    group = input()
    print(straight_of_eight(group))


It took me a while to figure out your code. I have solved this problem a couple of times before, but found your code hard to read. In large part, because your variable names are misleading....

board is not a board, it is an array of int, with the value of the queen's column. I see the board as being a 2D matrix, you have it as a 1D array.
queens is not the number of queens, but the number of rows you have currently populated.

Then, your code is not as general-purpose as I was expecting.... Your code only ever finds solutions where the position (0,0) is a queen. Now, that's not to say that solutions with a queen there are wrong, but, are you sure? What if there is no solution with a queen in the corner....

If you know for sure there will be one, then you should at least document that..... if not, then it's a bug.

All in all, your code could use some more help to get it readable.


Nesting of paragraph with headings and cite with dynamic content in a VueJS app

I don't know Vue.js then I won't comment about that part.

Overall structure seems OK but maybe few things may be improved. The most obvious one is usage of CSS classes to apply styling without conveying any extra semantic. In your code bright class is applied to text to make it visually distinguishable but:

Name describes the applied style instead of its meaning. If you later decide to use dimmed text then you also need to change class name (or to keep them out-of-sync).
It does not help screen readers to understand what its content is: effectively just a sub-title.
It's applied both to
,  and...
 reinforcing its usage as mere styling instead of carrying any semantic value.

For the tagline I'd use a subheader or a specific class:

{{ beer.name }}

{{ beer.tagline }}

Alternatively:

{{ beer.name }}

{{ beer.tagline }}

Note that you can use mixins to avoid CSS duplication then there is no reason to re-use the same class multiple times. Note that you're using
 for the outer container and there it has little meaning, you may refactor your HTML code to be more HTML5ish:

  ...

Loading...

      <hgroup>

{{ beer.name }}

{{ beer.tagline }}

      </hgroup>

Note that I'm using  as outer container and
 with its own <hgroup>. What's for? Screen readers (and search engines) now know what each item is, the element conveys a semantic value and you can, also, directly use it in your CSS. Image is actually a side content of the
 then you can use .

Refactored this we should look at the other bright elements. Your paragraphs are some text with a title. Exactly what
 is for:

Description:

{{ beer.desc }}

Tips from the brewer:

...

We finally arrived to the
. In this case you're quoting a small inline tweet, also note that usually
 does not contain any extraneous content (besides a  with the  element). What I think is more appropriate for this citations (which are not a separate standalone block of text) is the <q> element:

    <q cite="...">{{ beer.tips }}</q>

Few important things here: quotation marks should not be part of your HTML, browser already does it (using the appropriate symbols for the current language - which BTW you should add to your HTML). Also note the cite attribute to reference the source (if it's a twitter than you have an URL to link).  element can follow inside
.

You can (and probably should) style
 directly without using bright. You may also like (if required by your CSS) to wrap each section with
 (in this case you may have <hgroup> instead of the
 list).

You may consider to use microdata for some of your content (beer name and author of the tweet).

JS local variables in addBeer() can be const instead of let.

I see absolutely no reason (for this kind of content) to do not support accessibility. It's more complex than one paragraph in this questionthen just to refer to official W3C documentation.


Is my design still a state design pattern, or some abomination?

First of all all design patterns are well defined. Every deviation of it will distort your implementation and negate advantages into disadvantages. That is because all known design patterns in general were NOT MADE UP. They were IDENTIFIED to be the best model structures to represent some of the real world structures.

The state pattern is a behavioural pattern. Behaviour is not existent for types only objects can behaves. The state pattern consists of a holder object and an association to a state object that is known abstract. Every single state decides on his own what is the following state dependent on the state of the holder object. So far your implementation as well.

But currently you are only hopping from one state to the other without doing something. You are currently not manipulating any object local variables of the holder object what will be the target of the state pattern. The manipulation is done in the for-loop. The holder object provides the information to the action() method of each state object. So here you distribute responsibilities between the holder object and the state object. My recommendation is to let the state objects decide on their own, when to get the next character. Because the "input" variable is not in object scope you should put it there. Doing this in the run() method will lead to an error prone and not thread enabled solution. So here I would pass the "input" through the constructor and make it object local available. No Parameter for the run() method anymore. For each Thread instantiate a fresh Fsm object with new input.

Furthermore you have at least one other "state" representation: isCompleted(). This should be represented as a state as well and not with a separate construct in the result.

What your implementation explicitly defines is the reuse of the state objects (caching).

In a special case you will not face any problem. That is if only behaviour is encapsulated in the state object no "state". So the state objects must not have object local variables to be modified (and of course no class variables too). BTW this is another pattern called flyweight. Its primary feature is immutability. So in your implementation you should ensure that your state objects are immutable.

If you have state within your state objects then you have to consider an initialization mechanism for your stateful state objects or always create new state objects. If you don't do that you introduce distributed states because the execution of the next state does not only depend on the state of the holder object. It also depends on the state of the following state object that the predecessor is not aware of. But every state object must be aware of ANY state to decide to what next state is to delegate. So if you have stateful state objects you must newly instantiate or initialize them or make them a flyweight. As your state objects hold no state you currently have no problem.

But one other thing is allowed. You may parametrize a successor with a result of a predecessor. I am not sure about any use cases but may pass information around because the current state object can decide on its own what to do. But in your example your are not passing anything around.

OK, what about the enum? Under the condition your state objects remain flyweights the enum is an unnecessary code fragment. You can remove the enum and introduce constants for each state object. If you have the intention to have stateful state objects I recommend to avoid reusing state objects. Of course you can initialize them but this is error prone. In this case it's also not necessary to have an enum.

Currently you are returning a complex object that consists of a boolean and the enum (the TYPE!!!) of the new state. I recommend to return nothing (void). The boolean as already stated can be seen as a separate state construct beside the existing state pattern which should be represented as a separate state object. The enum is obsolete when you use state object constants or newly instantiate state objects. The return value is obsolete if you provide a setState() method on the holder object. I didn't recognize until now that you haven't got a currentState variable held by the holder object. That has to be introduced.

Finally to make your Fsm (whatever this will be) generic you should provide a set of start states (public Set<..> getStartStates()) on the holder object. They will be accessible to the client object that uses an instance of Fsm. The client may pass one start state into the constructor.

As well you should provide a set of end states. Your loop should then only look like this:

while (!getEndStates().contains(currentState)){ currentState.action() }.

One thing I won't go into: To make Fsm generic I assumed to have flyweight state objects. If you do not have flyweights you will go deep into meta modelling. Then you would introduce a type level. BTW your enum was somehow something like this but under the assumption of flyweights unnecessary and under the assumption of stateful state objects insufficient.

To answer your question finally: It's not the standard way to implement the state pattern and it has its pitfalls because of that.