Flatten iterator for nested list in python3

Conceptually, this is a recursion problem.  You've unrolled the recursion into iteration to support the __iter__() method.  However, this is precisely the kind of problem that generators can solve trivially!  (Here, I've used yield from, which is a feature introduced in Python 3.3.)

from collections import Iterable, Mapping
from operator import methodcaller

def flatten(it, map_iter='values', max_depth=128):
    if max_depth < 0:
        raise RecursionError('maximum recursion depth exceded in flatten')
    elif isinstance(it, str):
        yield it
    elif isinstance(it, Mapping):
        for item in methodcaller(map_iter)(it):
            yield from flatten(item, map_iter=map_iter, max_depth=max_depth-1)
    elif isinstance(it, Iterable):
        for item in it:
            yield from flatten(item, map_iter=map_iter, max_depth=max_depth-1)
    else:
        yield it

I've named the parameter it, which is a triple entendre that can be interpreted as "iterable", "item", or just the third-person singular impersonal pronoun.

Instead of FullStackError, which leaks information about how your iterator is implemented, just use the built-in RecursionError.  Personally, I'd choose to scrap the depth limit altogether, since the Python interpreter's stack will have its own natural recursion limit.


Pinoniq has the right idea, which can be taken a bit further:

VideoFactory $vf = new VideoFactory();
Video $video = $vf->createVideo( "http://youtube.com/..." );
$video->setDimensions( 640, 480 );
$video->embed();

Here, the VideoFactory can parse a URL. The createVideo method would return a subclass of Video, which is a YouTubeVideo. However, the implementation need not be dependent on YouTube. This allows you to also write:

VideoFactory $vf = new VideoFactory();
Video $video = $vf->createVideo( "http://vimeo.com/..." );
$video->setDimensions( 640, 480 );
$video->embed();

You'll note that the only item that changed is the URL, but both video formats can be embedded.


Implementation of C Standard Library Function ntohl()

Unless you wish to optimize the code, with specialized swappers for various hosts orders, you are doing it wrong.

I invite you to check The Byte Order Fallacy by Rob Pike. The punch line: the byte order of the computer you are executing the code on doesn't matter, because the language abstracts it for you.

Thus, only the byte order of the network matters, and the network is big-endian:

#include <stdint.h>
#include <string.h>

uint32_t ntohl(uint32_t const net) {
    uint8_t data[4] = {};
    memcpy(&data, &net, sizeof(data));

    return ((uint32_t) data[3] << 0)
         | ((uint32_t) data[2] << 8)
         | ((uint32_t) data[1] << 16)
         | ((uint32_t) data[0] << 24);
}

This function will work no matter the endianness of the host, even on the crazy middle-endians ones.

Oh, and it optimizes well in general, in case you were wondering:

ntohl(unsigned int):
        mov     eax, edi
        bswap   eax
        ret

bswap being the native CPU instruction to swap bytes on x86.


A couple quick things to make maintenance easier:

It's easier to work out where you're going if you use continue instead of the goto. If you do keep the goto, I'd at least edit the comment to refer to the beginning of the while loop instead of a specific line number. That will change if you have to change something, and you don't want to have to remember to update the comment.

In terms of readability, when checking for order of operations, you could do something like

if (precedence(act2) > precedence(act1))

Then it would be easier if you wanted to add an exponent operator.


Your code is indeed correct but it is slow: for each day, you are looping over the whole array of numbers to determine if a given plant is killed in that day. You won't be able to optimize your approach further than what you already have. To validate the last 2 test inputs, you need to take another approach.

This problem can be tackled in O(n) complexity by only processing the input array once, from left to right, as was done in this other code review. The idea of the algorithm is to traverse it only once and calculate, for each plant, the number of days it will stay alive.

The observation that can be made is that the number of days plant i will stay alive is the number of days the right-most plant to the left of i that has less pesticide than i, incremented by 1. And if there are none, then the plant never dies. Taking an example:

 6   5   8   4   7   10   9
             |   +--------+
             |   |        |
             |   |        when will this plant die?
             +---|
             |   the day after this one dies and when will this one die?
+------------|
|            the day after this one dies and when will this one die?
|
never
|
+------------0---1--------2

Since we reached the beginning of the array, we know that the plant with pesticide 4 never dies, hence the plant with pesticide 7 dies on day 1 and the plant with pesticide 9 dies on day 2.

We can then improve this first approach. By going from left to right, if we hit a plant i that will never die, we can actually forget all the plants before and stop checking them because any plant waiting for one of those to die will have to wait for i to die first and we know that it will never happen.

In terms of code, this can be implemented by having a stack of a Plant class that would hold its pesticide count and the number of days it stays alive. For each number, we start from the top of the stack and look the closest plant behind having less pesticide; in the mean time, we keep a running daysAlive that is simply the maximum days alive of the encoutered plants and we remove them as we go on. If we reached the end and the stack is empty, it means the plant never dies so we set its daysAlive to 0 and push it to the stack. Otherwise, it means the plant dies the day after that one and we push it to the stack.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    int[] garden = new int[input.nextInt()];
    for (int i = 0; i < garden.length; i++) {
        garden[i] = input.nextInt();
    }

    System.out.println(maxDaysAlive(garden));
}

private static int maxDaysAlive(int[] numbers) {
    Deque<Plant> stack = new ArrayDeque<>();
    int maxDaysAlive = 0;
    for (int pesticide : numbers) {
        int daysAlive = 0;
        while (!stack.isEmpty() && pesticide <= stack.peek().pesticide) {
            daysAlive = Math.max(daysAlive, stack.pop().days);
        }
        if (stack.isEmpty()) {
            daysAlive = 0;
        } else {
            daysAlive++;
        }
        maxDaysAlive = Math.max(maxDaysAlive, daysAlive);
        stack.push(new Plant(pesticide, daysAlive));
    }
    return maxDaysAlive;
}

private static class Plant {

    int pesticide = 0, days = 0;

    public Plant(int pesticide, int days) {
        this.pesticide = pesticide;
        this.days = days;
    }

}


Ultra-simple, automatic, non-float, 1-4 column, grid system

This is not to take away at all from your system above, which is very smart.

I'm still very much on the CSS Grid learning curve and I was genuinely curious to see how straightforward / difficult it might be to replicate your output above, using CSS Grid.

.grid {
  display: grid;
  grid-template: repeat(4, 42px) / auto;
  grid-gap: 8px;
}

div p {
  margin: 0;
  padding: 0;
  line-height: 42px;
  text-align: center;
  font-family: sans-serif;
}

