Listing the playlists on which each song appears

Use Map for fast lookups

The main performance cost is the search for songs

The best way to get better lookup performance is to use a Map to store the songs. Maps use a hash to lookup items and is very fast once the Map has been created.

You can create a map as follows, it adds an array for the playlist.

const songMap = new Map(songList.map(name => [name,{name,playLists:[]]));

Then you iterate the playlist and the songs it contains, adding the playlist to each song

for (const [playListName, songs] of Object.entries(playlists)) {
    for (const songName of songs) {
        const songItem = songMap.get(songName);
        if (songItem) {
             songItem.playLists.push(playListName);
        }
    }
}

You can then iterate the songMap and create the final object containing songNames with arrays of playlists

 const songPlaylists = {};
 for(const song of songMap.values()) {
       songPlaylists[song.name] = song.playLists;
 }

Then convert to JSON if you need.

Why the processed store?

However I would argue that the whole process is pointless unless you are extracting some higher level information from this process.

Ideally you would store the songs in a Map and each playlist also stored in a Map and would contain a Map of songs. Thus you can lookup playlists a song is in as follows

  function findSongPlaylists(songName) {
      const playlists = [];
      for (const playlist of playlistMap.values()) {
          if (playlist.songs.has(songName)) { playLists.push(playList.name) }
      }
      return playlists;
  }

To further improve the store, you would assign a unique id (a number) to each song and playlist and use the and do all the searches using ids. This will give even better performance and save a huge amount of RAM.

For casual viewing it is the ideal.

BTW the link you provided showing how you extracted the song data has a very long way of getting the data. All that data is store in the page indexed DB and can be extracted and saved to disk with a few lines of JS. (no need to scroll the page). Use Dev tools > application tab and open indexedDB to find the data.

Update Extra

Looking through the link you posted Copy Google Play Music songs all the solutions required rather hacky method (due to song list being a view) of slowly scrolling over the data to acquire it. The question is locked thus I am unable to add a better answer. As this question is related I will add a better way of sourcing the data here.

Paste the following snippet into the Dev-Tools console and hit enter. It will extract all the songs and save them to your download directory as a JSON file (named music_[your id].tracks.json)

The json file contains (data refers to the parsed json file)

data.fields an array of field names in the same order as in the array
data.tracks an array of records (one per song) containing fields in the same order as in  data.fields.

Note I do not use Google Music (Used a friends account so had limited time) and hence I guessed the content. You can add extra fields if you find the array index. To get a single record go to dev-tools > application (tab) > indexedDB > music_[your id] and select a record.

Example record extracted from music_####.tracks For security ids have been masked with # or A...

"########-####-####-####-############":["########-####-####-####-############","Sheep","https://lh4.ggpht.com/AAAAAAA-AAAAAAAAAAAAAA_AAAAAA...","Pink Floyd","Animals","Pink Floyd","sheep","pink floyd","animals","pink floyd","Roger Waters","Rock",null,620059,4,0,0,0,1977,0,null,null,0,0,1372528857298236,1408583771004924,null,"AAAAAA...","AAAAAAAA...",2,"",null,"AAAAAAA...","AAAAAAAA...",128,1372582779985000,"https://lh3.googleusercontent.com/AAAAAA_AAAA...",null,null,[],null,null,null,null,null,null,null,null,null,null,"AAAAAA...",[],null,null,null,null,0,null,null,[["https://lh3.googleusercontent.com/AAAAA...",0,2],["https://lh3.googleusercontent.com/AAAAA...",0,1]],true,6,null,1],

To keep the file size down the data is in an array. Nulls have been converted to 0.

(function () {
    console.log("From https://codereview.stackexchange.com/a/213683/120556"); // DO NOT REMOVE THIS LINE if you publish this snippet.
    console.log("Just a moment locating music DB...");
    const data = {
        dbName:"",
        info: "From Google Play Music App IndexedDB.\nField names in order of song array index.\nTo keep JSON size down null has been replaced with 0.\nDates ar in micro seconds 1/1,000,000 sec (I don't know what date1, date2, date3 represent)\nImages may require additional query properties.\nSource https://codereview.stackexchange.com/a/213683/120556",
        fields: "GUID,song,image1,band,album,albumArt,composer,genre,length,track,tracks,disk,disks,year,plays,date1,date2,bitrate,date3,image2".split(","),
        tracks: [],
    };
    const idxs = [0,1,2,3,4,5,10,11,13,14,15,16,17,18,22,24,25,34,35,36]; // idx of info to extract. There are many more field,
    indexedDB.databases().then(info => {
        const name = data.dbName = info.find(db => db.name.indexOf("music_") === 0).name;
        indexedDB.open(name).onsuccess = e => {
            console.log("Extracting tracks fro DB " + name);
            const t = e.target.result.transaction("tracks", IDBTransaction.READ_ONLY);
            t.oncomplete = () => {
                Object.assign(document.createElement("a"), { download : name + ".tracks.json", href: URL.createObjectURL(new Blob([JSON.stringify(data)]), {type: "text/json" })})
                    .dispatchEvent(new MouseEvent("click", {view: window, bubbles: true, cancelable: true}));
            }
            t.objectStore("tracks").openCursor().onsuccess = e => {
                if (e = e.target.result) {
                    Object.values(JSON.parse(e.value)).forEach(t => data.tracks.push(idxs.map(i=>t[i]===null?0:t[i])));
                    e.continue();
                }
            }
        }
    }).catch(()=>console.log("Sorry can not complete data dump :("));
})()

To extract a record from the JSON

// data is the parsed JSON file
const songName = "A song name";
const songFieldIdx = data.fields.indexOf("song");
const track = data.tracks.find(rec => rec[songFieldIdx] === songName);

To convert track array record to track object

const trackObj = {}
for(const field of data.fields) { trackObj[field] = track.shift() }


First, about free(). If you need memory, you call malloc() and it will give you a pointer that points to a block of memory that is yours now. The OS will (hopefully) take care that no one else will use this memory. But, as with all resources, be it sockets, open files or threads, you will have to relinquish this memory at one time. At the latest, when your application exits. Better, before that, ideally the moment you don't need it anymore. And that's what free() is for. That pointer you got from malloc()? Give it to free() and you're telling the OS that you're done with this particular block of memory. This will allow other programs to reutilize the memory and keeps your memory footprint small. However, that means that you shouldn't use this memory yourself again. The mean thing is that using the memory anyway might not crash your application right away. That's why it's always a good idea to set a pointer to NULL right after freeing it. That way, if you try to use this pointer again, it will crash directly, making it more obvious where the error is.

If you don't free memory you allocated, it's a memory leak. Especially if this happens periodically, it can be a real problem, because the longer your program runs, the more memory it consumes. Memory it doesn't use, but other programs might need. So always free your memory. Use tools like valgrind to check for leaks and other problems.

Now, to your function. I spotted one little error:

struct accListNode *temp = theList->head;
free(theList->head);
theList->head = temp; // Does nothing
theList->head->next = temp->next; // Potential crash

I think the first line should read

struct accListNode *temp = theList->head->next;

Otherwise, the third line does nothing (it's just the first line in reverse) and the fourth will sooner or later lead to a crash because you're accessing free'd memory.

Then, there's the second case, where there's only one element in the list. Are you sure you want to remove that element without first checking if it's actually the data that was requested to be removed?

And a small optimization in the last case:

for(cur = theList->head->next; cur != theList->tail; cur = cur->next)

You've already established that the data to remove isn't in the tail or head, so you don't need to check them again.
The rest is just stylistic:

if(theList->head == NULL)
    return;

Even if it's only one line, it's good practice to put braces around it:

if(theList->head == NULL) {
    return;
}

Also, you use struct accList a lot. You can make a typedef like so:

typedef struct accList accList

It looks a little weird, but after that, you can replace all your struct accList with just accList. To better distinguish it from a variable name, I also recommend renaming it to AccList.


It would be better to do your evaluation only for the particular elements that could be affected each time rather than to reevaluate all of them on any change in any input.

We can rewrite this to pass along the element that triggered the event and the ID of the element that we want to update the style on. Take a look at this:

function quantityCheck(eventElement, quantity) {
 //try to use const or let instead of var.
 //by passing 'this', we now have the target element that triggered the event,
 //so we only need to grab the one we want to change.
 const quantToChange = document.getElementById(quantity);

 //we can also use a tertiary function to make our change to shorten things a bit.
 quantToChange.style.display = eventElement.value.length ? '' : 'none';
}

    Quantity 1
    <input type="number" id="Quantity1Value" oninput="quantityCheck(this, 'Quantity2')" required>

    Quantity 2
    <input type="number" id="Quantity2Value" oninput="quantityCheck(this, 'Quantity3')">

    Quantity 3
    <input type="number" id="Quantity3Value" oninput="quantityCheck(this, 'Quantity4')">

    Quantity 4
    <input type="number" id="Quantity4Value">


Comment on the builder pattern

I don't think that Joshua Bloch discovered any new version of the builder pattern. I suggest to follow the standard way and purposes from the GoF.

The purposes of the builder pattern are:

avoid having a lot of constructor parameters
provide a default and preserve consistency to be able to ALWAYS build an object
make the code fluently readable

I think here the pattern is not appropriate and not implemented in the way it should be. The Update()-method for example has nothing to do with any builder pattern.

A guess on the intention

As you mentioned a "repository" you are dealing with some kind of persistence context. In your implementation the build()-method will create a new object in the repository and the update()-method wil update an existing object in the repository so far I understand.

Proposal, creation and result

The design I would follow is a natural approach.

If you want to create a new resource then you create a proposal object that contains data that may be considered during a creation process. The proposal object itself may have been constructed by a builder pattern. That depends on the purposes mentioned in the first place.

After that the proposal object is passed into the creation process. It will be validated and checked against internal system consistency. The creator object is well defined as the responsible for the creation of the wished object (SRP).

If no validation errors occured and it is not violating the systems consistency the object ist created AND persisted. The object may be internally (in the responsible object) constructed through the builder pattern. But that has nothing to do with persistence.

Proposal, update and result

The same with the update. The only difference is that you have an update proposal, an existing object to update and a responsible object that will to the update process.

Now it's getting interesting. The result of the update can be a versioned new object xor a cached old object. This depends on if you want to work with immutability or not. As you have an "id" I suggest to have the objects cached and mutable.

Nevertheless you have to override equals and hashcode in both scenarios. But be careful: two objects of any version are equal if their id is equal.

Conclusion

Do not make the builder pattern return mutable objects, always return new objects. The "builder" pattern is meant to "build" something not to update something
Only build transient, never involve persistence in the builder pattern
Have a proper design for CRUD-Operations for your persistent objects (business objects??) and well defined responsibilities
Distinguish between proposal, creator/updater/deleter and result

I am sorry, this is more a design issue of your problem domain than a pattern issue.


Converting JSONP to JSON: Is this Regex correct?

The problem with the code is that it doesn't really express what you are trying to do:

apijson = re.sub(r'([a-zA-Z_0-9\.]*\()|(\);?$)','',jsonp)

The code would seem to indicate that you are trying to find and replace many instances of some regular expressions inside the string. However, you are really trying to strip parts off of the beginning and end. I'm also not a huge fan of regular expressions because they are usually pretty dense and hard to read. Sometimes they are awesome, but this is not one of those times.

Additionally, you aren't anchoring the regular expression to the beginning of the string which is what you'd need to strip off. The only case I could see that being a problem is perhaps if there were strings inside the json which matched the regular expression. Its best to be sure.

Also, I think JSON-P allows functions like alpha["beta"] which will doesn't fit your regular expression. Also what about additional whitespace or comments?

I would suggest doing something like:

   apijson = jsonp[ jsonp.index("(") + 1 : jsonp.rindex(")") ]

That way you are more clearly stripping everything outside of the first and last parenthesis.


First, the usual disclaimer about performance: most of the time, you shouldn't worry much about it. If you find that your code is too slow, you should measure to find out which part is causing the slowdown and improve that. Trying to make code that's not performance critical more efficient is often a waste of your time.

In your specific case, I don't think the calls to First() would hurt your performance. But I would understand if you wanted to fix that to make your code more DRY. To do that, you could use Select():

var cpuInfo = edgeLPs
    .GroupBy(e => e.CPU.ID, e => e.CPU)
    .Select(g => new { id = g.Key, cpu = g.First() })
    .ToDictionary(g => g.id, g => new
    {
        LogicalProcs = g.cpu.LogicalProcessorsCount,
        Cores = g.cpu.Cores.Count,
        SMT = g.cpu.SMT
    });

Though the change from .First() to something like .cpu isn't actually much of an improvement.

Also, I think that using First() like this can be a sign of faulty logic. If you know that there will be always at most one CPU with a given ID, then you should use Single() instead, or, in your case, simply use ToDictionary() without the preceding GroupBy(). If there can be multiple CPUs with the same ID, i think you should figure out what to do with the rest of them, and not simply ignore all but the first one.


Fetching ALL data set from API iterating via response data

I only have some minor additions, maybe a little syntax sugar. I've tested most of it in the JavaScript console, and it still needs at least some JSBin trials before going live.

function retrieveBatch(offset){
  var opts = {
    limit  : 100,
    offset : offset || undefined
  };

  return new Promise(function(resolve, reject){
    chargebee.subscription
      .list(opts)
      .request(function(err, value){
        // return only if err is defined
        err && return reject(err);
        // if you got this far, there's only one way out
        return resolve(value);
      })
  })
}

function retrieveAll(){
  var subscriptions = [];

  function inception(data){
    if(!data){
      return retrieveBatch().then(inception);
    }
    if(data.list){
      subscriptions.push(data.list);
    }
    if(data.next_offset){
      return retrieveBatch(data.next_offset).then(inception);
    }

    return _.flatten(subscriptions);
  }
  return Promise.resolve(inception(false))
}


Yes, you can add more functionality to your project. You can take this in many different directirons such as adding courses that students and register for.

As for a error handling, you could add a check in your set functions of the Student class to check for formatting or content and return a boolean value based on if they pass the validation or not. For example, since studentnum is a string, you can check to make sure that the format of letters and numbers if correct, if there is a certain format.

You could also use a try-catch block around the code where you read in the values from the user. Or validate that the user enter an acceptable value for each entry such as checking that when the user is asked to enter the age, check to make sure that they did indeed enter a number.


Yes there is a thread safety issue. While the getIterator() is synchronized, the Iterator it returns is not. LinkedHashMap supports removal through the values() view, and hence the Iterator can be used to modify the Map without proper synchronization.

  UserRecord userRecord = new UserRecord();
  populate(userRecord);

  Iterator iterator = userRecord.getIterator();

  iterator.next();
  iterator.remove(); // unsynchronized modification of the Map

The easiest solution is to use Collections.synchronizedMap() which basically does what you attempted.

private Map<String, ClientHandler> container;

public UserRecord()
{
    container = Collections.synchronizedMap(new LinkedHashMap<>());
}

If you do this, the methods on UserRecord no longer need to be synchronized.

As an aside, you will want to properly use generics.


Split the array so that the sum of the numbers on one side of the split equals the sum of the numbers on the other side

The solution to this problem is easy, once you know the trick.

The trick, is to calculate the sum of all values then do add/subtract until they match...

This is very different to what you have done, so it does not really make sense to review your algorithm, and then say 'you did it wrong'.

What I will do, is say your code is neat enough, and the logic you have done is visible enough, to make the algorithm clear. Even though it is not the best algorithm, you have implemented it well.

The problems with your algorithm are that you are doing the following:

you are calculating the sums of each side of the split each time
you are calculating all possible splits, even if you could identify a successful split sooner
The Pairs and other classes are overkill for the solution you could have....

So, the following code (on ideone too) makes the 'simple' solution 'obvious'....

public static bool CanArrayBeSplit(int[] intArray) {
    int sum = 0;
    foreach (int v in intArray) {
        sum += v;
    }
    int left = 0;
    int right = sum;
    for (int i = 0; left != right && i < intArray.Length; i++) {
        left += intArray[i];
        right -= intArray[i];
    }
    return left == right;
}
public static void Main()
{
    Console.WriteLine("Testing: " + CanArrayBeSplit(new int[]{1,2,3,4,5,6,7,8,9}));
    Console.WriteLine("Testing: " + CanArrayBeSplit(new int[]{1,2,3,4,5,6,7,8,9,45}));

}


Is this an efficient way to use one event for multiple controls?

The problem is not in switching between senders but the fact that each branch calls a different method on inBank. I would suggest creating an enum for the denominations:

enum Denomination {
  Quarters,
  QuarterRolls,
  Nickels,
  NickelRolls,
  ...
}

and having a single setter in inBank:

void set(Denomination denomination, int value);

Then you can create a dictionary of controls to denominations:

IDictionary<NumericUpDown, Denomination> dict = new Dictionary<NumericUpDown, Denomination>();
dict[bkI_Ls_Quarters] = Denomination.Quarters;
dict[bkI_Rl_Quarters] = Denomination.QuarterRolls;
...

and your event handler would simply be:

private void BankInChanged(object sender, EventArgs e)
{
    var objSender = (NumericUpDown) sender;
    Denomination denomination = dict[objSender];

    currBoat.inBank.set(denomination, Convert.ToInt32(objSender.Value));
    currBoat.updateTotals();
    updateStatDisplay();
}


Prologue

To be frank, this is a sub-optimal problem to be applying object-oriented programming concepts, for two reasons that I can think of:

It is only a trivial step to extract the first subsequence of digits from a String, and
Java has a number of built-in methods to do that.

Object-oriented programming concepts are more applicable to richer classes ("models") with appropriately-scoped actions, in layman terms. For example, you may want to drive(Direction.FORWARD) a Car, make a Duck quack() or process(Message) messages using a MessageProcessor.

Learning the APIs, or the Alternative Approach

Before any attempts to write new code, you often need to understand what are some of the existing solutions to the problem at hand. This implies you need to be reasonably familiar with the provided features/APIs from your programming language of choice, and subsequently third-party libraries.

Using Java as an example, unless it's for self-learning purposes, I will not expect to see new and extremely similar variations of a List implementation for every codebase or project I come across: I simply expect the use of the ArrayList objects to do that.

So, conveniently, what are the some of the other available solutions for this? Regex, Pattern and Matcher come into play:

public static int getFirstNumber(CharSequence input) {
    Matcher matcher = Pattern.compile("[0-9]+").matcher(input);
    return matcher.find() ? Integer.parseInt(matcher.group()) : -1;
}

What is being done here:

The pattern "[0-9]+" (or "\\d+") represents a subsequence of digits we want to find, which must at least be a digit long.

The surrounding parentheses specifies that we want to reference our matches using grouping: Following clarification by @Boris the spider.
The Pattern object here represents the regex pattern, and certain interactions it can have with String (or more accurately, CharSequence) inputs.

We then pass our input to matcher() to create our Matcher object.

The Matcher object here represents the results of applying the regex pattern on the input.

We then 'ask' by matcher.find() to see if we have matched any subsequences.

If we do, we can get our first match by matcher.group(), else we return -1 as you have used as such.
edit: As suggested by @ Machinarius, you may consider throwing an Exception to indicate that no subsequences were found.

You want new features? Sure! Matcher has other methods that lets you process on the input iteratively. For example, you can use it to iterate till the last subsequence, you can combine all hits into a larger number, etc. It is not as restrictive as you might think.

Hopefully, this shows you why you do not have to keep writing new code every time.

Reinventing the wheel?

Now, suppose you do not wish to rely on regex for this problem. What are some of the improvements you can use for your solution?

You should make your methods static, as it is generally not a recommended approach to keep creating wrapper objects for 'one-off' operations.

Instead of storing textToParse as a class-level field, pass it between your methods.

You should only look for the last index if startIndex is not -1. It's nice that you do a bit of input validation here, but that becomes redundant if you structure your method calls correctly.
The return statement from numberAt(int) should just be return letter >= '0' && letter <= '9', since it's redundant to use an if statement here.
As far as my understanding goes, there isn't a clean, short and simple way to de-duplicate the two loops you are running across the getIndexOf... methods. Well, I can think of a slightly more fluent way using Java 8's IntStream and IntPredicate but I'll defer that suggestion for the time being, partly also because I don't think it's a good fit.
Consistent bracing, this can be a pet peeve of some developers... Java's recommended way of using braces for methods (and if statements) is actually in my alternative solution above.

Unit testing

Last but not least, one of my more favorable topics here... It is not good enough to just display the output of your method. You need to perform assertions on the output to ensure your method is working as it should. This is where unit testing frameworks like JUnit, TestNG and Hamcrest matchers come into play to facilitate the writing of unit testing code. As a quick illustration, you should have a something similar to the snippet below that can be run as a unit test. Somewhat conveniently, both JUnit and TestNG are using their respective @Test annotations, so it wouldn't make a difference here. assertThat() and equalTo() are from the Hamcrest library.

public class IntegerParserTest {
    @Test
    public void doTest() {
        assertThat(Integer.valueOf(IntegerParser.getFirstNumber("abc123xyz456")),
            equalTo(Integer.valueOf(123)));
    }
}


I was about to propose some changes to your code to reduce the line-count (and get rid of those @cached objects, bad idea IMHO), but I think it's the big picture what it's failing here. Some notes:

You are creating an OrderForm abstraction when in fact Rails gives all the infrastructure you need to write this in Order in a simple and very concise way.
All those validations belong to each model, validating them from an outside class is not a good practice.
Use accepts_nested_attributes_for (in models) + fields_for (in views) so the associations are automatically (and transparently) handled by Rails.

[EDIT] Regarding the non-cached approach, a glimpse of what I'd write:

order = @item.order || build_order
order.customer = @customer
shipping_address = order.shipping_address || order.build_shipping_address
shipping_address.attributes = params.slice(:shipping_name, :shipping_street,...)


To me, that's exactly Bubblesort: it takes care the largest element moves to the end of the array, and then operates on length-1 elements.

Edit: this does look quite similar to Bubblesort, but - as a diligent reader noticed - is not quite Bubblesort, as the algorithm does not compare (and swap) adjacent elements (which indeed is the main characteristic of Bubblesort). If you replace array[j] > array[i] with array[j] > array[j+1], you will get Bubblesort.

This implementation will fail if less than two input elements are given (0 or 1) - hint: the array is already sorted in these cases (just add an if).

A small improvement would be to add a flag in the i loop which records if any swapping happened at all - the outer for loop may terminate if the inner loop didn't perform any swaps. (Time) performance of Bubblesort is considered to be awful in comparison to other algorithms, but it must be noted it's the fastest algorithm on an already sorted array - if you add that flag ;)


Making additional subclasses at any time should be as painless as possible

You don't need a separate class for it!

I don't see any real difference between a Bandit and a Skeleton and a regular monster. You don't add or change any methods in the subclasses, and you don't add any new variables (other than the static ones).

The most important change you can make here is to only use one class. And then you'd want different methods to instanciate that class. This can be considered factory methods

A current smell of your code is that your call to the super constructor is a very long one and it's using many variables and some calculations on them. Factory methods will deal with this.

I also think that you are overusing static variables. There are a bunch of ways to deal with this but in this example I will just put them as local variables in a method. A future extension would be to create a MonsterConfiguration class that keeps these variables as fields, then you can create several MonsterConfigurations, and perhaps read some MonsterConfigurations from XML?

In your Monster class, add String name as a parameter to the constructor and remove the abstract keyword from it.

public Monster createBandit() {
    int minDefense = 1;
    int maxDefense = 1;
    int minStrength = 1;
    int maxStrength = 3;
    int minAttack = 1;
    int maxAttack = 3;
    int maxHp = 4;

    int defense = random.nextInt(maxDefense-minDefense+1) + minDefense;
    int strength = random.nextInt(maxStrength-minStrength+1) + minStrength;
    int attack = random.nextInt(maxAttack-minAttack+1) + minAttack;
    int hp = random.nextInt(maxHp-minHp+1) + minHp;
    return new Monster("Bandit", defense, strength, attack, hp);
}

I would suggest moving these things to fields in the class or perhaps preferably, methods of the Monster class:

    double min = minDefense+minStrength+minAttack+((double)minHp/10);
    double max = maxDefense+maxStrength+maxAttack+((double)maxHp/10);
    double avg = ((max+min)/2)-4;
    averageLevelDouble = (double)Math.round((avg/STATS_PER_LEVEL)*10)/10;
    averageLevelString = (Math.round(min)-4)/STATS_PER_LEVEL + "-" +
                 (Math.round(max)-4)/STATS_PER_LEVEL;

These methods could be called something like: getMin, getMax, getAvg, getAverageLevelDouble, getAverageLevelString.

Now if you want to have a Skeleton, just make a createSkeleton method.


Is there a route to the end of the jump table?

All paths do not return

    def canJumpPos(pos):
        if pos >= len(nums):
            return False
        elif pos in memo:
            return memo[pos]
        else:
            for i in range(nums[pos], 0, -1):
                if canJumpPos(i + pos):
                    return True
            memo[pos] = False
            # Missing Return

This means canJump([3,2,1,0,4]) returns None, not False!  A violation of your declared -> bool return.

No memoization of True

When this code returns True:

                if canJumpPos(i + pos):
                    return True

memo[pos] is never set to True.  This means that if canJumpPos(pos) is called called with the same pos value, it will have to redo all the work it has already done to return the same True value!

Eschew offset additions, assiduously

            for i in range(nums[pos], 0, -1):
                if canJumpPos(i + pos):

Here, you are always using i + pos, never i by itself.
Instead of repeating this addition over and over again,
you could roll that addition into the range() end-points.

            for i in range(nums[pos] + pos, pos, -1):
                if canJumpPos(i):

Any and All

Looping over some condition until you find a True condition:

            for i in range(nums[pos] + pos, pos, -1):
                if canJumpPos(i):
                    return True
            # ...

is often better performed using any(...):

            if any(canJumpPos(i) for i in range(nums[pos] + pos, pos, -1)):
                return True
            # ...

The any(...) will terminate when the first True is found, and return True.  If no True value is found, it will return False.

There is a similar function all(...), which will terminate at the first False returning False.  If no False value is found, it returns True.


Conway life game implementation with scala

The main-things I changed:

Matrix is now completely immutable
Code is more self-documenting (extract complex code to methods, etc.)
I deleted the unnecessary inheritance
I don't like apply-methods which are used as contains-methods -> name change
I deleted parentheses in side-effect free methods
Many syntax improvements

The code:

object LifeGame extends App {
  case class Point(x: Int = 0, y: Int = 0)

  object Matrix {
    def empty: Matrix =
      Matrix(Set.empty)
  }

  case class Matrix(private val data: Set[Point]) {

    def contains(p: Point): Boolean =
      data contains p

    def update(p: Point, b: Boolean) =
      if (b) copy(data+p) else copy(data-p)

    def iterator: Iterator[Point] =
      data.iterator

    override def toString = {
      def best(func: (Int, Int) => Int)(p1: Point, p2: Point) =
        Point(func(p1.x, p2.x), func(p1.y, p2.y))

      val minBoundary = (Point() /: iterator) { best(math.min) }
      val maxBoundary = (Point() /: iterator) { best(math.max) }

      val sb = StringBuilder.newBuilder
      for (i <- minBoundary.x to maxBoundary.x) {
        sb.append("\n")
        for (j <- minBoundary.y to maxBoundary.y) {
          sb.append(if (this contains Point(i, j)) "x" else " ")
        }
      }
      sb.append("\nmin=%s, max=%s" format (minBoundary, maxBoundary))
      sb.toString
    }
  }

  object Engine {

    def newCell: (Boolean, Int) => Boolean = {
      case (true, 0 | 1) => false
      case (true, 2 | 3) => true
      case (true, _) => false
      case (false, n) => n == 3
    }

    def apply(input: Matrix): Matrix = {
      def block1D(i: Int) =
        Seq(i-1, i, i+1)

      def block2D(p: Point) =
        for (x <- block1D(p.x); y <- block1D(p.y)) yield Point(x, y)

      def points =
        (input.iterator flatMap block2D).toSet.par

      def calcCell(p: Point) = {
        val neighbours = block2D(p) filter { p != }
        val alive = neighbours map { input contains } count { true == }

        if (newCell(input contains p, alive)) Some(p)
        else None
      }

      val cells = (points map calcCell).seq collect { case Some(p) => p }
      (Matrix.empty /: cells) { (result, p) => result(p) = true }
    }
  }
}


About your code:

I am glad you liked the idea of building the inverse structure programmatically, but here I don't think it's necessary :) Only two aminoacids have the same weight, I'd write the reversed hash.
Why residue instead of aminoacid?
I don't see why you need take_while here.
xs.reduce(0) { |acc, x| acc.method(x) } -> xs.reduce(0, :method).
Minor detail: personally I prefer explicit uses of $stdin.readline instead of gets.