.box-1 {color: #fff; background-color: #4af;}
.box-2 {color: #fff; background-color: #fa4;}
.box-3 {color: #000; background-color: #def;}
.box-4 {color: #000; background-color: #fed;}

@media (min-width: 540px) {

  .grid {grid-template: repeat(2, 42px) / repeat(2, auto); grid-gap: 16px;}
}

@media (min-width: 800px) {

  .grid {grid-template: 42px / repeat(4, auto);}
}

col

col

col

col


The best way to do this would be to take each of your sections, and give them each a function of their own. Also, when it's possible, separate user input functions from purely logic to improve readability!

For example, it could start looking like this:

def verify_pin(pin):
    if pin == '1234':
        return True
    else:
        return False

def log_in():
    tries = 0
    while tries < 4:
        pin = input('Please Enter Your 4 Digit Pin: ')
        if verify_pin(pin):
            print("Pin accepted!")
            return True
        else:
            print("Invalid pin")
            tries += 1
    print("To many incorrect tries. Could not log in")
    return False

def start_menu():
    print("Welcome to the atm!")
    if log_in():
        # you will need to make this one yourself!
        main_menu()
    print("Exiting Program")

start_menu()

Whenever you can avoid nesting, you should. This makes it easier to read.

In this case you can clearly see logging in will open the main_menu (which you will have to write), and entering a correct pin is the only way to log in.


Stochastic gradient descent squared loss

You probably do not need help with this question anymore (looks like it's been a year), but I thought I'd point something out in case someone else finds it useful. I think your squared loss expression should be \$(w'*x - y)^2\$ and the derivative of that with respect to \$x\$ is: \$2*(w'*x-y)*w\$. What you have is the outer product which results in a matrix minus a scalar. So I noticed two errors:

You need an inner product instead of an outer product.
You applied the chain rule wrong when you took the derivative w.r.t x.


I'll start from what I perceive as "top" and work my way down.

  <form action="/api/blogPosts" method="post">
    <input onChange={this.handleChange} type="text" name="postbody"></input>
    <button type="button" onClick={this.handleClick}>Submit</button>
  </form>
  <List array={this.state.posts} />

You'd probably want to abstract the <form> into its own component. You can then expose a submit event, essentially just a callback handed down to a prop on the component. Your form component will call that callback, passing in the details you need for your AJAX.

Additionally, List and array don't really tell me anything. What kind of list is it? What's in the array? Better name them properly before you start scratching heads and lose hair.

Also, <input> doesn't need a closing tag.

// Better

  <PostForm onSubmit={this.handleSubmit} />
  <Posts posts={this.state.posts} />

componentDidMount: function() {
    $.ajax({
        type: 'GET',
        url: '/api/blogPosts',
        success: function(data) {
            this.setState({
                posts: data
            });
        }.bind(this)
    })
},

handleClick: function() {

    event.preventDefault();

    var blogPost = this.state.postbody;

    $.ajax({
        type: 'POST',
        url: '/api/blogPosts',
        data: {
            postbody: blogPost
        }
    });

    $.ajax({
        type: 'GET',
        url: '/api/blogPosts',
        success: function(data) {
            this.setState({
                posts: data
            });
        }.bind(this)
    })
},

I see that your GET request is redundant here. You can put that in a separate function, say loadPosts. Your functions don't really tell me anything either. Sure, they're handling a click, or respond to a mount but what are they doing?

Also, I see you're using jQuery. POST and GET requests have shorthand versions, $.post and $.get respectively.

When you handle the click, you call two AJAX operations in sequence. That sequence isn't guaranteed, especially when network latency is introduced. By the time you launched the GET, the POST might not have finished yet, and your GET return an incomplete list. It could also be that your POST succeeded, but GET failed. Usually, a POST request returns an updated version of the resource. Use that to just patch in the new data instead of retrieving the entire list.

Also, it's recommended you use the Promise interface of jQuery operations. tl;dr: use then instead of success, error, done or fail.

Since you're on React, I assume you use a transpiler setup. You can take advantage of new ES6 syntax, like arrow functions, shorthand literal assignment, shorthand literal functions

componentDidMount(){
  this.loadPosts();
},
onSubmit(post){
  this.submitPost(post);
},
loadPosts(){
  return $.get('/api/blogPosts').then(posts => this.setState({posts}));
},
submitPost(postBody){
  return $.post('/api/blogPosts', {postBody}).then(post => this.state.posts.push(post));
}

Now if your API can't handle returning the updated resource from a POST, you can simply call your GET after the POST suceeds.

submitPost(postBody){
  $.post('/api/blogPosts', {postBody})
   .then(() => this.loadPosts())
}

var List = React.createClass({

  render: function() {
    return (

        {this.props.array.map(function(post) {

          return (
            <Item postbody={post.postbody}></Item>
          )
        })}

    )
  }
})

Usually when I see nested functions, I just move out the function into the class instead of inline. Much cleaner, and less visual clutter. Also, Item doesn't really tell me what it is. What kind of item is this? If this is a post, then it should be named Post or BlogPost.

var List = React.createClass({
  createPost(post){
    return <BlogPost postbody={post.postbody}></BlogPost>
  },
  render() {
    return (

        {this.props.array.map(this.createPost)}

    )
  }
});


Comments are below the code fragments.

const ENC_IN = "utf8";
const ENC_OUT = "base64";

With the choice of encryption and encoding, I'd include the "encoding" part fully (e.g. ENCODING_IN and ENCODING_OUT).

const KEY = Buffer.from("…", ENC_IN);

No, a key should not be a constant, and a key should certainly not be a string, even if it has a specific encoding. A key should be 16, 24 or 32 fully unpredictable bytes (for 128, 192 or 256 bit keys respectively). With UTF-8 you only have some 108 possible printable characters for each byte. Besides that, many libraries will not handle partial or overly long keys well.

If you want to use a password, then use a password based key derivation function (PBKDF) and then createCipheriv / createDecipheriv. Support for that is build in (note that createCipher / createDecipher is deprecated).

Encryption

const encrypt = async function encrypt(data) {

At this point you may want to document the character encoding and the base 64 encoding that is being applied, the mode of operation and that an IV and authentication tag is added. Document or point to the protocol in other words.

const IV = Buffer.from(CRYPTO.randomBytes(BUFFER_SIZE));

Good, random IV. For GCM though I'd use 12 bytes or the mode has to perform additional operations for no security benefit.

const ENCRYPTED = Object.freeze({

Even though you froze the variable, it's still a local variable and therefore you should not be using all uppercase.

data: enc,
iv: IV,
authTag: CIPHER.getAuthTag()

Now this is a bit weird. Unless I'm mistaken enc is now base 64 encoded, but iv and authTag are just plain buffers of binary data.

Decryption

 * @param {string} iv - initialisation vector

Strange, your iv of type Buffer seems to have magically become a string...

Otherwise the decrypt function is nicely symmetrical to the encrypt function, which is good.

Beware of overly stringifying your code. Beware of wrapper classes; don't start using above class for all your code: use user specific encryption routines insetead, and clearly specify your protocol.

When using GCM, you may want to allow additional authenticated data (AAD) to be included in the calculation of the tag.


Sorting an List of tiles based on size and row limitation

Magic numbers
You use 6 - rowSize and Mr.Maintainer has no idea what the 6 is standing for. Extract it to a meaningful named constant.

Naming
MenuItems seems to be plural of MenuItem, so what is a List<MenuItems> ?
One letter parameter names for counter/index fields are ok, but for a List<T> you should use something else neither t nor n.

Brackets {}
You should always use brackets for if statements at least if you use a new line for the action to take.

Refactoring
Let us name the parameter and local field in a better way and like already told, we should refactor the magic number to a const. As of the missing context this needs to be renamed by you later

private void SortTiles(ref List<MenuItems> menuItems)
{
    const int magicNumber6 = 6;
    int rowSize = 0;
    var sortedMenuItems = new List<MenuItems>();
}

Instead of using a while() loop, we should use a for loop, so we can skip the two calls to menuItems.RemoveAt() and just call menuItems.Clear() after the loop.

Next we should refactor the magicNumber6 - rowSize outside of the inner loop, as this needs to be calculated only once for the inner loop. Next a small adjustment of the inner loop startindex to int j = i + 1  and we have this

private void SortTiles(ref List<MenuItems> menuItems)
{
    const int magicNumber6 = 6;
    int rowSize = 0;
    var sortedMenuItems = new List<MenuItems>();

    while (menuItems.Count > 0)
    {
        int minimumSize = magicNumber6 - rowSize;
        MenuItems menuItem = menuItems[0];
        if (minimumSize < menuItem.Size)
        {
            bool suitableTileFound = false;

            for (int j = 1; j < menuItems.Count; j++)
            {
                menuItem = menuItems[j];
                if (minimumSize >= menuItem.Size)
                {
                    suitableTileFound = true;
                    sortedMenuItems.Add(menuItem);
                    rowSize += menuItem.Size;
                    menuItems.RemoveAt(j);
                    break;
                }
            }
            if (!suitableTileFound)
            {
                rowSize = 0;
            }
        }
        else
        {
            sortedMenuItems.Add(menuItem);
            rowSize += menuItem.Size;
            menuItems.RemoveAt(0);
        }

    }
    menuItems = sortedMenuItems;
}

but wait, we can still do better. We can use the List<T>.Find() method to remove the inner loop at all and while we do this we can also get rid of some of the fields we had used and as change the const to the correct name maxRowSize

private void SortTiles(ref List<MenuItems> menuItems)
{
    const int maxRowSize = 6;
    int rowSize = 0;
    var sortedMenuItems = new List<MenuItems>();

    while (menuItems.Count > 0)
    {
        int minimumSize = maxRowSize - rowSize;
        MenuItems menuItem = menuItems[0];
        if (minimumSize < menuItem.Size)
        {
            menuItem = menuItems.Find(item => minimumSize >= item.Size);
            if (menuItem != null)
            {
                sortedMenuItems.Add(menuItem);
                rowSize += menuItem.Size;
                menuItems.Remove(menuItem);
            }
            else
            {
                rowSize = 0;
            }
        }
        else
        {
            sortedMenuItems.Add(menuItem);
            rowSize += menuItem.Size;
            menuItems.RemoveAt(0);
        }
    }
    menuItems = sortedMenuItems;
}

but what if we need to adjust the maxRowSize...? Let us pass it as a parameter then. Because we don't want now to change the code using this method, we add an overloaded method also.

private void SortTiles(ref List<MenuItems> menuItems)
{
    const int maxRowSize = 6;

    SortTiles(ref menuItems, maxRowSize);
}

private void SortTiles(ref List<MenuItems> menuItems,int maxRowSize)
{
    int rowSize = 0;
    var sortedMenuItems = new List<MenuItems>();

    while (menuItems.Count > 0)
    {
        int minimumSize = maxRowSize - rowSize;
        MenuItems menuItem = menuItems[0];
        if (minimumSize < menuItem.Size)
        {
            menuItem = menuItems.Find(item => minimumSize >= item.Size);

            if (menuItem != null)
            {
                sortedMenuItems.Add(menuItem);
                rowSize += menuItem.Size;
                menuItems.Remove(menuItem);
            }
            else
            {
                rowSize = 0;
            }
        }
        else
        {
            sortedMenuItems.Add(menuItem);
            rowSize += menuItem.Size;
            menuItems.RemoveAt(0);
        }

    }
    menuItems = sortedMenuItems;
}


Subscribing and manipulating data from API in Angular

just my personal opinion, so pick what you like and ignore the rest. :-)

In general i think it is a good practice to use your "own" data structure in the frontend.
if the backend changes their format, then you only have to change your mapping functions, and the rest could stay the same. If you use the backend format directly, then your code depends on that format. Means, if the backend changes a name, you would have to change that name all over your application...

Some points in general:

subscribe/unsubscribe
the first thing i would like to mention is, that if you subscribe in a component, then this subscription will be still active, after your component is long dead. Or to make it more explicit, when you "subscribe", then call the method "subscribe" on the observable. And you provide a (fat arrow) function to it. This function is then stored in the observable. Now, each time the observable emits a value, the function is executed. Because this function now "lives" in the observable, it does not get cleaned up when your component is destroyed. This can create memory leaks and/or unwanted behavior.

Therefor if your oberservable does not complete by itself (e.g. an http call, will only do one emit and then "complete") you should always clean up your subscriptions. This could be done by saving them all into a "Subscription" object.

private subscriptions: Subscription = new Subscription();
// ...
this.subscriptions.add(
    this.myObservable.subscribe( (...)=>{...})
)
this.subscriptions.add(
    this.myOtherObservable.subscribe( (...)=>{...})
)

ngOnDestroy(){
  this.subscriptions.unsubscribe();
}

forEach vs. map
forEach is used if you want to execute something for each element of an array. Map is used, if you want to change the format of each element. In your case you want to change the format, so i would prefer "map"

let counter = 1;
this.licence_data = data.map( el => {
   return {
     count: counter++,
     unique_key: el.licenceId,
     key: el.licenceKey,
     date: el.dateCreated
   };
}

Readability by extracting into methods
I personaly like it, when i don´t have to read 5 lines (often much more) of code to understand what happens here. Its much easier if a method is called and the name of the method gives me a good clue what happens in it. As a result, sometimes i don´t even have to look into the method, because the name alone tells me that the problem i am hunting is not there. OR the name gives me some context which allows me to understand the content of the method more easily.
And last but not least, splitting code into multiple methods means to separate the code into chunks which communicate with each other over interfaces. And that makes changes much easier, because, as long as i do not change the interface (the method signature), as long can i do changes without having to fear to break something outside. That makes refactorings much easier.

this._licence.get_licence_by_id(id).subscribe(
  (data: Licence[] => this.licence_data = this.mapToUIFormat(data)
);

this.mapToUIFormat(licences: Licence[]): MyUiFormat { // i would give that format an interface
    let counter = 1;
    return data.map(  licence => {
       return {
         count: counter++,
         unique_key: licence.licenceId,
         key: licence.licenceKey,
         date: licence.dateCreated
       };
    }

}

The advantage of this method is, that its a "pure" method. It only expects some input, and it returns an output that ONLY depends on the input. It also has no side effects, means it does not change anything else. That makes it easier to understand and very easy to test.

If you want you could also extract the mapping of a single licence into the ui format in a extra method. It depends on the complexity of the code, but in some circumstances it really helps to structure the code.


Is there a better way of defining generic entity classes?

There is no way to simplify generic parameters if you want to keep Entity class generic, as  noted by @svick.

The only thing I can suggest as alternative here is to remove generic parameter from Entity. I don't think you need 10 different types for Id field, most likely you'll have int Id or Guid Id, so you can create

public interface IEntity<T>
{
    T Id { get; set; }
}

public abstract class IntEntity: IEntity<int>
{
    public virtual int Id { get; set; }
}

public abstract class GuidEntity: IEntity<Guid>
{
    public virtual Guid Id { get; set; }
}

Not sure if you need IEntity<T> interface, added it so that you don't loose the possibility to reference both types of entities in generic manner.

Yes, you'll have to declare separate IntEntityRepository and GuidEntityRepository, but I don't think it's that hard given that you can extract common code to base class, and it's a one-time job.

As to mappings - I don't use class hierarchy for them (declaring all the fields on the actual entity mapper), but you can do the same trick as with repositories.


This is what I mean with pureRenderComponent:

const SportsMoving = ({editHandler, sportsDescription, ...props }) => {

   const isRunning = sportsDescription.sportsDate && sportsDescription.sportsDate.length > 0 && sportsDescription.sportsDate !== '2199-01-01';
   const sportFire = props.profile.firstName || "";

   return (

            {
              isRunning
                ? `Want some advice ${sportFire}?`
                : `Want a helpful tip ${sportsFire}?`
            }

            {
              isRunning
                ? "Stay focused by setting a target date for completion of your sports."
                : "Add some momentum to your account by setting up automatic recurring deposits."
            }

               {
                 isRunning
                   ? "Set Target Date"
                   : "Set Up Automatic Deposits"
               }

   )
}

now in your parentComponent you can use it like so:

     ...

     <SportsMoving editHandler={this.editHandler} ...props />


Generate a sequence of coin flips until pattern is hit

To avoid return statements:

def l(s: String): Boolean = {
  if (s.endsWith("hhhh")) true
  else if (s.endsWith("thhh")) false
  else l(s + (if (Math.random > .5) "h" else "t"))
}

Although I don't like if - else if sequences, in this case it remains simple and readable, but it still can be simplified like this

def l(s: String): Boolean = {
  if (s.length > 3) s.endsWith("hhhh")
  else l(s + (if (Math.random > .5) "h" else "t"))
}

or even

def l(s: String): Boolean = {
  s.endsWith("hhhh") || l(s + (if (Math.random > .5) "h" else "t"))
}

Randomness

I think that there is a minor issue with random values distribution.

As per Scaladoc for Math.random:

  Returns a Double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

For the current condition, this means that 0.5 < h < 1.0 and 0 <= t <= 0.5.

0.5 is not included in the lower bound for generation of h values, which favors t very slightly.

The condition for equal distribution should be if (Math.random < 0.5) "t" else "h".


I'm not sure about ways to improve performance, but I did notice a couple things.

Guaranteed Returns

If the specified key is already set to the specified value, your function does not return anything. Maybe this is the expected behavior, but I could see it being a problem if you used the function to directly update the URL.

window.location.href = changeURLParameter("thriggle","boring");
// If thriggle already == boring, this redirects you to /undefined

One way to fix that would be to simply remove the If statement if (aURLParams[sVariable] != sNewValue){...}.

Without that check, regardless of whether the parameter is already set to the specified value, it'll be overwritten with the desired value and the URL string will be returned.

Original Sin

window.location.origin does not exist in older versions of Internet Explorer (9 and down). If your user base doesn't overlap with those poor souls still using IE9, feel free to ignore this one, but otherwise you could do something like this:

var sOrigin = window.location.origin ? window.location.origin : window.location.protocol + "//" + window.location.host;
sNewUrl = sOrigin + window.location.pathname;

Edit: even better, as you noted in your followup comment, just update window.location.search directly and you won't have to deal with window.location.origin!


Main notes:

Whenever you have a method broken up into commented sections, consider pulling out each section into its own, clearly named method.  This will make the pieces of your code focused and readable, and eliminate the need for comments.
Use ruby's built in functional methods rather than procedurally looping and bulding things manually.  group_by does most of the work for you in this case.
You can map over hashes, returning an array of [key, value] arrays, and then call to_h at the end to get back a transformed hash.
average_days_on_market_sale_type_segment is an unwieldy name.  avg_days_on_market_by_type seems like a small improvement you could make (generally naming hashes as value_by_key is clearer), but it's still long.  If you have expertise in real estate, you might be able to come up with something clearer that reflects language used by agents.  A quick google search came up with "CDOM", so maybe cdom_by_type would work, but with naming, there's no "correct" answer -- only what will be clear to the people working with the system.

A couple other things:

This isn't tested, since I don't have your data to test with.  So there may be some trivial errors.
The methods sales_description and avg_days_on_market that I introduced aren't really instance methods, since they are pure functions operating on a sale or array of sales.  This hints at further opportunities for refactoring by introducing objects for Sale or Sales, but that may be overkill at this point.

Refactored code:

def average_days_on_market_sale_type_segment
  last_years_sales.group_by {|sale| sales_description(sale)}
                  .map {|desc, sales| [desc, avg_days_on_market(sales)]}.to_h
end

def last_year_sales
  self.real_property_sale_projects
  .where(status: 'reviewed')
  .where('deal_date between ? and ?', Time.at(Time.now - 1.years), Time.now)
  .map(&:real_property_sale)
end

def sales_description(sale)
  sale.sale_description.parameterize.underscore.to_sym
end

def avg_days_on_market(sales)
  total_days = sales.map {|sale| sale.real_property_sale_project.days_on_market}
                    .inject(:+)
  total_days / sales.size
end


Preface

This is great code.  Your solution is more than \$10^{42}\$ times nicer than the given solutions on the linked page that promote crap like #include <bits/stdc++.h>.  You are already much better than them in this regard.

The algorithm

Making use of the STL, your algorithm can be simplified like this:

std::vector<long long> subsetSums(const std::vector<int>& set)
{
    std::vector<long long> subset_sums{0};
    subset_sums.reserve(std::size_t(1) << set.size()); // to prevent iterator invalidation
    for (int num : set)
        std::transform(subset_sums.begin(), subset_sums.end(),
                       std::back_inserter(subset_sums),
                       [=](number_t prev_sum){ return prev_sum + num; });
    return subset_sums;
}

(You need #include <algorithm> for std::transform and #include <iterator> for std::back_inserter)  Here, we first push 0 to the list of sums.  Then, for each element \$x\$, we add \$x\$ to the previous sums and push these new sums.  Therefore:

The initial list of sums is {0}.
For the first element 5, the list becomes {0, 5}, where 5 = 0 + 5.
For the second element 4, the list becomes {0, 5, 4, 9}, where {4, 9} = {0, 5} + 4.
For the third element 3, the list becomes {0, 5, 4, 9, 3, 8, 7, 12}, where {3, 8, 7, 12} = {0, 5, 4, 9} + 3.

Miscellaneous

The common practice is to put a space between #include and the header name, as in #include <iostream>.  And simply delete using namespace std; rather than commenting it out to show you are following good practice :)

You use int for the original numbers, and long long for the sums.  Don't mix different data types.  Write a type alias like

using number_t = long long;

And use it consistently throughout your code.  This makes it clear what these types are used for.

i should really be of an unsigned type.  And isPowerOf2 should also operate on an unsigned type.  The isPowerOf2 function can be made constexpr.  And I prefer a looser layout with more spaces and less parentheses:

constexpr bool isPowerOf2(std::size_t x)
{
  /* First x in the below expression is for the case when x is 0 */
    return x && !(x & (x - 1));
}

1 << set.size() potentially overflows.  std::size_t(1) << set.size() is better.  For me, it may be better to extract a function and check for overflow:

// returns 2^n
template <typename T, std::enable_if_t<std::is_integral_v<T> && is_unsigned_v<T>, int> = 0>
constexpr T power2(T n)
{
    assert(n < std::numeric_limits<T>::digits);
    return T(1) << n;
}

Passing a std::vector by value may cause unnecessary copies.  Pass by const reference instead.

return 0; can be omitted for the main function.

The future

C++20 provides us with bit manipulation utilities.  We can replace isPowerOf2(i) with std::ispow2(i) (after you make i unsigned).  The aforementioned power2 function can also be improved with concepts:

// returns 2^n
template <std::UnsignedIntegral T>
constexpr T power2(T n)
{
    assert(n < std::numeric_limits<T>::digits);
    return T(1) << n;
}

The algorithm can also be simplified with the Ranges library and std::bind_front:

std::vector<number_t> subsetSums(const std::vector<number_t>& set)
{
    std::vector<number_t> subset_sums{0};
    subset_sums.reserve(std::size_t(1) << set.size());
    for (int num : set)
        ranges::push_back(subset_sums,
            subset_sums | ranges::view::transform(std::bind_front(ranges::plus, num)));
    return subset_sums;
}


By using BitConverter.ToInt32 you can simplify the GetPixel() method to

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Color GetPixel(int x, int y)
{
    return Color.FromArgb(BitConverter.ToInt32(bytes, y * stride + x * 4));
}

Also there is no need to place () arround the multiplications because they will be done first.

Because GetPixel and SetPixel are public you should add some validation to them. This can be done by adding a private method GetPosition() like

private int GetPosition(int x, int y)
{
    if (x > stride) { throw new ArgumentOutOfRangeException("x"); }

    int position = y * stride + x * 4;

    if (position >= bytes.Length) { throw new ArgumentOutOfRangeException("y"); }
    return position;
}

now the changed GetPixel() method looks like

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Color GetPixel(int x, int y)
{
    return Color.FromArgb(BitConverter.ToInt32(bytes, GetPosition(x, y)));
}

Basically you don't need the Color to determine if a pixel is black or white. You can just check if the argb value of that pixel matches the values for Color.Black or Color.White like

private const int black = -16777216;
private const int white = -1;

public bool IsBlackAndWhite(int x, int y)
{
    int argb = BitConverter.ToInt32(GetPosition(x, y));
    return argb == white || argb == black;
}

You should let your variables some space to breathe.

for(int j=0; j<Height; j++)

should be

for(int j = 0; j < Height; j++)

Your IDE will usually have a keyboard shortcut for formatting the code.

Declaring multiple variables in one line makes your code less readable.


What’s the largest MD5 hash you can find?

max() takes a key

The main thing I wanted to point out is that max() takes a key, which is a one-argument ordering function.

This lets you rewrite your string_with_largest_hash as:

def string_with_largest_hash(plain_strings, current_leader):
    strings = chain(plain_strings, (current_leader,))
    return max(strings, key=numeric_md5)

Which is quite a bit shorter, and in my opinion easier to understand.


Top hit on Google looks very similar; in any case no need to reinvent this.

But really, if this is the initial password, the users are going to get it how? Are the being forced to reset it immediately? All that is more a question for https://security.stackexchange.com/ than here.

But sure, looks okay, AFAIK SecureRandom is thread-safe (is that important?) and it's going to produce "random enough" output, the loop is okay too.

Though why specifically 16 characters and not e.g. 32? Do they have to enter them from a sheet of paper? Then there would be a couple of issues with it, like possibly mistaking i, I, l, L and 1, or 0, o and O, ... and so on.


Converting a number to binary and back as a test in Java

Cryptic names

int n = 10;
int m = 20;

Please give longer and more descriptive names to n and m

Overworked main

I would define outside of main

public static double FloatToBin(float n) {

}

public static double BinToFloat(bin n) {

}

So that main can contain the IO only.


This body.split('{'}) is doing you a disservice, as it destroys the structure of the response. Split it by lines instead:

body = Net::HTTP.get(...)
data = body.lines.map { |line| JSON.parse(line) }


Utility functions for processing tweets or texts

A few obligatory PEP-8 rules:

Imports should be grouped in the following order:

standard library imports
related third party imports
local application/library specific imports

Use blank lines in functions, sparingly, to indicate logical sections.
Two blank lines between the import statements and other code.
Two blank lines between each function.
Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.

If this is written for python-3.x, I'd also suggest going for Type Hinting.

In the split_texts definition, I'd suggest having naive=False as the default (or naive=True) depending on the more obvious choice of the two.

In the function total_rts (could be renamed to total_retweets), you can avoid one entire level of nesting by returning early in the first if not string_inclusion clause.

The function clean_text makes several transition tables, which could be extracted out of the function and made a constant. More importantly, what I understood from the definition, I think you're (in order):

cleaning the text of all printable characters
cleaning the text of all characters leftover from step 1
cleaning all punctuation from result of step 2
replacing all kinds of whitespace characters with a single ' ' in the result of step 3.

You can define global transition tables as follows:

WHITESPACE = ' ' * len(string.whitespace)
CLEAN_TRANSLATION = str.maketrans(string.whitespace, WHITESPACE, string.punctuation)

Alternatively, you can take the CLEAN_TRANSLATION inside the clean_text function and use the undefined non-printable characters in concatenation to string.punctuation. So, the function becomes:

def clean_text(text):
    undefined_chars = text.translate(
        str.maketrans({c: None for c in string.printable}))
    cleanup_translation = str.maketrans(
        string.whitespace, WHITESPACE, string.punctuation + undefined_chars)
    return text.translate(cleanup_translation)

And, most importantly, the description for each function that you've provided in the question, could be converted to a docstring for each of them.


Disclaimer : this is not a proper code review.

A different algorithm

There is a O(n) in time and O(1) in space algorithm (and one can easily see that a smaller complexity cannot be achieved).

You just need to XOR all elements so that the one in pairs cancel each other and you are left with the lonely integer.


Read integers from text file and write to CSV file

Brave attempt :-) This can be so much better ;-)

Running scripts

The script has the shebang #!/bin/bash, but you invoke it as sh script.sh.
The purpose of a shebang is to make scripts runnable as ./script.sh.
When invoked this way, the shell looks at the shebang, and runs the script with the specified executable.
sh is often symlinked to Bash, but not always.

In short, if a script doesn't require Bash, then use the shebang line #!/bin/sh and run it as ./script.sh or sh ./script.sh.
If it requires Bash, then use the shebang line #!/usr/bin/env bash and run it with ./script.sh or bash ./script.sh.

Filtering lines

Bash is not particularly well-suited to filter lines by patterns.
grep is a great tool for that.
So instead of reading line by line with Bash to filter,
look for ways to use grep.
In this example, replace the loop with:

grep '[0-9]$' "$file" | while IFS= read line; do
    ...
done

Empty conditional branches

I think your intention here was to do nothing when the condition is true:

if [ "$lastchar" == : ]
    then
        echo -ne
elif ...

If you ever need to do nothing, you can use true or : like this:

if ...; then
    :
elif ...

But this is not a good example to use this trick,
because a better solution exists.
A better solution would have been to drop the if, and change the elif to if.
An even better solution would have been to call continue if the line doesn't match the required pattern, so the loop body would be flatter:

if ! [ "$lastchar" -ge 0 -a "$lastchar" -le 9 ]; then
    continue
fi

breakdown=...

With my tip with grep in the previous point, you don't need a condition at all.

Extracting two numbers

This is very inefficient:

breakdown=$(echo "$line" | cut -d':' -f2,6)
master=$(echo "$breakdown" | cut -d'a' -f1)
clone=$(echo "$breakdown" | cut -d':' -f2)
final=$(echo -e "$master,$clone" | tr -d ' ' >> tempsplit.txt)

The problem is that for each line this runs many processes: echo, cut, tr, and multiple $(...) sub-shells.

I see a simpler way to achieve what you want. Looking at these sample lines:

tape with barcode: 000053 and is: offline at listed location: MCR Shelves and is: Full and is copy of tape with barcode: 000047
tape with barcode: 000044 and is: offline at listed location: MCR Shelves and is: Full and is copy of tape with barcode: 000042

We could extract the two numbers and put a comma in between like this:

Replace all non-digits at the beginning with empty string (= remove)
Replace all non-digits with a comma

Try this simple pipeline:

grep '[0-9]$' file | head | sed -e 's/^[^0-9]*//' -e 's/[^0-9][^0-9]*/,/'

This works for the head of the file, but not the entire file. On closer look, there are lines that have a third number between the target numbers, which breaks the above pattern:

  tape with barcode: 000484 and is: online at listed location: i40 QUANTUM and is: Appendable and is copy of tape with barcode: 000483

After replacement this line becomes:

  000484 and is: online at listed location: i40 QUANTUM and is: Appendable and is copy of tape with barcode: 000483

Observe that there is a space after the first number and before the last. So to handle such case, we could change the logic of the second step to: "replace everything between two spaces with a comma".

Let's give that a try, on lines containing "i40":

grep 'i40.*[0-9]$' file | head | sed -e 's/^[^0-9]*//' -e 's/ .* /,/'

It seems the script could be replaced with:

grep '[0-9]$' "$file" | \
    sed -e 's/^[^0-9]*//' -e 's/ .* /,/' | \
    awk 'NR % 2 == 0' | sort -n > tapelist_split.csv

No temporary files needed.

If you have the GNU version of sed (typically in Linux), then you can use it delete every 2nd line instead of awk, slightly simpler:

grep '[0-9]$' "$file" | \
    sed -e 's/^[^0-9]*//' -e 's/ .* /,/' -e '1~2d' | \
    sort -n > tapelist_split.csv

Quoting

When you use variables as command parameters,
it's important to double-quote them to protect from word splitting and globbing. So a loop should read from $file like this:

while ...; do ...; done < "$file"

Understanding command parameters

Why did you use the -rf flags here?

rm -rf tempsplit.txt

There's no good reason to use those flags in the above script.

The -r flag is to delete directories recursively. But the parameter above is a single file. The -r flag serves no purpose.
The -f flag is to force deleting a file that might be protected, or to suppress error in case the file doesn't exist. Neither is the case here. The flag serves no purpose.

Flags in a script that serve no purpose or noise, confusing.
Understand all the flags you are using,
and make sure they have a reason to be there.

The field separator

The variable name is incorrect here:

while IFs= read line

Should have been:

while IFS= read line

Variable names in Bash are case sensitive.


Finding all upper/lower case combinations of a word

public static void comb(String word) {
    int combinations = 1 << word.length();
    char[][] chars = { word.toLowerCase().toCharArray(),
                       word.toUpperCase().toCharArray() };
    char[] result = new char[word.length()];

    for (int i = 0; i < combinations; i++) {
        for (int j = 0; j < word.length(); j++) {
            result[j] = chars[(i >> j) & 1][j];
        }
        System.out.println(new String(result));
    }
}

[Edit]

I did some profiling, and my version seems slightly better, and the following version is even a little bit faster:

public static void comb(String word) {
    word = word.toLowerCase();
    int combinations = 1 << word.length();
    for (int i = 0; i < combinations; i++) {
        char[] result = word.toCharArray();
        for (int j = 0; j < word.length(); j++) {
            if (((i >> j) & 1) == 1 ) {
               result[j] = Character.toUpperCase(word.charAt(j));
            }
        }
        System.out.println(new String(result));
    }
}

However, all versions so far are in the same ballpark and won't change something substantial, because System.out.println dominates the performance.

[Edit 2]

The algorithm really doesn't matter much, the System.out.println impact is too heavy. Collection everything in a StringBuilder and calling System.out.println doesn't help either. However, quite surprisingly my profiler tells me that this simple recursive version performs best:

public static void comb4(String word) {
    comb4(word,new char[word.length()],0);
}

private static void comb4(String word, char[] accu, int index) {
    if(index == word.length()) {
        System.out.println(accu);
    } else {
        char ch = word.charAt(index);
        accu[index] = Character.toLowerCase(ch);
        comb4(word, accu , index+1);
        accu[index] = Character.toUpperCase(ch);
        comb4(word, accu, index+1);
    }
}


Bash script which downloads the latest linux stable kernel

Good stuff:

Yay for putting your code on github.  I see a lot of folks afraid to wait until everything is perfect to do that.  But having the backup and history of git is too handy to wait like that.  So I love seeing somebody doing that from day 1 of a project.
Yay for use the double square bracket form of if and checking for common mistakes.
Yay for using env.  As you can see from my github I'm not so great at this one, but it is a good idea.

Suggestions:

Move common code into a library.  Your EUID check is the most obvious culprit.  To create a shell library you should create a file of functions and then source it into each of your commands.  So to translate your check into a function is easy:

function validate_root {
    if [[ $EUID > 0 ]] ; then
            echo "You need root privileges for this script."
            exit
    fi
}

Then use the library later like so:

source lib.sh

validate_root # be root or exit

Move common data into the library.  The most common item is /etc/latest-kernel... what if you want to move it somewhere else?  If it is in a variable in one place it will be a lot easier to do.  There's no reason not to throw those into the common shell library file too.
It looks like you made a cut and paste error on purgelatestkernel but since I can check out the github version I can see what you meant there.  Generally you're not supposed to edit code during code review put I think you'd be ok to fix that part up since you're not altering the code you meant to review.
Avoid duplicate code by looping in the install:

for file in lk create_etc_lk purgelatestkernel
do
        echo copying $file to /usr/bin
        cp $file /usr/bin
done

This also makes it easy to add other things like a validation of permissions or check for return values without insane amounts of error-prone cut and paste.
Instead of having the option for a prompt be something that requires a source code alteration why not make it conditional based on a variable that possibly could be altered with a command line option?


#include<stdio.h>
#include<stdlib.h>
struct node {
    int data;
    struct node *next;
};
struct node *list=NULL;
struct node *root=NULL;
static int count=0;

Don't store data in global variables. It makes your code unreusable and harder to follow.

struct node *create_node(int);//function to create node
void travel_list(void);
void create_list(int);
void reverse_list(void);
int main()
{
    int i, j, choice;

Using variables like i and j only make sense if used in the sense of indexes. Otherwise, the code just gets harder to read. Choice is also not very informative.

    printf("Enter a number this will be root of tree\n");
    scanf("%d", &i);
    create_list(i);
    printf("Enter  1 to enter more numbers \n 0 to quit\n");
    scanf("%d", &choice);
    while (choice!=0){
     printf("Enter a no for link list\n");
        scanf("%d",&i);

Use consistent indentation. Otherwise things will go downhill fast.

//  printf("going to create list in while\n");

Don't leave dead code in your code, that's what source control is for.

    create_list(i);
        travel_list();
    printf("Enter  1 to enter more numbers \n 0 to quit\n");
    scanf("%d", &choice);

Deja vu. Why isn't the previous instance doing the same thing done in the loop?

    }
    printf("reversing list\n");
     reverse_list();
     travel_list();
 }

// end of function main
void create_list (int data)

This function appends to the end of a list, it doesn't create it. Use function names that indicate what is really happening.

{
 struct node *t1,*t2;

t1 and t2 are very uninformative variable names.

 //printf("in fucntion create_list\n");
 t1=create_node(data);
 t2=list;
 if( count!=0)

This is the only place that count is used. Check whether list is null instead.

 {
   while(t2->next!=NULL)
   {
   t2=t2->next;
   }
 t2->next=t1;
 count++;
 }
 else
  {
   root=t1;

You don't ever seem to do anything with root.

   list=t1;
   count++;
  }
}
struct node *create_node(int data)
{
    struct node *temp;

The new node isn't really temporary

    temp = (struct node *)malloc(sizeof(struct node));
        temp->data=data;
    temp->next=NULL;
  //      printf("create node temp->data=%d\n",temp->data);
//  printf("the adress of node created %p\n",temp);
    return temp;
}
void travel_list(void )
{
 struct node *t1;
 t1=list;
 printf("in travel list\n");
 while(t1!=NULL)
 {
 printf("%d-->",t1->data);
 t1=t1->next;
 }
 printf("\n");
}
void reverse_list(void)
{
    struct node *t1,*t2,*t3;

This piece of code would be way easier to follow if you used real names

       t1=list;
    t2=list->next;
    t3=list->next->next;

This is going to fail for lists shorter then three elements

   int reverse=0;
   if(reverse==0)

This will always be true since you just assigned reverse = 0.

   {
    t1->next=NULL;
    t2->next=t1;
    t1=t2;
    t2=t3;
    t3=t3->next;
    reverse++;

You never use reverse again

    }

    while(t3!=NULL)
     {

     t2->next=t1;
    t1=t2;
    t2=t3;
    list=t1;
    travel_list();
    t3=t3->next;
    }
    t2->next=t1;
    list=t2;
}

My version of reverse_list (untested)

struct node * reverse_list(struct node * list)
{
    struct node *previous, *current;
    previous = NULL;
    current = list;
    while(current)
    {
        struct node * next = current->next;
        current->next = previous;
        previous = current;
        current = next;
    }
    return previous;
}

}


Just quickly, here's some feedback:

I think your set up code is fine (where you're creating the JFrames etc), it's very boiler platey, but that's java.
But you shouldn't put that logic in the constructor. Put it in an init() method, called after construction.
Do use scope declarations, ie. make that Hangman() constructorpublic Hangman(). Same with void testLetter is this method meant to be public or private? Make it explicit so that others (and yourself, in six months!) know how the code is meant to be used.
Consider separating your Swing/GUI logic, and your game logic to different classes. ie, something like HangmanApp (your main class) contains a HangmanGui and a HangmanLogic.
You have magic numbers all through your code. For example this line is particularly bad: textContents.setText("Incorrect Guess! You have " + (6 - incorrectGuesses)  + " left.");
What if you want to change the number of guesses? Ideally these configurations would be set in a properties file, but for a small application setting them at the top of the class is fine.
Your if else branching in testLetter is scary. As it currently is, I can't immediately see what each branch is for. Comments would help on each branch, but I would move 'test if the letter fits' logic, and 'what should I do if letter is correct/incorrect' logic, into their own private methods.

eg. something like:

void testLetter(String a) {

     if (evaluateGuess(a)){   //returns true if guess is correct
         handleCorrectGuess(a);
     }
     else (
         handleIncorrectGuess(a);
     }

}

You don't need to use a == comparison on booleans. Use a descriptive variable name and ! operator instead. ie. if (!gameLost){... or if(gameStillInProgress){...


So this is not the typical code review, as the code in question is pretty basic in terms of what it does. It is a given algorithm, and you need to do the given operations. The one possible varying factor is the random.random() lines. Can this affects times?

Let us test the random generation of some numbers using various random generators:

import random
import numpy
import timeit

t = 100001
def org_random_random(runs=t):
  for a in range(t):
    int(random.random() * 3) + 1

def org_random_randint(runs=t):
  for a in range(t):
    random.randint(1, 3)

def numpy_random_randint(runs=t):
  for a in range(t):
    numpy.random.randint(1, 3)

def numpy_random_randint_x(runs=t):
  numpy.random.randint(1, 3, runs)

orr = timeit.timeit(org_random_random, number=5)
ori = timeit.timeit(org_random_randint, number=5)
nrr = timeit.timeit(numpy_random_randint, number=5)
nrx = timeit.timeit(numpy_random_randint_x, number=5)

Sorry for terrible naming, it's just something I threw together, and when I ran it using https://repl.it/languages/Python3, it gave me the following output:

org_random_random     : 0.18020408600023075
org_random_randint    : 0.8966416030016262
numpy_random_randint  : 0.9019350050002686
numpy_random_randint_x: 0.004406830999869271

All three variants has been 'normalised' to produce a number between 1 and 3, and the last variant generates all of the numbers in one go. And the last one is way faster than the other.

In other words, I would suggest to pre-build the random numbers, and make a custom generator feeding you from this pre-built array of random numbers. This would potentially drastically reduce the running time of your algorithm.

Using a prebuilt random number array

Here is a simple rebuild using a pre-built array of random numbers from numpy:

runs = 10000001
random_numbers = numpy.random.randint(1, 3, runs + 6)

j = 0
k = 0

for i in range(1, runs):
    p = random_numbers[i]
    g = random_numbers[i+1]

    if p == g:
        r = random_numbers[i+2] % 2 + 1
        if p == 1:
            r += 1
        if p == 2 and r == 2:
            r = 3
    else:
        r = p ^ g
    s = g
    f = g ^ r
    if s == p:
        j = j + 1
    if f == p:
        k = k + 1

print(f"After a total of {t - 1} trials,")
print(f"The 'sticker' won {j} times ({int(j/t*100)}%)")
print(f"The 'swapper' won {k} times ({int(k/t*100)}%)")

When timed (without the print statements), this ran about 33% faster than the original. It does kind of reuse the random numbers slightly, but it shouldn't affect the overall randomness too much, I think.

Other possible factors

Just for the fun of it, I also tried exchanging the range() with a while a < runs loop, but that only had a minor effect for the larger number of runs. NB! If you was using Python 2.x, there would most likely be a massive effect out of changing range() into xrange().

The if s == p could be eliminated, and the j += 1 could be moved into the p == g block. This also, has little to no effect in my tests.

Lastly, using various python implementation will also effect timings. Using PyPy, IPython, C-Python(?), or other variations could change the time usage. I've used https://repl.it/languages/Python3, which reports the following on sys.version():

3.6.1 (default, Apr 26 2017, 20:23:36)
[GCC 4.9.2]

I also tried with an actual generator with both the large prebuilt list of random numbers, and a loopable generator with 1013 random numbers. Those had similar run times to the original code.

So, with the exception of making a python wrapper and implement the algorithm in another language or re-build the algorithm, I would be surprised to see a faster implementation. But I'll happily be proven wrong!


What I've seen the most when it comes to builder patterns is that the object (in your case Animal) will get constructed in the build method of the builder. It is preferred to create instances of objects with all the data that the object should have, eg not creating invalid states of an object. This prevents you from having illegal state in your program which might produce bugs. By constructing your Animal as soon as you create a builder instance you have to make your Animal mutable which is not always what you want. For example, in some cases a class might have only final fields which can only be assigned via constructor.

In your case, constructing the Animal in the build method it would look something like this:

public class Animal {

    private String animalName;
    private int animalAge;

    public static class AnimalBuilder {
        private String animalName;
        private int animalAge;

        public AnimalBuilder() {
        }

        public Builder withName(String animalName) {
            this.animalName = animalName;
            return this;
        }

        public Builder withAge(int animalAge) {
            this.animalAge = animalAge;
            return this;
        }

        public Animal build(){
            Animal animal = new Animal();
            animal.animalName = this.animalName;
            animal.animalAge = this.animalAge;
            return animal;
        }
    }

    public Animal(){ }

    public String getAnimalName() {
        return animalName;
    }

    public int getAnimalAge() {
        return animalAge;
    }
}

You can then use it

Animal animal = new AnimalBuilder()
    .withName("Terry")
    .withAge(5)
    .build();

You can also add a static method builder() to the Animal class which returns a new builder:

public class Animal {
    ...

    public static AnimalBuilder builder() {
        return new AnimalBuilder();
    }
}

Animal animal = Animal.builder()
    .withName("Terry")
    .withAge(5)
    .build();

Does this mean a lot of duplication? Unfortunately, yes, builder patterns need a lot of duplicate code. You can also look at Lombok's Builder annotation which will generate all the builder boilerplate code for you. In that case it will just be

@Builder
public class Animal {

    private String animalName;
    private int animalAge;

    public Animal(){ }

    public String getAnimalName() {
        return animalName;
    }

    public int getAnimalAge() {
        return animalAge;
    }
}
```


Determining whether a number is a palindrome

Not much there to be ugly to be honest.  I guess all I might consider would be the reverse of MrSmith42 and adding functionality to avoid the duplication of ToString().

private static bool IsPalindrome(int value)
{
    var valueStr = value.ToString();
    return valueStr == string.Concat(valueStr.Reverse());
}


Small script to verify hash of a downloaded file

Notes:

I'd use getopts for arg parsing -- lots of examples on stackoverflow about how to use it.
always quote your variables
you should validate the algorithm:

sum_exe="${algo}sum"
if ! type -P "$sum_exe" >/dev/null; then
    error_exit "'$algo' is an unknown checksum algorithm"
fi

have the checksum program read from stdin, then you don't have to do your incorrect unsafe word parsing since the program will not print a filename

hash_calc=$( "$sum_exe" < "$downloaded_file" )

As the above doesn't work, let's use read from a process substitution

read -r hash_calc _ < <("$sum_exe" < "$downloaded_file")


VBA save multiple records code, 2 for loops or change to 1 for loop with if statement inside

On Error GoTo 0 is used in conjunction with On Error Resume Next to reset any errors that may occur between the two statements.

For this reason,  On Error GoTo 0 in the ↓ line below ↓ should be changed to On Error Resume Next.

If Not BasicInclude.DebugMode Then On Error GoTo Error_Handler Else On Error GoTo 0

I would rewrite the Validation statement removing the else clause.  This will make the code easier to read.

If out <> "" Then
    MsgBox "Please fill out the following fields: " & vbCrLf & out, vbCritical, "Error"
    SaveSerials = 1
    Goto Error_Exit:
End If

Setting objects to nothing is rarely necessary with today's garbage collectors.

set rs = Nothing
set rs2 = Nothing
set rs3 = Nothing

Recordset should be closed.

rs.Close
rs2.Close
rs3.Close

Grouping your recordset field will improve the readability of the code, make it easier to spot missing fields, and just makes sense.

For i = 1 To Me.lstData.ListCount - 1
    'Add record to dbo_Part_Serial_Number
    rs.AddNew
    rs.Fields("Part_No").Value = Me.txtPart_No.Value
    rs.Fields("Label_Date").Value = Me.txtDate_Created.Value
    rs.Fields("Serial_No").Value = Me.lstData.Column(i)
    rs.Fields("Operator").Value = Me.txtOperator.Value
    rs.Fields("Work_Order").Value = Me.cboWork_Order.Value
    rs.Fields("Date_Code").Value = Me.txtDate_Code.Value
    rs.Fields("Notes").Value = Me.txtNotes.Value
    rs.Fields("Flex_Circuit_Date_Code").Value = Me.txtFC_Date_Code.Value
    rs.Fields("Flex_Circuit_Int_Date_Code").Value = Me.txtFCI_Date_Code.Value
    rs.Fields("Substrate_Date_Code").Value = Me.txtSubstrate_Date_Code.Value
    rs.Fields("SMF_Date_Code").Value = Me.txtSMF_Date_Code.Value
    rs.Fields("r").Value Me.chkR.Value
    rs.Update

    'Add record to dbo_Label_Trace_Temp
    rs2.AddNew
    rs2.Fields("PartNumber").Value = Me.txtPart_No.Value
    rs2.Fields("PartSerialNumber").Value = Me.lstData.Column(i)
    rs2.Fields("Operator").Value = "%1" & Me.txtOperator.Value & "%"
    rs2.Fields("WorkOrder").Value = Me.cboWork_Order.Value
    rs2.Fields("Date_Code").Value = Me.txtDate_Code.Value
    rs2.Update
Next

You may consider extracting code  related to the three recordset into their own subroutines but it is not necessary.

It is hard to discern the meaning of the return value of SaveSerials (e.g. -1, 0, 1) without studying the code. Consider using an Enum.


This took a while to parse, it's probably me, I found few flaws with the code, except for a distinct lack of comments.

I would have made url in preload an optional, 2nd parameter, I would probably want to call preload a few times with different URL's ( for 'data' )
I think using a switch for media and data is overkill, I would have done a simple if statement.
Since you have a number of times function(data) {deferred.reject(data);});, I would have assigned this to an actual function.
{cache: true}, for data seem unfortunately hardcoded, consider this as well as optional parameter ?
You define current on top, but totalImg in preloadImage, pick one spot and put both vars there
Sometimes you postfix with Img, sometimes with Images. I would stick everywhere to Images, it is so much more readable
Except for the angular.module('myApp').service( line, you have succinct lines of code, nice to read
No need to store a shortcut to data.data in var data = data.data;preloadImage(data, localStorageService.get('cachetoken'));
I would not have gone down the road of managing an array of promises, I probably would have done a simple if (current===totalImg) deferred.resolve('RESOLVED');
'RESOLVED' seems kind of pointless to provide as a parameter to resolve, we know it's resolved ;) Perhaps totalImg + ' images loaded' ?


Generate out_filename from input_filename and suffix

You can dramatically simplify the function by using the os.path.splitext() instead:

import os

def generate_out_file(in_file, suffix='out'):
    """Appends '.out' to an input filename."""
    filepath, file_extension = os.path.splitext(in_file)
    return filepath + "." + suffix + file_extension

Demo:

$ ipython3 -i test.py
In [1]: generate_out_file("./file.txt")  # file in a current directory
Out[1]: './file.out.txt'

In [2]: generate_out_file("/usr/lib/file.txt")  # path to a file
Out[2]: '/usr/lib/file.out.txt'

In [3]: generate_out_file("file.txt")  # just a file name
Out[3]: 'file.out.txt'

In [4]: generate_out_file("file")  # no extension
Out[4]: 'file.out'

In [5]: generate_out_file("/usr/lib/file")  # no extension with a path
Out[5]: '/usr/lib/file.out'


I'm assuming from looking the code you're using Zend Framework. I've solved similar issues in Zend and Symfony using php partials.

You could create a partial _list_item.phtml

        <input name="dates[]" class="datebox" style="width: 120px;" type="text" value="<?php echo $date ?>" />

        <input name="contents[]" type="text" value="<?php echo $message ?>" style="width: 100%;" />

Then in your view:

<?php foreach ($this->events as $event): ?>
    <?php echo $this->partial('list_item.phtml', array(
        'date' => $event->GetDate()->format('Y-m-d'),
        'message' => $event->GetMessage(),
    )); ?>
<?php endforeach; ?>

Then for your javascript:

function AddNewEvent()
{
    var today, html, temp;
    // call str_replace because javascript doesn't like new lines in strings
    html = '<?php echo str_replace(PHP_EOL, "\n", $this->partial('list_item.phtml', array(
        'date' => $event->GetDate()->format('Y-m-d'),
        'message' => '',
    ))); ?>';
    $(this).after(html);
    temp = $(this).next();
    CreateDateboxes($('.datebox', temp));
    $('.ui-icon-trash', temp).click(RemoveParent);
}

Viola! No template duplication because the affected code is in a partial. No excess javscript templating libraries, although if this kind of thing is prevalent in your application I'd suggest some refactoring and implementing such a templating library.

This approach will have the least impact on your work flow, little to no learning curve, and a short investment in development time for big decrease duplication (bosses love hearing that kind of thing).


Overall it looks pretty good. There are a couple of improvements.

Stylistically, JavaScript doesn't place the { character on a new line. You'll see it start on the same line separated by one space:

function Events() {
    // ...
}

if (condition) {
    // ...
} else if (condition) {
    // ...
} else {
    // ...
}

Since you are not using any function closure variables, there is no need to recreate the on and trigger methods each time the Events constructor function is called. Use the prototype property instead:

function Events() {
    this.stack = [];
}

Events.prototype = {
    stack: null,

    constructor: Event,

    on: function (event, callback) {
        // ...
    },

    off: function (event, callback) {
        // ...
    },

    trigger: function (event, data) {
        // ...
    }
};

You could remove the need for the new operator with a little constructor function trickery:

function Events() {
    if (!(this instanceof Events)) {
        return new Events();
    }

    this.stack = [];
}

This would allow you to generate a new Events object by calling Events():

Events().on("foo", function(event) {
    // ...
});

The word Events makes this seem like a collection of existing events. Really you've created an event dispatcher, and EventDispatcher feels like a better name.


When you say

  I want to handle input like the following [...]

I take you to mean that you want to tokenize a language similar to the one recognized by the standard POSIX shell (since you tagged [posix] and presented an example), or maybe even that exact language.

You posited in comments that perhaps you needed a parser generator such as yacc or bison for this job.  Although these tools can indeed do such a job, code for such a subsystem -- a "lexical analyzer" or "scanner" -- is more often generated via a different kind of code generator; lex and its GNU variant flex are the canonical tools for this purpose.  These two particular tools allow you to describe your tokens (and separators) via regular expressions, and from such descriptions they generate C code for a table-based DFA that processes the language character by character and splits it into tokens.  This is certainly one plausible way you could proceed.

On the other hand, depending on the language you want to recognize, it's not necessarily unreasonable to write your own lexical analyzer from scratch, or in favorable cases to use an available function such as strtok() to do the job.  This affords the possibility of a better-tuned implementation than can be produced via a general-purpose tool (or not), it does not incorporate an additional language into the project, and the source might even be smaller.

You ask,

  Is there a better way?

and the answer is certainly "yes".  Other than broad generalities such as I have given so far, however, code review is not really a good platform for what essentially boils down to designing a complete replacement for your present code.  From here out, therefore, I focus on the code you actually presented:

The name of your function is poorly chosen, as it does not describe its behavior very well.  For what it seems meant to do, "tokenize", "find_tokens", "scan", "analyze", or a similar name would be more fitting.
The name of the token parameter seems poorly chosen.  Tokens (or in shell terminology, "words") are the function's output, not a good description of its likely input.  Maybe this parameter should be a "line", or such.
On the other hand, such code would be more flexible if it could read directly from the input, instead of being presented a pre-read string.
That your function accepts parameters awk and i suggests that it is intended to be used multiple times, incrementally, to build up one params array, but if so then it has no mechanism to return its present value of awk to the caller, which it seems would be necessary.
You have no protection against overrunning the bounds of your params array.  It would probably be better to pass a double pointer, and let the function (re)allocate space as needed.
When you identify tokens / words, you should consider making copies instead of using pointers into the original string (the latter being what strtok() provides) as there are all kinds of unpleasant surprises that could result from using the space in the original string as storage for the tokenized words of the command.
And of course, I presume you know that strtok() consumes / modifies / destroys the input string.
Calling out awk as a special case is untenable for parsing shell input, as you cannot enumerate all the possible commands, nor know what form of argument or arguments to expect.  Even awk itself does not necessarily take a single-quoted (or even double-quoted) argument.  (Consider the perfectly viable command awk {print}.)
The standard shell does not organize input into bare words and quoted strings.  Single- and double-quoted subsequences can be concatenated with other quoted or unquoted sequences to form a single token.  For example, these mean the same thing to the shell: 'one shell word', one' 'shell" "word, and o"ne"' shel'l" "wo'r'"d"''.
If your shell language is simpler, so that you don't need to worry about internal quotes, then you probably still should not use the preceding token to predict quoting status.  Instead, look at the first character of each substring itself to see whether it is a single or double quote.
The shell recognizes escape sequences inside double-quoted strings; this requires a smarter scanner than strtok() to sort out.
Although the standard shell does not split words at quotes, there are several characters other than whitespace where it does split them (when they appear unquoted): |  & ; ( ) < >.  So for example, the shell will interpret the input ls -al|awk '{print $1}' exactly the same as it does your example command, even though there is no whitespace around the |.


Animated scrolling to a place in the same webpage

You should declare these styles into classes, and use jQuery to toggle the classes. That way, you have good "separation of concerns". You end up with a smaller base code.

Additionally, one should not use the all for transition. It's bad for performance. Ideally, one should just indicate what property to transition.

There's also this neat trick that forces CSS to be hardware-accelerated. However, you should use it carefully. I read that there's drawbacks to excessive use, and instead of performance gains, you lose performance.

With what I know, here's how you can optimize that animation code:

CSS:

#BlankSpaceMenu.transition,
.ConHome.transition,
.ConTech.transition,
.TopHeader.transition{
  transition : all 0.4 ease
}

#BlankSpaceMenu.transform,
.ConHome.transform,
.ConTech.transform{
  transform : translateY(-50em)
}

.TopHeader.transform{
  border-bottom-color : rgba(0,0,255,1)
}

JS:

$(function () {

  // Cache the set, assuming they don't change.
  var animationSet = $('.ConHome, #BlankSpaceMenu, .ConTech, .TopHeader');

  $('#Tecnologia').click(function () {
    animationSet.addClass('transition transform');
  });

});


General feedback on Conway's Game of Life implementation

Separate different concerns in your code.  The function simulate does two things that should be separated, namely changing the state of the world and calling the function that saves it as an image.  As it is, it's impossible to re-use only the state-changing logic.  Instead, move the game logic to a function simulate_step (or whatever you want to call it).

Stick to the PEP8 naming conventions: functions and variables should be written lowercase_with_underscores. Otherwise, you follow the guide very nicely.


In practice, your code will be fine. In theory, it is not guaranteed to terminate, but the probability of that happening is literally negligible.

However, what you are doing is picking a random integer between 1 and 3 (both inclusive), with the number not repeating. With only three possibilities, we could draw up a state machine:

states = {
  1: [2, 3],
  2: [1, 3],
  3: [1, 2] };
if (lastRandom === undefined) {
    random = Math.floor(Math.random() * 3) + 1;
}
else {
    random = states[lastRandom][Math.floor(Math.random() * 2)];
}
lastRandom = random;

Unfortunately, that involves generating all the states first, which is impractical for larger ranges. There, we could use this more clever approach:

var min = 1;
var max = 3;
if (lastRandom === undefined) {
    random = Math.floor(Math.random() * (max - min + 1)) + min;
}
else {
    random = Math.floor(Math.random() * (max - min    )) + min;
    if (random >= lastRandom) random += 1;
}
lastRandom = random;

So if we are choosing the first number, everything works as usual. But for any subsequent number, we choose an integer from a set one smaller (to reflect that one number, the lastRandom, can't be chosen). If the random number obtained like this is less than the lastRandom, it can be used as is. Otherwise it has to be incremented by one, so that the lastRandom has been skipped.

Test to compare code:


Find the highest prime factor for given number

Minor Changes

In factorsOf:

1 is not a proper factor. Start the loop with var i = 2.
n isn't either. Stop the loop with i < n.

Prime Factors

Here is a simple optimization for testing the 'primeness' of a factor. The key is that you have already found a array of factors. Instead of testing every i such that i<n, you can simply test it against the array of factors.

For example, 65 is a factor of 13195. Instead of testing 1 through 64, check to see if any of 13195's other factors divide 65. 65's factors have to also be a factor of 13195 so if it is not prime, there has to exist another factor of 13195 that divides 65.

// Takes a array of proper factors for some number, n,
// and returns a array of the prime factors of n.
// [descriptive function names are a good practice]
function factorsToPrimes(factors) {
    var primes = [];
    // Go through each factor
    for (var i=0; i<factors.length; i++) {
        var iIsPrime = true;
        // Check to see if any other factor divides it
        for (var j=0; j<factors.length; j++) {
            if (factors[i]%factors[j] == 0 && i != j)
                iIsPrime = false;
        }
        // If no other factor divides it, it must be prime
        if (iIsPrime)
            primes.push(factors[i]);
    }
    return primes;
}

Finding Factors

At this point, factorsOf(n) is the choke point. So if we need to go faster (and we do), we need to fix this.

Factors come in pairs. By definition, a is a factor of n if there is a b such that a*b == n. We also know that the smaller factor is always less than or equal to sqrt(n).

Thus instead of looping from 2 to n, we can loop from 2 to sqrt(n).

// Takes a number, n, and returns a array of
// all the factors of n.
function factorsOf(n) {
    var factors = [];
    for (var i = 2; i <= Math.sqrt(n); i++) {
        if (n % i === 0) {
            factors.push(i);
            factors.push(n/i);
        }
    }
    return factors;
}

The factor array and the prime factor array aren't necessarily sorted, so the final step is to find the largest prime factor. Here is a concise way to do that using max.

console.log(Math.max.apply(Math, primeFactors)); // Node.js
console.log(Math.max(...primeFactors)); // Or with ECMAScript 6 support

[Note: these changes allow you to get the correct solution (to PE #3) in about a second]

Big O Analysis

[WARNING: Unnecessary technical jargon]

Here is a Big O analysis of you code and these changes. Big O can be useful for finding performance choke points and it is a great tool for "it-works-for-small-input-but-hangs-on-large-input" problems.  So here is a breakdown of your code:

Factors -> O(n)

factorsOf -> O(n)

Prime Factors -> O(n * lg(n))

primes -> O(lg(n))
isPrime -> O(n)

Overall -> O(n * lg(n))

The time spent on finding prime factors grows the fastest. So if we want to go fast, we need to fix this. Then if we want to go faster, we need to improve our factorization. The Big O of these two changes is:

Factors -> O(sqrt(n))

factorsOf -> O(sqrt(n))

Prime Factors -> O(lg(n)^2)

factorsToPrimes -> O(lg(n)^2)

Overall -> O(sqrt(n))


Improving performance in a Webdriver method

Bunch of small things not related to your performance problem :

Utils.WaitForAjax should be Utils.waitForAjax. Method in Java start with a lower letter.
Don't return ArrayList, it's an implementation. You should use the interface List. The day you want to change to an LinkedList, it will be easier.
I recommend to always use {} for if, even if you only have just one line. But that is up to you.
I like to name ignoredException an exception that I'm ignoring. Make it more clear.

By looking at your code, I can only guess that your performance bottleneck probably is new ProductView(rProduct) or rProduct.isDisplayed(). If in ProductView your scrapping the page, it could take a lot of time depending on the driver and the method you're doing it.

But with the code your showing us right now, there is nothing particularly wrong.


The following is the IL generated for zerobits(uint x, int n, int i);

There seems to be full optimization by inlining sizeof(uint) * 8 = 32, and uint.MaxValue = -1 = 0xffffffff

The CIL runtime stack works only with 4 byte or 8 byte integers, even the LDC_I4_S pushes a byte as a 4 byte integer to the stack, so, there is no performance gain in changing parameter types to smaller integers, byte or short

A slight improvement (may be);

These methods need not to be instance members and can be defined static. Changing them to static will remove 1 push instruction to the stack (argument 0, the instance to invoke the method on) at the caller site.

That's all. 100 million iterations on my 2-cpu 8 core windows 7 HP machine executes in 17-18 ms, and 8-9 ms of it seems to be the iteration (empty loop) itself.

IL_0000:  ldarg.1       // push x (stack : x)
IL_0001:  ldc.i4.m1     // push 0xffffffff (uint.MaxValue is inlined, m1 = -1 = 0xffffffff) (stack : x, 0xffffffff)
IL_0002:  ldc.i4.s   32 // push 0x20 (sizeof(uint) * 8 is inlined) (stack: x, 0xffffffff, 0x20)
IL_0004:  ldarg.2       // push n (stack: x, 0xffffffff, 0x20, n)

IL_0005:  sub           // subtract -> (0x20 - n) (stack : x, 0xffffffff, 0x20-n)

// The following two instructions are for ENSURING SHIFTING RIGHT WITH A POSITIVE INTEGER
IL_0006:  ldc.i4.s   31 // push 0x1f (stack : x, 0xffffffff, 0x20-n, 0x1f)
IL_0008:  and           // (0x20 - n) & 0x1f (stack : x, 0xffffffff, 0x20-n) - We assume that n < 0x20

IL_0009:  shr.un        // shift right unsigned, 0xffffffff >> (0x20-n) (stack : x, 0xffffffff >> (0x20-n))

IL_000a:  ldarg.3       // push i (stack : x, 0xffffffff >> (0x20-n), i)

// The following two instructions are for ENSURING SHIFTING LEFT WITH A POSITIVE INTEGER
IL_000b:  ldc.i4.s   31 // push 0x1f (stack : x, 0xffffffff >> (0x20-n), i, 0x1f)
IL_000d:  and           // (i & 0x1f) (stack : x, 0xffffffff >> (0x20-n), i) - We assume that i < 0x20

IL_000e:  shl           // shift left (0x20-n) << i (stack : x, (0xffffffff >> (0x20-n)) << i)
IL_000f:  not           // not (stack : x, ~(0xffffffff >> (0x20-n)) << i))
IL_0010:  and           // and x & ~(0xffffffff >> (0x20-n)) << i) (stack : x & ~((0xffffffff >> (0x20-n)) << i)
IL_0011:  ret           // return x & ~(0xffffffff >> (0x20-n)) << i)


Find indices of white space characters in a string

General remarks

value, as a parameter name, isn't very descriptive,
The code considers that white spaces can only be " " or "\n" or "\t". This a performance optimization and supposes prior knowledge of the contents of the string. More generally you could make the check this way:

if char.isWhitespace {
    indices.append(index)
}

Array<Int> is not the same as [String.Index] of IndexSet. A String can be traversed using String.Index and not and Int.

Performance

The following codeis twice as fast in my tests, but doesn’t work with emoji :

func whiteSpacesIndices(in str : String) -> Array<Int> {
    var indices: Array<Int> = []
    let blanks: [UInt32] = [32, 10, 9]  //these values correspond to space, new line, and tabulation respectively.
    for (index, scalar) in str.unicodeScalars.enumerated() {
        if blanks.contains(scalar.value) {
            indices.append(index)
        }
    }
    return indices
}

You can learn more about the Unicode scalar representation here.

Free function or instance method?

The whiteSpacesIndices function seems more like a property on strings. It is appropriate for a String to know about the indices of white spaces (and new lines) within itself:

extension String {
    var whiteSpaceIndices: [Int] {
        var indices = [Int]()
        let blanks: [UInt32] = [32, 10, 9]
        for (index, scalar) in self.unicodeScalars.enumerated() {
            if blanks.contains(scalar.value) {
                indices.append(index)
            }
        }
        return indices
    }
}

And could be used like so:

"Hello world!".whiteSpaceIndices    //[5]
"ä ö ü".whiteSpaceIndices           //[1, 3]


Yeah, you're not doing yourself any favours by having the elements of the IF conditions in differing orders. It took a bit for me to re-sort everything so I could understand what the heck was going on. I think it distills down to this:

<cfscript>
    if (structKeyExists(URL, "after")){
        param name="URL.start" default=URL.after type="time";
        variables.endDate = today;  // I am not sure what scope TODAY is in, but SCOPE IT. TODAY *must* be a valid, unambiguous date string, EG YYYY-MM-DD
    }else{
        param name="URL.start" default="00:00:00" type="time";
        variables.endDate = token;  // same as with TODAY: scope it and make sure it's a valid date
    }
    param name="URL.end" default="23:59:59" type="time";

    variables.startDate = token;

    variables.start = parseDateTime("#startDate# #URL.start#"); // this could error if the contributing values don't comprise a date/time
    variables.end = parseDateTime("#endDate# #URL.end#");       // ditto
</cfscript>

<cfquery name="STUDENT" datasource="#STUD_DB#">
    SELECT *    <!--- [LIST YOUR COLUMNS HERE, DO NOT USE SELECT *] --->
    FROM student_profile
    WHERE Date_Modified BETWEEN <cfqueryparam value="#variables.start#" cfsqltype="CF_SQL_TIMESTAMP">
                        AND     <cfqueryparam value="#variables.end#"   cfsqltype="CF_SQL_TIMESTAMP">
</cfquery>

Some notes on this solution:

You probably want to do better validation than how I've just used a typed param, and parseDateTime() without first checking the thing actually parses as a date time!
You want to check and recheck the if statement logic I've used. I did not 100% compare it to your initial if logic

Some general notes:

always scope your variables.
parameterExists() has been deprecated for over ten years. Do not use it.
you seldom want to SELECT *. In general, specify the columns you want; do not return columns you don't actually need
NEVER hard-code values into the SQL string. ALWAYS pass them as parameters.
Don't use strings in place of date/times, when you are doing date operations.


If you're worried about repeating Context.Set<TEntity>() about the place, you can assign a field in your constructor instead:

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    protected readonly DbContext Context;
    protected readonly IDbSet<TEntity> Set;

    public Repository(DbContext context)
    {
        Context = context;
        Set = context.Set<TEntity>();
    }

    public TEntity Get(int id)
    {
        return Set.Find(id);
    }
}

I would say that I don't generally like generic repositories but I won't get in to that now. A lot of people use the pattern and I don't know of any canonical 'this is bad' sources so am happy to disagree over it.

One thing you do need to consider though: multiple column primary keys. That's why Find takes an array (params). You're making a method that will throw if the object has a multiple column primary key (Get).


Decrease Image downloading time with HttpURLConnection

Buffered streams usually result in greatly improved performance:

input = new BufferedInputStream(connection.getInputStream());

The buffer size is 8kb per default, tuning it may be an option (but not without measuring).

And, if you download multiple images: parallelize it with multiple threads (most of the time is consumed by I/O waits anyway), this usually improves performance by factors.


First off, it's not a stored procedure, it's a view.

That said, the main change I would make is to use a CTE, once you have upgraded.

ALTER view [dbo].[JobCost_EstVsAct]
    --SELECT * FROM JobCost_EstVsAct Where jobnumber = '122773'
AS
WITH cte1 as (
    SELECT JobNumber, CostCenter, Amount, 0 as cost
    FROM Avanti_ActiveJobBudgets AJB
),
cte2 as (
    SELECT jobnumber, costcentre as CostCenter, 0 as Amount, cost as Act
    FROM Avanti_ActiveCostDetails
),
cte3 as (
    Select * From cte1
    Union
    Select * From cte2
)
SELECT JobNumber, CostCenter, sum(Amount) as Est, sum(cost) as Act
FROM cte3
--where cost + Amount > 0     /* This line is a bug */
GROUP by JobNumber, CostCenter
HAVING sum(Amount) + sum(cost) > 0   --bug correction

Replacing the cteX with more appropriate names.


Writing data of a certain integer type to a buffer

#define CONVERT(T, F, v) T val = *(static_cast(T*, src)); \
    F( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + v ); \
    bw->curPos += length;

    [...]

    case BW_DATA_TYPE_UINT8:
    {
        CONVERT(Uint8_T, Uint8ToLittleEndianAr, 0)
        break;
    }

    case BW_DATA_TYPE_UINT16_LE:
    {
        CONVERT(Uint16_T, Uint16ToLittleEndianAr, 1)
        break;
    }

    case BW_DATA_TYPE_UINT32_LE:
    {
        CONVERT(Uint32_T, Uint32ToLittleEndianAr, 3)
        break;
    }

    case BW_DATA_TYPE_UINT64_LE:
    {
        CONVERT(Uint64_T, Uint64ToLittleEndianAr, 7)
        break;
    }

    case BW_DATA_TYPE_UINT16_BE:
    {
        CONVERT(Uint16_T, Uint16ToBigEndianAr, 1)
        break;
    }

(untested!)
You can go beyond that and even generate the whole case, but this version is a compromise to keep readability.
[EDIT] I missed the bottom of your code, but I suppose you can complete yourself... :-)


Syntax

First things first - I had to fix a handful of syntax errors for this to compile.  The most glaring is the misspelling of std::cout in many places.  The other bug is the forbidden conversion of string literals from const char* to char* - fixed by declaring a as const char* a[].

Style

The code is very dense - more whitespace around operators will help readability.  The one-letter variable names also hinder comprehension - i and j are obviously loop indexes, but what's k for?

These style issues are especially important in interviews - your interviewer wants to know whether you can write code that other employees are able to work with.

Structure

Everything here is crammed into main().  That's not great practice in general, as it makes your code hard to re-use.  Prefer to write a function - that's more amenable to unit test, allowing you to specify different strings to scroll, and to capture the output (e.g. into a std::ostringstream).

Algorithm

Rather than writing a single character at a time, it's probably easier to work with a std::string.  If we pad both ends with spaces, it's then just a matter of selecting the right substring to print at any given time.

Re-writing the code

I'd start by defining the interface I want to use.  Something like this:

#include <iostream>

int main()
{
    scroll_text(std::cout, "TEST", 4);
}

Now we know how we want to call it, let's write the signature:

void scroll_text(std::ostream& out,
                 const std::string& text,
                 unsigned width)

And now implement using the padding strategy I mentioned:

const std::string padding(width-1, ' ');
auto padded_text = padding + text + padding;

for (unsigned i = 0;  i <= padded_text.length() - width;  ++i) {
    out << padded_text.substr(i, width) << '\n';
}

Putting this all together:

#include <ostream>
#include <string>

void scroll_text(std::ostream& out,
                 const std::string& text,
                 unsigned width)
{
    const std::string padding(width-1, ' ');
    auto padded_text = padding + text + padding;

    for (unsigned i = 0;  i <= padded_text.length() - width;  ++i) {
        out << padded_text.substr(i, width) << '\n';
    }
}

// Test program

#include <iostream>

int main()
{
    scroll_text(std::cout, "TEST", 4);
}

Advanced

We could make the code more efficient by using std::string_view to reduce the amount of copying.  I won't show that here, but you might consider it as an exercise.

Another exercise - make the width argument optional, and if not specified, then use the length of the input string as the width.


Multiple if conditions in one block - looking for faster and more efficient code

First of all, your formatting seems messy, please fix it.

Did you rip it out or is there really zero documentation in there (JavaDoc)? Consider adding some, it will make your life and that of others easier.

First step would be to add an overload to match() which accepts two strings, like this:

private boolean match(Context messageContext, ContextRule contextRule) {
    return match(contextRule.getMessageContext().getUser(), messageContext.getUser())
            && match(contextRule.getMessageContext().getApplication(), messageContext.getApplication())
            && match(contextRule.getMessageContext().getService(), messageContext.getService())
            && match(contextRule.getMessageContext().getOperation(), messageContext.getOperation());
}

private boolean match(String value, String contextValue) {
    return value.equals(ContextRuleEvaluator.WILDCARD) || value.equals(contextValue);
}

This makes it already a lot easier to read. Naming of the variables is a little bit suboptimal, that's because I could not come up with better names right now.

Ultimately you should see if you can't extend and change Context to contain a match() function. This would require to change Context into an abstract class, so it might not be possible.

public abstract class Context {

    public abstract String getUser();

    public abstract void setUser(String user);

    public abstract String getApplication();

    public abstract void setApplication(String application);

    public abstract String getService();

    public abstract void setService(String service);

    public abstract String getOperation();

    public abstract void setOperation(String operation);

    /**
     * Matches this context against the given Context.
     *
     * @param context
     * @return
     */
    public boolean match(Context context) {
        return match(getUser(), context.getUser())
                && match(getApplication(), context.getApplication())
                && match(getService(), context.getService())
                && match(getOperation(), context.getOperation());
    }

    private boolean match(String value, String otherValue) {
        return value.equals(ContextRuleEvaluator.WILDCARD) || value.equals(otherValue);
    }
}

That would allow you to do this in your code:

return contextRule.getMessageContext().match(messageContext);

Which is very readable, even if you don't pack it into a function but call it directly.


Rewrite apply function to use recursion instead

Lisp is a multiparadigm language.

apply is just as lispy as recursion, and, in a way, much more so (think in HOFs)!

Style

Please fix indentation.
Please write #'foo instead of (function foo).

Implementations

The first (HOF) version can be much more efficiently rewritten in using mapcan (provided defscribe-path returns fresh lists):

(defun describe-paths (location edges)
  (mapcan #'describe-path
          (cdr (assoc location edges)))))

The second (recursive) version can be made tail recursive using an accumulator. This would help some compilers produce better code.

(defun describe-paths-recursive (location edges)
  (labels ((processx-edge (edge acc)
             (if (null edge)
                 acc
                 (processx-edge (rest edge)
                                (revappend acc (describe-path (first edge)))))))
    (nreverse (processx-edge (cdr (assoc location edges))))))

Note the use of revappend/nreverse instead of append to avoid quadraticity.


Partitioning a list to a list of smaller lists

I don't agree with your method of handling 0 or negative partition sizes.

A partition is always meant to be a sub-section of a whole. A partition with size 0 is impossible if the whole is non-empty, as there is no way to cut up a whole into sub-sections of size 0. (Note, an empty whole will of course be divisible into partitions of size 0). The same logic applies for negative values. I would think raising a RuntimeException such as an IllegalArgumentException would make more sense in that context. null objects shouldn't be partition-able either, as they are not even empty "wholes".

Now as for handling sub-section sizes larger than the size of your list, you already define that by having incomplete sub-sections if your sub-section size doesn't divide into your container size. You are missing a test for this, however.

A final remark: since Iterable isn't confined to Collection's measly 2 billion item limit for indexing, you might consider using a long for your partition size if you plan to
use this for large data sets.


Checking if multiple user-entered numbers are in the right range

This snippet is not very useful. You should not let the user continue after giving you wrong input; rather, as soon as an incorrect number is entered, you should figure out what to do next.
(As you have not included any context in your question, this is left as an exercise to you).
Your names are extremely poor:
str is a library function and should therefore never be used as a variable name.
str and ski are useless as they do not reveal what the variables are about.
Be expressive.
You are repeating yourself on a small scale: you are writing int(input(...)) twice and the two portions of the if statement follow the same logic. Get rid of the duplication.

Consider these improvements applied to your code:

Use list comprehensions and generator expressions to your advantage
Use the all(...) function with a generator expresssion to verify that all answers are in the specified range

prompts = ('text here', 'text here')
answers = [int(input(p)) for p in prompts]
if not all(0 < a <= 50 for a in answers):
    print('did not enter between 1 and 50')

# if you need to access the answers individually, use
first, second = answers


Bash script to install vim configuration files

Shebang

You should declare what shell you require to make porting the script easy and not a nightmare of commands not being available and syntactical differences leading to bugs.

#!/bin/bash

Pull conflicts

The script does not account for problems when pull does funny things like conflicting. Also to prevent changes to the executable run through PATH modifications (whether intentional or not) you may want to consider using the absolute executable path.

Looping

I'd personally prefer the simpler loop instead of the string looping you do there.

for i in $dirs
do
  if !(mkdir -p $i) then
    error_exit
  fi
done

at least on my zsh this works as intended.