I'd write:

module Rosalind
  MONOISOTOPIC_MASS_BY_AMINOACID = {
    "A" => 71.03711,
    "C" => 103.00919,
    "D" => 115.02694,
    "E" => 129.04259,
    "F" => 147.06841,
    "G" => 57.02146,
    "H" => 137.05891,
    "I" => 113.08406,
    "L" => 113.08406,
    "K" => 128.09496,
    "M" => 131.04049,
    "N" => 114.04293,
    "P" => 97.05276,
    "Q" => 128.05858,
    "R" => 156.10111,
    "S" => 87.03203,
    "T" => 101.04768,
    "V" => 99.06841,
    "W" => 186.07931,
    "Y" => 163.06333,
  }

  def self.problem_prtm(aminoacids_string)
    aminoacids_string.
      chars.
      map { |aminoacid| MONOISOTOPIC_MASS_BY_AMINOACID[aminoacid] }.
      reduce(0, :+)
  end
end

protein = $stdin.readline.rstrip
weight = '%.3f' % Rosalind.problem_prtm(protein)
puts(weight)

Same idea, slightly different approach:

module Rosalind
  ...
  def self.problem_prtm(aminoacids_string)
    aminoacids = aminoacids_string.chars
    masses = MONOISOTOPIC_MASS_BY_AMINOACID.values_at(*aminoacids)
    masses.reduce(0, :+)
  end
end


My main issue with this code is the function interface as you already identified yourself. These are the most glaring issues in my opinion:

Parameter names are not clear. Names like i and n might be good enough in very short, self-contained loops/closures, but not as function parameters. I similarly don't like abbreviations like orig, and cur because the full words are not much longer. Always consider you first see this function, is it original or origin, is it current or cursor? Your interface should be clear without reading the code.
You are always passing a full string slice while you know you will only read from a certain offset (i).
Passing n is redundant, as almost any check that you do against this can be replaced by checking if you reached the end of orig.
Similarly but less obvious passing i is redundant. The obvious part is related to the first point, if you only pass the slice this represents offset 0. Now, you also use this as a cache key, but that's not necessary. If instead of passing the full slice you only push the 'remaining' string you can use this as cache key to exactly the same effect.
You insert true in the cache, which requires it to be a map, but there are several reasons why this is useless. I'd just use a HashSet that is only updated for false. Reasons are as follows:

If you found a 'true', the function finished anyway.
When indexed by usize and with this judging system you can't use the cache for multiple string inputs (and never for multiple word inputs). So the true cache is even useless here.
But even if you could re-use the cache, the true adds little, because you can quickly prune the false branches already.

You explicitly end with return false;, it is more idiomatic to simply say false (without the semicolon).
You have a whole construct that basically loops over a splitted version of your input. This can be significantly simplified by using the built-in split_at.

Based on all this I refactored your original algorithm to the following:

use std::collections::HashSet;
impl Solution {
    fn dfs(remaining: &str, words: &HashSet<String>, mut cache: &mut HashSet<String>) -> bool {
        for i in 1..remaining.len() + 1 {
            let (word, remaining) = remaining.split_at(i);
            if words.contains(word.into())
                && !cache.contains(remaining.into())
                && Self::dfs(remaining, &words, &mut cache)
            {
                return true;
            }
        }
        if remaining.len() == 0 {
            true
        } else {
            cache.insert(remaining.into());
            false
        }
    }
    pub fn word_break(s: String, word_dict: Vec<String>) -> bool {
        let set = word_dict.into_iter().collect::<HashSet<String>>();
        let mut cache = HashSet::new();
        Self::dfs(&s.as_str(), &set, &mut cache)
    }
}

This may not yet be ideal, I for example don't like remaining and dfs as names. Other improvements you could try but are honestly overkill for a braintease exercise:

It seems somewhat weird to pass words and cache as a parameter. More idiomatic would be to make a WordBreakChecker struct. You provide it with a new initializer that sets the cache and words, and then have a single dfs (or better check) function that only takes the string as input.
In my example I still index the slice explicitly by using a for loop and split_at. That's good enough for here, but it may be interesting practice to implement the Iterator trait to iterate over these combinations directly (honestly, it may exist already in std or a crate, I didn't look to hard).


I would recommend moving the database access stuff from your "View Controller" and into more of a data access controller (think DAL).

Also, it's been a bit since I've used Entity Framework, but if I remember right, you can take the following code:

var applicants = context.Applicants.GroupBy(a => a.EmailAddress)
                                 .Select(grp=>grp.FirstOrDefault())
                                 .ToList() ;
List<ApplicantList> applicantList = new List<ApplicantList>();

foreach (var a in applicants)
{
   //get Jobs for each applicants
   var query = from dba in context.Applicants.Include("Jobs")
                        where a.EmailAddress == dba.EmailAddress
                        select dba.Jobs;
   List<Jobs> jobs = query.ToList();
   applicantList.Add(new ApplicantList (){ Applicant = a, Jobs = jobs });
}

viewModel.Applicants = applicantList;

viewModel.Jobs = context.Jobs.ToList();

And replace it with:

var applicants = context.Applicants.Include("Jobs").ToList();

If Entity Framework is set up right, it should pull in the Jobs that are tied to each applicant automatically.  It is highly recommended to create DTOs based off of your Entity Framework entities though, so you can cut off any circular reference pitfalls (in this case, make sure that the Jobs object doesn't reference the Applicants object).

For the most part though, this doesn't look as bad as a lot of the code that I have run into that has made it into actual production environments.


Some quick remarks:

Don't start variable names with underscores unless they're class-wide private ones.
Local variables should be camelCased. OutputXML doesn't follow that rule.
Split your code into smaller methods that don't intermix data retrieval and file writing. Your method does multiple things, depending on some (odd) logic. Even its name doesn't make sense: it's called SqlExtract yet it generates CSV or XML files depending on seemingly arbitrary conditions.
Don't hardcode your connection string. Put it in a .config file and access it via the ConfigurationManager.
Why do _con.Open(); and _con.Close();? The using takes care of this.
Don't loop through table1.Rows. Instead have a method that transforms a DataRow row into a csv line and use that to construct a IEnumerable<T>, which you then can use in combination with string.Join(). Something like var csvContents = string.Join(Environment.NewLine, table1.Rows.Cast<DataRow>().Select(x => DataRowToCsvLine(x)));. That's one line (instead of 20) which expresses far better what your code does (and yes, the DataRowToCsvLine method is also a couple of lines, but it doesn't pollute the main logic).
row[1].ToString() == "END": are you sure it is always going to be "END"? Or is it possible it can be "end"? Consider using string.Equals() instead, which allows for case insensitive comparisons. Same for fileName == "item1" etc.
Properly dispose of StringWriter with a using block. Example: https://social.msdn.microsoft.com/Forums/vstudio/en-US/7d949d5c-a41c-4dc7-bbcb-429761f851d1/is-calling-flush-and-close-necesary-for-stringwriter-and-xmltextwriter?forum=netfxbcl

None of the above might improve the speed of your code, but it will make it much more maintainable and consistent.


Yes, this is the right way to do it.

Many Clojure programs do not bother with creating empty maps. The absence of a value or nil behave like an empty map. For example (assoc nil :foo :bar) returns {:foo :bar}. You may be able to initialize to an empty sorted-map, and only assoc-in novelty as you need it ... depending on your logic.


There are a few issues that I see in your code. I'm not sure if all matter, but I'll try to list them anyway.

You said you call AESROUND<<< 8, 16, 16 >>>(1024);, but you present __global__ void AESROUND_AD(const int SIZE). Are AESROUND() and AESROUND_AD() the same kernels? Is that a typo?
Calling AESROUND<<< 8, 16, 16 >>>(1024); means (amongst other) that you dynamically allocate 16 (third parameter of the <<< >>>) elements of a shared memory segment of type to-be-defined inside the kernel (declared extern __shared__ whatever mySegment[];). So you allocate that segment in your kernel call, but do not actually declare in the kernel body. Yet another typo?
In the kernel itself, you reference dev_state which isn't declared anywhere. Is that a global variable? Shouldn't that be better put a input parameter of the kernel?
The computation of tid explicitly assumes that the block size is 16, which is true here. However, if this changes when calling the kernel, then the formula would become false. So if this isn't supposed to change, then use a macro for the block size (such as #define BLOCKSIZE 16) and use it in your definition of tid, and the call to AESROUND(). But if this size might change in the call of the kernel, then use tid = blockIdx.x * blockDim.x + threadIdx.x;. And as a more general comment, try to avoid "magic numbers" in your code, or at least put them into macros or const variables, so that you give them a sensible name and therefore a meaning.

Now, the initial question was about performance:
Well, I guess that this all boils down to one simple issue: you do not maximise neither your core occupancy, nor your memory bandwidth. Indeed, you only request 16 threads per block, which isn't even enough for a warp. Therefore, irrespective of your actual GPU architecture, at any moment, at most only half of your cores are utilised. Moreover, once the initial data loaded in shared memory, you only compute using 4 threads, so only utilising 1/4 of the available cores at most.

Considering what I can see (and sort of understand) of your kernel, I have the feeling that you'd better be using one single block of 128 threads per message to compute, and to load all of it at once in your shared memory. Then to compute as you do in your kernel, but with now 4 times more threads involved. This would have the double benefit of permitting you to avoid having to store you partial results in global memory at each round, and to increase your occupancy.

And to fully utilise your GPU, you would need to compute several messages in parallel, one per block.


metafunction to determinate the biggest of all supplied types

How about this? It’s not all that much shorter, but IMHO quite a bit simpler:

#include <type_traits>

template <typename A, typename... B>
struct max_type
{
    typedef typename max_type<A, typename max_type<B...>::type>::type type;
};

template <typename A>
struct max_type<A>
{
    typedef A type;
};

template <typename A, typename B>
struct max_type<A,B>
{
    typedef typename std::conditional<(sizeof(A) > sizeof(B)), A, B>::type type;
};


The delete function is not right. It is very non-optimal to shift every item by one index after each deletion. Imagine the queue has 1 million items and the deletion of front element is needed.

From Wikipedia:

  Fixed length arrays are limited in capacity, but it is not true that
  items need to be copied towards the head of the queue. The simple
  trick of turning the array into a closed circle and letting the head
  and tail drift around endlessly in that circle makes it unnecessary to
  ever move items stored in the array. If n is the size of the array,
  then computing indices modulo n will turn the array into a circle.

So, you should use a Circular buffer.

This video has a good explanation of queue and circular buffer: Data structures: Array implementation of Queue.


Factor script to change case of all filenames in a directory

Comments! Comments are good, especially to people who are just learning Factor right now. Admittedly, for Factor, it's pretty readable -- I finally got it, after staring a while and doing lots of Googling -- but comments are always nice.

I can't find anything about the : name>something ( etc -- etc ) word syntax online -- namely, the >something part. Because of that, I'm just gonna assume that it's good syntax and move on. Alright, I finally found it! And yes, that's good syntax -- you're supposed to use a>b for functions converting a to b, and that's exactly what you do. It might be better called directory-file-names>upper/>lower, but that's just personal preference.

It looks good, though. After figuring out how Factor works, it's pretty readable (for Factor), and actually makes me want to use the language more. Plus, as far as I can tell, you're following the official coding style to the letter. Well done.


Find the next 8 dates that are Mondays (exclusive of today)

I think you may have a bug (depends on how the calculation should work). If today is a Sunday, the mondayOffset will be 7 - (0 - 1) == 8, meaning the entire upcoming week will be skipped. In other words, mondayOffset will always be in the range 2-8. I'm guessing that's not what you want.

When dealing with dates, I find it simpler to deal with them as just dates, rather than as millisecond timestamps. Also, with timestamp arithmetic there's always the risk of time zones messing things up for you (for instance when going to/from daylight savings time).

Besides a millisecond number, the Date constructor also accepts separate arguments for year, month, date, hour, etc.. The neat thing is that if you pass a date that doesn't exist, like June 33rd, it'll automatically roll over to July 3rd.

So you can just increment the date argument as needed to produce valid dates in the future:

var app = angular.module("angularApp", []);
app.controller("appController", function($scope, $filter) {
  $scope.mondays = [];

  var today  = new Date(),
      year   = today.getFullYear(),
      month  = today.getMonth(),
      date   = today.getDate(),
      offset = 8 - (today.getDay() || 7); // days till next Monday

  for(var i = 0 ; i < 8 ; i++) {
    $scope.mondays.push( new Date(year, month, date + offset + 7 * i) );
  }
});
body {
  font-family: verdana;
  font-size: 10pt;
}

{{date | date}}

Here the offset will be in the range 1-7, so if today's a Sunday, it'll only skip 1 day ahead.


Predicting random numbers based on past output

You need to find or create a Mersenne Twister rainbow table. In other words, pre-compute all (or some subset) possible outputs, store them (time-space tradeoff), and compare the series you receive to the stored series.

The article quoted in https://stackoverflow.com/questions/6618836/how-if-at-all-does-a-predictable-random-number-generator-get-more-secure-after suggests the number of values you need to store may be much smaller.


Why not separate the 2D element into two parts.

The interface that can be used
The shared resource

Used by the Draw2D interface
Used by the D2Elements.

Then D2Elements does not need to depend on an object that can go out of scope, they have partial ownership of the shared resource (with any common data that they and the Draw2D needs.

class Draw2D
{
    // interface as before
    // Weak pointers as before.

    std::shared_ptr<SharedResource>   data;
};

class D2Element
{
    //... As before.

    std::shared_ptr<SharedResource>   sharedData;
};

Even of the Draw2D's lifetime ends, then the shared resource (because it is shared with any created children) will not die and thus not be destroyed.


Process a line in chunks via Regular Expressions with Ruby

Because you're using the "bang" version of gsub, parse_line modifies the string you pass to it, which is generally a not a good idea. I wouldn't expect a parsing method to "eat" my input.
Since there's only one line and your regexes are anchored to the start of it, there's little point in using gsub (i.e. global substitution), since you'll only ever match 1 occurrence of the pattern.
Don't bother with all the newline literals. puts will automatically add one, and if you want an extra one, you should be able to just say puts with no argument in a strategic location (i.e. after having tried all the patterns).

This seems like a good fit for Ruby's case statement (aka switch) since you can match against regexes directly. And Ruby also sets other magic variables besides $1 and $2 whenever you match a regex. There's no reason to make the method recursive, though. A simple loop would do nicely too.

For instance:

def parse_line(line)
  puts "Processing: #{line}"

  # Loop until the string's empty (or we hit the return below)
  until line.empty?
    # Try matching the line
    case line
    when /^(\d+) 0 -1 1 (\d+) \d+\s*/
      puts " - Matched format 1 - found: #{$1} - #{$2}"
    when /^\d+ 0 -1 2 (\d+) \d+\s*/
      puts " - Matched format 2 - found: #{$1}"

    # more patterns...

    else # no match
      puts " - Line still has data but no matches found. (Left with: #{line})"
      return # stop here
    end
    line = $' # set line to the *unmatched* part, i.e. the remainder
    puts "" # output an extra blank line
  end

  puts "Entire line matched, yay"
end


Check if we find new value from a request

Global code
Move the code after your __main__ check into a function, since it's still in global scope.
PEP8
firstReq should be first_req, and the same for new_req.
Dict comprehension
I would rearrange your filtered comprehension to be only a dict, and to use dict.update. In other words,
filtered = {r: self._requests.get(r) for r in requests}

self._requests.update({
    r: time
    for r, orig_time in filtered.items()
    if orig_time is None or time - orig_time >= self._cooldown
})

List comprehension
    firstReq = []
    for _ in range(random.randint(1, 5)):
        firstReq.append(f"US {random.randint(1, 10)}")

can be
first_req = [
    f"US {random.randint(1, 10)}"
    for _ in range(random.randint(1, 5))
]

Diagnostic printing
    print(self._requests)

is out-of-place. Remove it, and if you still want this to happen, issue an equivalent statement from main(), perhaps printing the entire RequestFilter and overriding __str__ to return pprint.pformat(self._requests).
Change detection
Apparently what you actually want is to return a boolean that is true if self._requests has changed. This can be done like:
filtered = {r: self._requests.get(r) for r in requests}

old_requests = dict(self._requests)

self._requests.update({
    r: time
    for r, orig_time in filtered.items()
    if orig_time is None or time - orig_time >= self._cooldown
})

return old_requests == self._requests


A few notes:

I am confused as to why you need AngularJS for this.
I prefer to use the bitwise & with 255 instead of 0xFF in this case.
Your function can't handle non-hex characters such as #.  I would remove them before parsing.
You can simplify your creation of the RGB string by using the join() method.

Final function:

function hexToRgb(hex) {
    hex = hex.replace(/[^0-9A-F]/gi, '');
    var bigint = parseInt(hex, 16);
    var r = (bigint >> 16) & 255;
    var g = (bigint >> 8) & 255;
    var b = bigint & 255;

    return [r, g, b].join();
}


Note: I'm sorry if this is completely irrelevant but I'm not entirely sure what you are trying to accomplish. If I'm way off base please let me know.

When I create a template loader I generally use output buffering with php include. This allows you to run the page as a php file without displaying its content before you are ready. The advantage to "parsing" your php files this way is that you can still run loops and functions.

This is how your loadFile method would look.

<?php

function loadFile($file, array $variables = null) {
  try {
      if (file_exists ( $this->dir . "/" . $file )) {

          // start output buffering
          ob_start();

          // create variables from the key/value pairs in the array
          if( is_array($variables) ) {
              extract($variables);
          }

          include_once $this->dir . "/" . $file;

          // store the output
          $this->text = ob_get_clean();

          // $this->text = file_get_contents ( $this->dir . "/" . $file );
      } else {
          throw new Exception ( $this->dir . "/" . $file . " does not exist" );
      }
  } catch ( Exception $e ) {
      error_log ( $e->getMessage () );
      die ();
  }
}

?>

As I said before, I'm not sure what kind of templates you are trying to load, but hopefully this will help.


This can actually be solved with a super efficient 1 line of code, but the explanation is long :)
(and there are a few other things I should point out first)

Your code will fail with any input bigger than \$2^{62}\$ because you never overshoot this number by multiplying by 2 a power of 2 (in your code: current). This is because a signed long has only enough bits to represent powers of 2 up to \$2^{62}\$ (you could have used it as an unsigned variable to have one extra bit, but it still wouldn't be enough to avoid this problem with the biggest numbers that the challenge says are expected input), multiplying it by 2 will cause the left most bit to become 1, which turns it into a big negative number, and multiplying it by 2 again will make it 0 which will then stay 0 no matter how much you multiply it, so your code will enter an infinite loop.

Once you detect that a number is a power of 2 you shouldn't reset previous and current to 2 because a power of 2 divided by 2 is still a power of 2, so you know you can divide current by 2 together with n.

A thing you could use to your advantage is the way powers of 2 look in binary code:

power | number | binary | even/odd power
2^0   = 1      = 00001  | even
2^1   = 2      = 00010  | odd
2^2   = 4      = 00100  | even
2^3   = 8      = 01000  | odd
2^4   = 16     = 10000  | even

Notice how all bits are 0 except one, the position of this 1 bit tells you if you need an odd or even number of divisions (turns in the game) to reach 1.

long filter = 0b101010101010101010101010101010101010101010101010101010101010101L;
boolean oddPower = (n & filter) == 0;

As soon as you reach a power of 2, this check is enough to tell you who's gonna win. An odd number of turns left means that the player whose turn it is now will win, otherwise the other player will win.

We can go further with looking at the bits and bypass the need to find the next lower power of 2 to divide n by it if n is not a power of 2. As you already know, any power of 2 is represented by a single 1 bit and lots of 0 bits. Now let's take a look at a few numbers represented in binary code:

3 = 0011
4 = 0100
5 = 0101
6 = 0110
7 = 0111
8 = 1000

When the number isn't a power of 2, according to the game you need to remove the next lower power of 2. In binary it's gonna look like removing the left most bit (you can look at the numbers above to confirm this). Given our knowledge and solutions so far, we can rewrite the rules of the game to simple binary operations:

if ( number is a power of 2 ) then:
    use the check from the previous part of my answer to figure out the winner.
else:
    turn the most left 1 bit to 0.

This means the number of turns until we reach a power of 2 and find the answer depends on how many 1-bits are in the number, and knowing if this number is odd or even - combined with the answer to whether the power you reach is odd or even - is all you really need to know to predict the outcome of the game!

Let's test this solution: here's what you see when you track the changes in a number as the game is played, in binary:

1000000110100
0000000110100
0000000010100
0000000000100
0000000000010
0000000000001

There are 4 1s (even number) but you don't remove the last 1 bit so ignore it and say there are 3 1s to be removed (odd number) and the first power of 2 you reach is 4 (even) so overall there will be an odd number of turns taken in the whole game, which you can see is true.

Here is the most optimized code I could possibly write to solve this:

static String counterGame(long n){
    boolean richardWins = true;

    while((n & 1) == 0){
        richardWins = !richardWins;
        n >>>= 1;
    }
    while(n != 1){
        if((n & 1) == 1)
            richardWins = !richardWins;
        n >>>= 1;
    }

    return richardWins ? "Richard" : "Louise";
}

This code looks at each bit once, so the time complexity of this code is O(log(N)) where N is the input number, and log(N) is the worst case scenario for the number of bits needed to represent the input number in binary.

Judging by the fact that the exception to the rules (where Richard wins when Louise gets the 1 at the start of the game) emerges naturally with this solution if you don't add an if statement at the start to take care of it, I'd say this is what the author of this challenge expected to be the best possible answer.

Bonus

There are processor instructions for counting 1 bits and trailing zeros, so you could actually do the whole thing in one line instead of manually looping through the bits, and using these processor instructions is faster:

static String counterGame(long n){
    return ((Long.numberOfTrailingZeros(n) & 1) == 1) ^ ((Long.bitCount(n) & 1) == 1) ? "Richard" : "Louise";
}

EDIT: a shorter code suggested by @JS1:

  By subtracting one, it turns all the trailing zeroes into trailing ones, so that they can be counted by bitCount.

static String counterGame(long n){
    return ((Long.bitCount(n-1) & 1) == 0) ? "Richard" : "Louise";
}


Testing if the binary representation of an integer has an odd number of ones

Leveraging code that other people wrote is always a great idea. In this case, there is count_ones:

fn odd_ones(x: u32) -> bool {
    x.count_ones() % 2 == 1
}

This method is a shim for the LLVM intrinsic @llvm.ctpop.i32, which seems likely to become the very optimized SSE4.2 popcnt instruction when available.

Beyond that, you have some poor indentation habits. Rust uses 4-space indents, not the 3 (?!?) spaces you have in your odd_ones function.

There should not be a space between a function name and the arguments, whether in the function definition or the function call. Your test method should be fixed.

Be consistent with your spacing on commas. No space before, one space after. |sum ,y| is just wrong.

You should give names to magic constants. A rogue 32 laying around doesn't mean anything. Give it a name like BITS_IN_U32. There's an unstable constant that you might be able to use someday.

When mapping and folding over an iterator, you might as well put all the mapping into the map call. There's no reason to do the bitwise-and in the fold.

I have no idea what !0 - 45345 is supposed to mean or why those particular values are useful. That's bad news when you try to understand this code in the future.

const BITS_IN_U32: usize = 32;

fn odd_ones(x: u32) -> bool {
    x.count_ones() % 2 == 1
}

fn odd_ones_test(x: u32) -> bool {
    let sum =
        (0..BITS_IN_U32)
        .map(|y| (x >> y) & 1)
        .fold(0, |sum, y| sum + y);
    sum % 2 != 0
}

fn test(from: u32, to: u32) -> bool {
    (from..to).all(|x| odd_ones_test(x) == odd_ones(x))
}

fn main() {
    println!("{}", test(!0 - 45345, !0));
}


I think in your case you can just do this:

document.body.style.background = colorChosen;

Avoiding all the ugly if else part.

A more robust solution will be using a lookup table to decouple the DOM ids from the proper colors string:

const colorFor = {
    "somethingRed": "red",
    "somethingBlue": "blue",
    "somethingBlack": "black"
};

...

document.body.style.background = colorFor[colorChosen];

With somethingBlaBla I mean a meaninful name that not contains the color.
The purpose is to contain the changes in case you want a different color in the future or if you want that more options have the same color.

Another improvement is to have a guard condition to avoid errors or weird situations:

var buttonClick = this.addEventListener ("click", function(e) {
    console.log(e.target.id + " button was clicked");
    var colorChosen = e.target.id;

    if (!colorFor[colorChosen])
        return false;

    document.body.style.background = colorFor[colorChosen];

});

Instead of just return from the function you can log an error or pup up a dialog with a warning to inform the user.
Or you can reset to a default color the background.

In the same way you can use a style instead of setting the color on the DOM element.

This could be better in some situation, depends on your app code convention.


Grouping, merging and mapping with a timetable

A review mostly focusing on style:

Avoid calls to console.log in clean code (it's okay for debugging, but should be removed afterwards)
Try not to declare variables in for statements ( the variable is accessible to the whole function anyway). Try to declare variables on top
Your code could use more comments, especially this part which was hardest to parse/grok:

     if (arr[i] - ranges[lastIndex][1] === 1) {
         ranges[lastIndex][1] = arr[i];
     } else {
         ranges[++lastIndex] = [arr[i], arr[i]];
     }

Other than that there is not much wrong with the code, I tried to write it in a more elegant way, but found my attempts usually longer and not that much more elegant.


Time optimization of counting shifts in insertion sort

Insertion sort is an O(n2) algorithm.  There's only so much you can do to optimize it.

This is a bit of trick question.  It doesn't actually ask you to sort the arrays in question; it just asks you to count the number of shifts involved.  So, for each element to be "inserted", just count the number of preceding elements that have a larger value.

Stylistically, your program should be modularized.  Each of the T test cases is independent, so isolate each test case in a function.  You probably don't have to buffer the results, either — just print the result from each test case as soon as you have the answer.


Enums

Java enums have been around for a long time, so it's really a waste not to be using them at this point.

However, I understand that this may simply be an exercise, to test and build your understanding of Java, one step at a time.  If that is the case, (or maybe if the exercises are given in a specific order, and you haven't yet progressed to the Chapter on enums) then maybe you are intended to avoid them.  I'll work on that assumption (no enums).

Representation

  Named constants for the four suits (CLUBS, DIAMONDS, HEARTS, SPADES)
  and the four ranks that are traditionally represented in words (ACE,
  JACK, QUEEN, KING).

A named constant simply means that in code, your Java can refer to constant values with variable names that are meaningful.  It does not mean that those constants must be Strings, and usually, they should not be.  If you have:

public class Carta {

    public static final int REI = 11;

then, this code is using a named constant:

int rank = REI;

while this code is not:

int rank = 11;

  The values of the rank constants should be 1, 11, 12, and 13, respectively.

This clearly is requesting an implementation where the constants are integer types, not String objects:

public static final int AS = 1;      // Ace
public static final int VALETE = 11; // Jack
public static final int DAMA = 12;   // Queen
public static final int REI = 13;    // King

(you'll have to double check my values .. I don't speak Portuguese, and I think I recognize the word Rei and Dama, but not the others)

These constants are in addition to the other cards, ranked 2 through 10.

Specification Terminology

  ... that are traditionally represented in words

This language may be confusing, I understand.  When they say "words", they're not asking for String constants.  They are referring to the fact that, outside of JACK/QUEEN/KING/ACE, the other cards are 2,3,4,5,6,7,8,9,10 ... which are numbers.

Comments

You have some comments here (again, with my limited understanding of Portuguese), that I believe are backwards:

// Constantes do Naipe (Rank) das Cartas
public static final String AS = "Ás";

// Constantes do Valor Facial (Suit) das Cartas
public static final String COPAS = "Copas";

As (or Ace) is not a Naipe, it is a Valor (value, or rank).  Even if the code is correct, it's important in software development to make the comments correct, too.

toString()

Finally, concerning the specification for toString(), I believe that your existing code satisfies the requirement.  But, remember, the constants really should be implemented as integers, not String constants.  So, if you rewrite the class to represent values as integers, you'll then need a new method to convert integer values to Strings.

A HashMap<Integer,String> would probably work for that purpose.  If you haven't gotten to using generics yet, even an array of strings (String[]) could be used to map int values to String, as long as you keep track of the 0 index, or use the 0 index element as an Invalid value.


Extracting the unsigned calculation just to solve the possible overflow problem is unnecessary. Of course, having an unsigned version of the function may be useful for other reasons in "real" code, but that would be a different motivation.

You can handle your problem here with a simple variable, and not a whole function:

double myPow(double x, int n) {
    unsigned int p = abs(n);
    double result = 1;
    while(p > 0)
    {
        if(p & 1) // if bit is set
        {
            result = result * x;
        }
        p = p >> 1;
        x = x * x;
    }

    if(n < 0)
    {
        return 1/result;
    }
    return result;
}

Changing the unsigned part to use the unsigned int p instead of n, and then using n to test for the negative later is just fine.

Now, a more general review...

Your comment (the only one), is not great, the code here is obvious:

if(p & 1) // if bit is set

I would remove the comment, or change it to // for odd powers

I needed to take some time to figure out how you did the algorithm, and how it works out to \$O(\log{p})\$ (where p is the power) complexity. It's an "advanced" solution, and in that respect you can be proud of it. I am trying to figure out how to make the algorithm more obvious though. It's complicated that the result is only set on odd-powers in the shifting. Comments on your algorithm would help, but I am sure there's a way to make the process more obvious in the code... I'm still thinking.

Regardless, the code style is good, your variable names are not great, but are not horrible for 1-letter names either.

Overall, with a better description of the mechanics of the solution as comments in the code, I would call it good.


Your properties are nullable even tough they are never null and assigned in the constructor. Declare them as

protected val database: MongoDatabase

This way, the child classes can access them without needing the safe-call operator and also you prevent them from overwriting the property.

Also, both of your methods call database.getCollection("users"). This is a sign that you need to extract the collection to a property rather than the database or client.

Also, it's better to pass a MongoClient or even a MongoDatabase to the constructor because it can be shared between multiple repositories and follows the dependency injection pattern.

Because you now have only one property, you can drop the init block.

abstract class BaseRepository<Entity>(db: MongoDatabase, collectionName: String) {
    protected val collection = db.getCollection(collectionName)

    abstract fun insertOne(e: Entity)

    abstract fun findOne(username: String) : Entity
}

I also got rid of the unnecessary semicolons.

Now to the child class. val userDocument =  collection?.find(Document("username", username))?.first() returns a nullable  Document?. But in the line below you cast the members to String which will throw an exception if the value was null. To get proper null safety, declare the return type of the method as nullable

abstract fun findOne(username: String) : Entity?

and rewrite the implementation, e.g. like so

override fun findOne(username: String): User? {
    val userDocument = collection.find(Document("username", username)).first() ?: return null

    return User(
            userDocument.get("chatId") as String,
            userDocument.get("username") as String,
            userDocument.get("email") as String
    )
}


We can create 676000 robots with unique names, because we have 26 possibilities for each 'letter position' and 10 possibilities for 'number position' in our name. So calculation is 26 * 26 * 10 * 10 * 10 = 676000.

Why am I mentioning that? Because that number is not so big and maybe it's worth to consider pregenerating all possible values, keep them in pool and get/return when necessary. That's another approach. I don't want to say that it's better. It will be more memory consuming solution, but robot 'initialization' will be faster. Also it'll be easier to apply fix for point 6. Anyway, you should always get what suits your requirements.

End of digression - back to your code!

Why I can't see namespaces both in tests and in class? You copied it that way?
I understand why you set up Random as static, but it's not thread safe the way you implemented it. Reference: [JON SKEET ARTICLE]
Static readonly HashSet is very dangerous, because it's instance is shared between all threads and Hashset.Remove method could cause strange problems/exceptions in multithreaded environment. Of course no one is saying that in requirements, but I think that case should never be ignored. ConcurrentDictionary should be your choice in here, because it ensures thread safety. [MSDN]
Letters in alphabet will never change, so you can keep it as a const field. Thanks to that you'll avoid allocation string for each time somebody tries to generate random letters.
In case for readability I have nothing to add it's pretty clear what's happening here.
Last, but most important, comment from my side. A little challenge for you :) what will happen with your code when you create 676000 robots and try to create one more? Hint: you can use code from Robot_names_are_unique() test method, but increase upper limit of iterations to 676000.

Hope this helps!


Check if an element is present within a linked list - follow up

The construct

for i in range(0, len(seq)):
    node = Node(seq[i])

is usually frowned upon. Consider a Pythonic

for item in seq:
    node = Node(item)

I see no reason to default seq to None.
append does not append. It prepends.
remove has an unpleasant code duplication. To avoid special casing the head, consider using a dummy node:

def remove(self, item):
    dummy = Node(None, self.head)
    prev = dummy
    while prev.next:
        if prev.next.data == item:
            prev.next = prev.next.next
            size -= 1
        prev = prev.next
    self.head = dummy.next

printdata may (or shall?) use the iterator:

def printdata(self):
    for node in self:
        print node.data


SQL Look up in a Stored Procedure across three tables

Does your EmployeeID and PropertyID parameters really need to be varchar(max), I find it hard to believe that an employee would have an ID with 8 000 characters. The same goes for the property ID. Change this to how many characters they are allowed to have (e.g., if an employee can only have an ID of 8 characters then use that, if it's 100 characters use that, and if it indeed is 8 000 characters, well then I suppose varchar(max) is fine)

I'd also advocate to use clearer aliases for your column. Instead of as PId you should alias it as as PropertyID.

This line is a bit unclear to me WHERE   TblA.RegionID > 0. Can a Region have an ID of 0 or less-than 0?

I also think that the LIKE in this line TblA.PropertyID LIKE '%' + @PropertyID + '%' is used for the wrong purpose. It seems like what you really are doing is comparing the PropertyID of TblA.PropertyID to the parameter @PropertyID and in my opinion there should be no need of using wildcards here. Instead use the equals operator.


Mixing controlled/uncontrolled behaviour with `getDerivedStateFromProps`

There is a small and subtle issue with your usage of getDerivedStateFromProps.

getDerivedStateFromProps is invoked right before calling the render
method, both on the initial mount and on subsequent updates. It should
return an object to update the state, or null to update nothing.

and

Note that this method is fired on every render, regardless of the cause.

Your implementation returns a new state object every render regardless, but it should return null when nothing needs to be updated. By returning a new state object each render then unnecessary re-renders may occur in children components if passed any values from this component's state as they would fail shallow object comparison.
class OptionsRow extends React.PureComponent {
  state = {
    currentPage: 0
  }

  ...

  static getDerivedStateFromProps(props, state) {
    if (props.pageSize !== state.prevPageSize) {
      // Reset page on pageSize change
      return {
        currentPage: 0,
        prevPageSize: props.pageSize
      }
    }

    // Nothing changed, return null to keep existing state
    return null;
  }

  ...

}

However, in 3+ years working with react I've not ever had any compelling reason to reach for getDerivedStateFromProps and the docs even specify

This method exists for rare use cases where the state depends on
changes in props over time.

The last bit bolded is the important bit. Your component's behavior appears to simply be an effect of a prop updating, i.e. a side-effect to reset state, and could be implemented via the componentDidUpdate lifecycle method.
Solution 1 - Bronze
class OptionsRow extends React.PureComponent {
  state = {
    currentPage: 0,
  }

  ...

  componentDidUpdate(prevProps, prevState) {
    // Reset page on pageSize change
    if (this.props.pageSize !== prevState.prevPageSize) {
      this.setState({
        currentPage: 0,
        prevPageSize: this.props.pageSize,
      });
    }
  }

  ...

}

But notice now that the state currentPage only needs to be reset when props.pageSize updates, so you can directly compare current and previous props and drop the storage of the "last" pageSize in local component state.
Solution 2 - Silver
class OptionsRow extends React.PureComponent {
  state = {
    currentPage: 0,
  }

  ...

  componentDidUpdate(prevProps) {
    // Reset page on pageSize change
    if (this.props.pageSize !== prevProps.pageSize) {
      this.setState({ currentPage: 0 });
    }
  }

  ...

}

There is still room for improvement though, using the third bullet point from the docs.

If you want to “reset” some state when a prop changes, consider either
making a component fully controlled or fully uncontrolled with a key
instead.

What this means is you can completely forego the getDerivedStateFromProps and componentDidUpdate logic to check and compare the props' pageSize value and simply use a react key that updates when the pageSize does.

When a key changes, React will create a new component instance rather
than update the current one.

Solution 3 - Gold
<OptionsRow key={pageSize} pageSize={pageSize} />


Database of students in a social network

Style

Indentation would make your query more readable.
Table names in MySQL may be case sensitive, depending on the underlying filesystem.  Therefore, it is safest to write the query using identifiers with the same case as stated in the problem.
SQL keywords are conventionally written in ALL CAPS, though some programmers object to that convention.
Single-letter names for table aliases are cryptic.  While I can somewhat understand friend f, I have a harder time accepting highschooler a.

Formulation

UNION, short for UNION DISTINCT, automatically deduplicates the result set.  If possible, prefer UNION ALL for efficiency.  However, in this case, you do need deduplication for the correct answer.
The two halves of the union seem repetitive.
Subtracting one from the final count is weird and risky.  I suggesting filtering out Cassandra herself from the result set.

Here's how I would write it:

SELECT count(Friend.ID1)
    FROM Highschooler AS Cassandra, Friend
    WHERE
        Cassandra.name = 'Cassandra'
        AND (
            Friend.ID2 = Cassandra.ID
            OR Friend.ID2 IN (
                SELECT Friend.ID1
                    FROM Friend
                    WHERE Friend.ID2 = Cassandra.ID
            )
        )
        AND Friend.ID1 <> Cassandra.ID;


Function that calls a function with the terminal temporarily set to raw mode

The sad fact is that your code should be even uglier. If f() throws an exception, you won't restore the resources correctly.

Idiomatic OCaml recommends that a recurring pattern can be described with a function. So you would define a function that takes:

a resource ('a)
a function to execute with the resource ('a -> 'b)
and a function to free the resource ('a -> unit)

The signature becomes:

val bracket : 'a -> ('a -> 'b) -> ('a -> unit) -> 'b

The bracket function would do the ugly let res = f() thing, but also wrap it with a try-catch.

UPDATE: The next version of OCaml (v4.08.0) looks like it will have a finally-type function added to the standard library: https://github.com/ocaml/ocaml/pull/1855


A Twitter bot that fetches Forecast.io data and tweets out the current weather with text and emojis

It looks pretty good to me. Just some minor notes:

Not that it's bad or anything, but in Ruby it's not usual to align code.
You can DRY the case block by creating a hash:

emojis_by_icon = {
  'clear-day' => 'sunny',
  'clear-night' => 'milky-way',
  ...
}

emoji_alias = emojis_by_icon.fetch(current_weather.icon, 'sunny')
icon = Emoji.find_by_alias(emoji_alias).raw

tweet = ... With long lines, I prefer to use the String#% interpolation:

tweet = "Currently it's %{temperature}° & %{summary} %{icon}" % {
  temperature: current_weather.temperature.round,
  summary: current_weather.summary.downcase,
  icon: icon,
}


let emptyGrid = (None, Array2D.init 3 3 (fun _ _ -> Mark.None))

This can be simplified using Array2D.create:

let emptyGrid = None, Array2D.create 3 3 Mark.None

In rotateCw and placeMark, x is used as the first index and y as the second. This is confusing, as the usual order is row then column. For instance,

let test = Array2D.create 3 3 Mark.None
test.[2, 1] <- Cross
printfn "%A" test

[[None; None; None]
 [None; None; None]
 [None; Cross; None]]

rotateCw can be simplified (assumes the indexing changes in the previous paragraph)

let rotateCw (grid : 'a[,]) = Array2D.init 3 3 (fun y x -> grid.[2 - x, y])

I find this version of placeMark a bit more readable

let placeMark (x, y) mark (_, grid : Mark[,]) =
    let res = Array2D.copy grid
    res.[y, x] <- mark
    (checkOutcome res, res)


1. Bug

Your program contains a bug. The second digit of 123456... is 2, but:

>>> d(2)
3

However, solving Project Euler problem 40 only relies on you having the correct result for d(10**i), and this you got right.

2. Improving your solution

There are no docstrings, so even though I have solved Project Euler problem 40 myself, it took me a while to figure out what your functions are doing. Even if you struggle to pick good names for functions (and this can be very hard), you can always make things clearer with a brief description and some examples.

There are also no doctests. Even a handful of doctests might well have found the bug.

The discipline of writing down what each function actually does will make it easier for you to choose good names. For example, once you have written the docstring for your function levels, it should be clear that a better name would be something like total_digits:

def total_digits(n):
    """
    Return the total number of digits among all the `n`-digit decimal
    numbers.

    >>> total_digits(1) # 1 to 9 (note that 0 is not included)
    9
    >>> total_digits(2) # 10 to 99
    180
    """
    return n * 9 * 10 ** (n - 1)

Choosing good names for variables is particularly hard when writing mathematical code (as when solving problems from Project Euler). It's typical of mathematical code that variables contain a number whose meaning is hard to capture in a short name. Long names would end up making your code hard to read, so it's often the case that the best approach is to give your variables arbitrary names like i, j, m, and n, and to explain their meaning in longer comments.
There's no need for level_filler to be a local function inside face_value (it doesn't make use of any context from face_value). If you moved it out to the top level then it would be easier to test it. (But in fact, it will be better just to remove it, as I will explain below.)
The expression int(levels(n)/n * 1.0) is the same as int((levels(n) / n) * 1.0) since multiplication and division have the same precedence and associate from left to right. So this expression converts levels(n) / n to a float and then back to an int, which is pointless. Also, since levels(n) is n * 9 * 10 ** (n - 1), when divided by n the result is always 9 * 10 ** (n - 1). It would be better to write this directly and avoid the useless multiplication by n followed immediately by division by n.
Similarly the expression int(math.ceil(i / n * 1.0)) doesn't do what you think it does: the division happens before the multiplication, so in Python 2 (where / truncates the result) this expression is actually the same as i // n and evaluates to the floor of the division, not the ceiling.
You make three calls to levels(n) in succession. It would be better to make just one call and remember the result.
The purpose of face_value(i) function is to return the number which contains the ith digit. This is where the bug lives:

>>> face_value(2)
3

In some sense you knew that this was incorrect, because you compensate for the error with your test if i == 1: return 1!

3. A better solution?

My own approach to this problem would be to simplify the structure as much as possible. The function levels is so simple (just a single expression) that we can easily inline it into face_value. And then various other simplifications become possible. Here's my version of your face_value:

def number_containing(i):
    """
    Return the number containing the `i`th digit in the sequence
    123456789101112...

    >>> number_containing(5)
    5
    >>> number_containing(13)
    11
    >>> number_containing(99)
    54
    >>> number_containing(100)
    55
    """
    n = 1                       # Number of digits.
    first = 1                   # The first n-digit number.
    count = 9                   # Count of n-digit numbers.
    while True:
        # The i-th digit is in the j-th n-digit number (but not if
        # there are more than j n-digit numbers).
        j = (i + n - 1) // n
        if j <= count:
            return first + j - 1
        first += count
        i -= n * count
        n += 1
        count *= 10

Having computed which number contains the ith digit, we then have to work out which digit it is, which you do using another sum over levels. In fact, it is much simpler to work out which digit you want at the same time as you work out which number this digit comes from. If you look at my function above, you'll see that all the information is already present at the point where we return the result. So it's easy just to return the digit at this point:

def d(i):
    """
    Return the `i`th digit of the sequence 123456789101112...

    >>> d(5)
    5
    >>> d(15)
    2
    >>> d(100)
    5
    >>> sequence = ''.join(str(i) for i in xrange(1, 10001))
    >>> all(d(i + 1) == int(digit) for i, digit in enumerate(sequence))
    True
    """
    n = 1                       # Number of digits.
    first = 1                   # The first n-digit number.
    count = 9                   # Count of n-digit numbers.
    while True:
        # Check the loop invariants.
        assert first == 10 ** (n - 1)
        assert count == 9 * first

        # The i-th digit is in the j-th n-digit number (but not if
        # there are more than j n-digit numbers).
        j = (i + n - 1) // n
        if j <= count:
            return int(str(first + j - 1)[(i - 1) % n])
        first += count
        i -= n * count
        n += 1
        count *= 10

Note that the last doctest is quite thorough!


Counting the positive integer solutions of an equation

(Remark: The question mentions "positive number of solutions", but from your code I assume that you meant "number of non-negative integer solutions".)

Coding style:

#include <cstring> is not needed here.
Don't use namespace std;, see for example Why is “using namespace std;” considered bad practice?.
long c; is only used in main(), so there is no need at all to declare it as
a global variable.
Always use braces { ... } for the body of for- and if-statements, even
if it has only one statement. It helps to avoid errors if additional statements
are added later.
Move the computation of the number of solutions to a separate function.
This keeps the main function small and is convenient if you add test cases.
I prefer a different spacing in for- and if-statements, but that may be a
matter of taste.
Variable names: If the equation is given as \$ x + y + xy = n \$, then why
not use the same names in your program? And x is a quite non-descriptive
name of a number of solutions.
It may not be immediately obvious why 2 is added to the number of solutions,
so an explaining comment would be appropriate here.

Then your code would look like this:

#include <iostream>

// Number of non-negative integer solutions to
//    x + y + x * y == n   .
long numberOfSolutions(long n) {

    if (n == 0) {
        return 1;
    }

    // Count all positive solutions:
    long count = 0;
    for (long x = 1; x <= n / 2; x++) {
        for (long y = 1; y <= n; y++) {
            if (x + y + x * y == n) {
                count++;
                break;
            }
        }
    }
    // Add 2 for the solutions x=0,y=n and x=0,y=n:
    return count + 2;
}

int main()
{
    long n;

    std::cin >> n;
    std::cout << numberOfSolutions(n) << std::endl;
}

Performance:

Your code tries all possible combinations of x, y to find solutions
and therefore runs in \$ O(n^2) \$. A small improvement could be to use the
symmetry of the problem, i.e. enumerate only pairs with x <= y:

for (long x = 1; x <= n / 2; x++) {
    for (long y = x; y <= n; y++) {
        if (x + y + x * y == n) {
            // Counts a 2 solutions if x != y:
            count = count + 1 + (x != y);
            break;
        }
    }
}

This cuts the total number of iterations down by a factor of 2, but it is still
\$ O(n^2) \$.

Better algorithm:

If you write your equation as
$$
  n + 1 = x + y + xy + 1 = (x + 1)(y + 1)
$$
then it becomes obvious that it can be solved by determining the
number of divisors of \$ n+1 \$. This known as the Divisor function and can be computed
efficiently.

Even the simplest implementation

long numberOfDivisors(long n) {
    long count = 0;

    for (long j = 1; j <= n; j++) {
        if (n % j == 0) {
            count++;
        }
    }
    return count;
}

runs in \$ O(n) \$ instead of \$ O(n^2) \$. More sophisticated methods use
the prime factorization  of \$ n \$ .


This is completely unnecessarily complicated:

needed_permissions_list = list(filter(None, needed_permission.split(".")))

This is equivalent:

needed_permissions_list = needed_permission.split(".")

The return True at the end of the if item != item2 is unreachable,
so you can delete that line.

item2 is not a good name. needed_item would be better, so you don't mix up which is which. It's important to know which is which, because the needed item must not contain *.

This is unnecessary:

    if permission_list[-1] == "*" and (permission_list[:-1] == needed_permissions_list):
        return True

This treats a special case, that the rest of the method automatically handles.
You can safely remove this part.

This is a shorter and simpler implementation:

def check_permission(needed_permission, permissions):
    needed_permissions_list = needed_permission.split(".")
    for permission in permissions:
        permission_list = permission.split(".")
        if permission_list == needed_permissions_list:
            return True
        zipped = zip(permission_list, needed_permissions_list)
        for item, needed_item in zipped:
            if item != needed_item:
                if item == "*":
                    return True
                else:
                    break
    return False

The assertions are not written in a Pythonic way:
you should avoid comparisons with True and False.
This is the Pythonic way:

assert check_permission("app.cat2.do.something", permissions)
assert not check_permission("app.cat2.do.something.special", permissions)
assert check_permission("app.cat1.some.task", permissions)
assert not check_permission("app.cat2.cat4", permissions)
assert check_permission("app.cat2.cat3.do.something.special", permissions)
assert not check_permission("something.completely.different", permissions)

Your spec is not very clear.
For example you didn't mention if the pattern a.*.c is valid.
Probably not valid, because your code doesn't handle the case (for example a.b.x will yield true).
Effectively, a pattern like a.*.c is handled as if it was a.*.
It's good to specify this clearly.

I don't really like this special treatment:

    if permission_list == needed_permissions_list:
        return True

Because this check has an overlap with the logic in the for loop:
if the two lists are not identical,
the loop will repeat some of the checks.
It would be better to get rid of this overlap,
see this alternative implementation:

def check_permission2(needed_permission, permissions):
    needed_permissions_list = needed_permission.split(".")
    for permission in permissions:
        permission_list = permission.split(".")
        zipped = zip(permission_list, needed_permissions_list)
        for item, needed_item in zipped:
            if item != needed_item:
                if item == "*":
                    return True
                else:
                    break
        else:
            return len(permission_list) == len(needed_permissions_list)
    return False

Finally,
another alternative implementation that also passes your assertions and somewhat simpler, taking a different approach without splitting to segments:

def check_permission(needed_permission, permissions):
    for permission in permissions:
        index_of_star = permission.find('*')
        if index_of_star == -1:
            if needed_permission == permission:
                return True
        else:
            normalized = permission[:index_of_star]
            if needed_permission.startswith(normalized):
                return True
    return False


Disclaimer: I have never used or implemented Pollard's rho algorithm.

calc_factor

I think this function does not need to be a nested function. It could be a normal function on its own (and thus be documented accordingly).

Maybe, its name and the name for its parameter could be updated for something that sounds more usual, maybe get_factor(n)...

Instead of checking if factor > 1 at the beginning of the loop, you could check if just after updating the value of factor.

Also, instead of trying to break out of 2 loops, you could simply return the value directly if factor > 1 and you realise you don't need to check the value of factor in other places.

You'd get something like:

def get_factor(n):
    x,x_fixed = 2,2
    cycles = 2

    while True:
        for counter in range(cycles):
            x = (x * x - 1) % n
            factor = math.gcd(x - x_fixed, n)
            if factor > 1:
                return factor
        x_fixed = x
        cycles *= 2

prime_factorization

Here again, you could probably rename the parameter for something shorter.

I am not sure what the conventional way to do is but once you get a factor with the other functions, it may be worth checking how many times it divides.

Potential issues

Finally, I have the feeling that the algorithm does not provide an real prime factorisation because the factors returned by calc_factor are not always prime factors, they are just "random" factors.

If it may help you, here is the function I've used many times for Project Euler factorisations:

def prime_factors(n):
    """Yields prime factors of a positive number."""
    assert n > 0
    d = 2
    while d * d <= n:
        while n % d == 0:
            n //= d
            yield d
        d += 1
    if n > 1:  # to avoid 1 as a factor
        assert d <= n
    yield n


Print total occurrences of a char in a string

The use of Map is unnecessary overhead. You can leverage the fact that chars can be mapped as ints along with a simple array to solve this problem.

private static final int OFFSET = 'a';

public String countNoOfInteger(final String str) {
    final int[] counts = new int[26];  // or 'z' - 'a' + 1, if you prefer
    for (final char character : str.toCharArray()) {
        counts[character - OFFSET]++;
    }

    final StringBuilder output = new StringBuilder();
    for (int i = 0; i < counts.length; i++) {
        if (counts[i] == 0) {
            continue;
        }
        output.append((char) (i + OFFSET));
        output.append(counts[i]);
    }

    return output.toString();
}

Some notes:

OFFSET could probably have a better name. I'll leave that as an exercise for the reader.
Contrary to other respondents, I heartily encourage the use of final as a statement of intent.
In a "real" system, it would be preferable to separate the business logic (find the letter counts) from the display logic (print them to the screen). In such a system, your method would return the counts int[] (or Map) and the caller (main(), in this case) would be responsible for displaying it (everything after the first for loop).
Note that this solution will fail spectacularly for invalid input. If that's something you need to handle, add a check to the first loop to ensure that character is between offset and offset + counts.length.


Am I dynamic filtering correctly in Django?

You can change the first method to

def get_filters(url, allowed):
    query = parse.urlsplit(url).query
    pack = dict(parse.parse_qsl(query))
    translated = {}

    for pk, pv in pack.items():
        if pk in allowed:
            translated[allowed[pk]] = pv

    return translated

Remove this condition, it's useless.

if filters:
    filtered_query = people.filter(**filters)
else:
    filtered_query = people

and just use

filtered_query = people.filter(**filters)

Maybe add search to the allowed filters? and improve the method to handle multiple values for a specific key.

allowed_filters = {
    'location': 'person_location',
    'role': 'person_role',
    'search': ['person_first_name', 'person_last_name']
}

```


Try

types = myTableList
    .Select(x => (int)x.item_type)
    .Distinct();

You may also want to add .ToList() at the end if you want to match original code