Bubble Sort in Forth (for strings) I wrote the following Forth code for sorting a string with the Bubble Sort method.
It looks nice to my eyes, but I'd like your experienced opinion and any comments about the code you might have.

In the compare-and-swap-next word, is using the return stack to save base address of string ok?
the bubblesort word uses 2 pick which is not so bad? A previous version had 5 pick (!), anyway ... is 2 pick fine: don't overthink about that or maybe try some more refactoring?
How would I go about adding a check for any swaps in each round and terminate the sort early? A variable? A stack cell (on TOS)? Rethink all of the implementation?

: compare-and-swap-next ( string i -- )
   2dup + dup >r c@ rot rot 1 + + c@ 2dup >
   if     r@ c! r> 1 + c!
   else   r> drop 2drop
   then ;

: bubblesort ( string len -- string len )
   dup 1 -
   begin  dup 0>
   while  dup 0
          do   2 pick i compare-and-swap-next
          loop
          1 -
   repeat
   drop ;

\ s" abracadabra" bubblesort \ cr type
\ s" The quick brown fox" bubblesort \ cr type
\ s" a quick brown fox jumps over the lazy dog." bubblesort \ cr type

Code available on github
Nitpicks welcome! Pedantism welcome!
Thank you!

To address your immediate concerns,

Using the return stack for storing your temporaries is a perfectly valid technique.

pick is always frown upon (as well as tuck, roll, and friends). It seems that the len parameter to bubblesort does not participate in computation - except the very beginning - and mostly just stays in the way. Consider
 : bubblesort
     dup >r 1-
     ....

and use over instead of 2 pick (don't forget to r> the length at the end).

I prefer a slightly different formatting of conditional. Consider
2dup > if
    r@ c! r> 1 + c!  else
    r> drop 2drop then ;

Same for the loops. Consider
: bubblesort ( string len -- string len )
    dup 1 - begin
    dup 0> while
        dup 0 do
            2 pick i compare-and-swap-next
        loop
        1 -
    repeat
drop ;

Keeping control words together with their respective conditions/actions looks more Forthy for me.

r> drop is also known as rdrop.
rot rot is also known as -rot.


Initializing super class's variable from sub class I have written down codes something like below:

abstract class ZmqSubscriber {
   protected String zmqPort, zmqIp, zmpTopic;
   public void start() {
      init();
      // connect to zeroMQ with initialized zmq port, ip, topic and receive data
   }
   abstract protected void init();
}

abstract class Collector extends ZmqSubscriber {
   @Override
   protected void init() {
      super.zmqIp = this.zmqIp;
      super.zmqPort = this.zmqPort;
      super.zmqTopic = this.zmqTopic;
   }
   public void otherMethod() { //blablabla }
}

class Syncronizer extends ZmqSubscriber() {
   //blablabla
}

class SensorCollector extends Collector {
   private String zmqPort, zmqIp, zmpTopic;
   @Override
   protected void init() {
      //this.zmqIp, this.zmpPort, this.zmqTopic will be already initialized at this moment using Spring framework's xml config file. In this way we can change ip and port at any time
      super.zmqIp = this.zmqIp;
      super.zmqPort = this.zmqPort;
      super.zmqTopic = this.zmqTopic;
      super.init();
   }
   // getters & setters for zmq port, ip, topic
}
class BeconCollector extends Collector {
   // blablabla like SensorCollector
}

I definitely need three-level extends and this code is running well.
But I think the way of initializing super class's (ZmqSubscriber) instance variable (zmqPort, zmqIp, zmqTopic) in sub class (SensorCollector) is not elegant, I can't say exactly why I think the part is not elegant, but I'm just "Feeling" it's not right when I looking at the code, maybe it is because of the duplicated code in init() method...

Could anyone suggest more elegant architecture?

It is ok to have more than two layers if you have a good reason for it. But, because the code shows only a little part, you probably have other subclasses of ZmqSubscriber.

In SensorCollector you are hiding variables by defining new variables with the same name. This leads to a bad bug which is difficult to hunt down. In case you set the local variables and calling a method of the parent class, this method doesn't use the values of your local variables, so the method doesn't behaves like you would expect, but it is not the method's fault. You probably shouldn't hide the parent's variables.

In Collector.init() you assign a variable to itself, so those three assigns don't do anything.

Here a little prove. Note: I compare super.a and this.a with == to show that their reference are equal, which means they occupy the same memory.

class Parent { String a = "foobar"; }

class Sub extends Parent {
    Sub() { System.out.println(super.a == this.a); }

    public static void main(String[] args) {
        new Sub();
    }
}

I think init()-methods in general are doing the same job a constructor does. So in my opinion you should use constructors instead. If you cannot use a constructor have a look at the builder pattern.

This is my suggestion using constructors. I defined the variables of ZmqSubscriber as final because I think they should never change in the lifetime of the object. So you only have getters or you can make them public (but this is very controversial, depends on your coding standards).

abstract class ZmqSubscriber {
   protected final String zmqPort, zmqIp, zmpTopic;
   public ZmqSubscriber(String zmqPort, String zmqIp, String zmpTopic) {
      this.zmqIp = zmqIp;
      this.zmqPort = zmqPort;
      this.zmqTopic = zmqTopic;
   }
   public void start() {
      // connect to zeroMQ with initialized zmq port, ip, topic and receive data
   }
   // getters for zmq port, ip, topic
}

abstract class Collector extends ZmqSubscriber {
   public Collector(String zmqPort, String zmqIp, String zmpTopic) {
      super(zmqPort, zmqIp, zmpTopic);
   }
   public void otherMethod() { /*blablabla*/ }
}

class SensorCollector extends Collector {
   public SensorCollector(String zmqPort, String zmqIp, String zmpTopic) {
      super(zmqPort, zmqIp, zmpTopic);
   }
}

Is zmpTopic a typo? Shouldn't it be zmqTopic?


Test if two nodes in a binary search tree are cousins Cousins are nodes at the same level of the tree, with different parents.
They don't have to share the same grandparent.

My solution depends on having a binary search tree with unique elements.

This code is faster than writing a special find(Node *) that returns the node's level and parent, and comparing results for each node.  If the nodes are not at the same level, this version will only descend down to the level of the node closer to the top, and bail out early.

I'm looking for confirmation that it is correct.

bool are_cousins(Node *root, Node *a, Node *b)
{
    if (a == b || a == nullptr || b == nullptr) {
        return false;
    }

    Node *a_parent = nullptr;
    Node *b_parent = nullptr;
    Node *a_seek = root;
    Node *b_seek = root;
    while (a_seek != nullptr && b_seek != nullptr) {
        if (a == a_seek && b == b_seek) {
            // found both nodes at the same level
            return a_parent != b_parent;
        }

        if (a == a_seek || b == b_seek) {
            // found one node but not the other at this level. bail out
            return false;
        }

        // found neither. seek down one more level
        a_parent = a_seek;
        a_seek = (a->value < a_seek->value) ?
            a_seek->left : a_seek->right;
        b_parent = b_seek;
        b_seek = (b->value < b_seek->value) ?
            b_seek->left : b_seek->right;
    }
    return false;
}

The logic seems sane to me in general.

If the caller has the values to seek instead of node pointers, then you could change the function parameters to the value types and drop the a == nullptr || b == nullptr checks. But if the caller has node pointers that you cannot know for sure if null or not, then indeed you don't have a choice.

I find these statements more readable without the line breaks and unnecessary parentheses:

a_seek = a->value < a_seek->value ? a_seek->left : a_seek->right;
b_seek = b->value < b_seek->value ? b_seek->left : b_seek->right;


Fetch Reattempt and Hold Date count in efficient way I am using 4 queries to get below 4 values , like this i need to use about 14 queries , Is there any way to reduce queries ?

<?php
echo " " . date("Y-m-d")." ";
echo "Reattempt : "." ";

$sql =

"SELECT
 COUNT(*) as count FROM orders
 WHERE DATE(reattemptdate) = CURDATE()
 ";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;

echo " "." Hold : ";

$sql =

"SELECT
 COUNT(*) as count FROM orders
 WHERE DATE(holddate) = CURDATE()
 ";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;
echo "<br>";
?>

<?php
echo date("Y-m-d",mktime(0, 0, 0, date("m"), date("d")-1,date("Y")))." ";
echo "Reattempt : "." ";

$sql =

"SELECT
 COUNT(*) as count FROM orders
 WHERE DATE(reattemptdate) = DATE(NOW() - INTERVAL 1 DAY)
 ";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;

echo " "." Hold : ";

$sql =

"SELECT
 COUNT(*) as count FROM orders
 WHERE DATE(holddate) = DATE(NOW() - INTERVAL 1 DAY)
 ";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;

?>

You can create one query and select all elements. For example:

select sum(case when DATE(reattemptdate) = CURDATE() THEN 1 ELSE 0 END) as reattemptdate,
       sum(case when DATE(holddate) = CURDATE() THEN 1 ELSE 0 END) as holddate,
       sum(case when DATE(reattemptdate) = DATE(NOW() - INTERVAL 1 DAY) THEN 1 ELSE 0 END) as prev_reattemptdate,
       sum(case when DATE(holddate) = DATE(NOW() - INTERVAL 1 DAY) THEN 1 ELSE 0 END) as prev_holddate
from orders;

php:

$results = $db_handle->runSelectQuery($sql);
$reattemptdate =$results[0]['reattemptdate'];
$holddate =$results[0]['holddate'];
$prevReattemptdate =$results[0]['prev_reattemptdate'];
$prevHolddate =$results[0]['prev_holddate'];
// display counters
echo $reattemptdate;
echo $holddate;
echo $prevReattemptdate;
echo $prevHolddate;


SSH Class with a method for downloading via SCP I am looking for a code review on this class. I found myself writing this logic a lot, so trying to save myself some time.

require 'etc'
require 'net/ssh'
require 'net/scp'

class SSHOps
  def initialize(host, user=Etc.getlogin, *args)
    @host = host
    @user = user
    @keys = args.empty?  \
    ? args << Etc.getpwnam(Etc.getlogin).dir + '/.ssh/id_rsa' \
    : args
  end

  ##
  # Download a file over SCP.
  #
  # ==== Attributes
  #
  # * +hostname+ - Target hostname to download the file from.
  # * +filename+ - Filename to download.
  def download_file(remote_path, local_path)
    ssh = Net::SSH.start(@host, @user, :keys => @keys)
    ssh.scp.download(remote_path, local_path, :preserve => true)
    ssh.close
  end

end

Some notes:

Your documentation doesn't match... well, it doesn't match anything in your code! Wrong documentation is the only thing worse than no documentation.
A ternary should not span multiple lines. Thankfully, a regular if..else is also an expression in Ruby.

@keys = if args.empty?
  Etc.getpwnam(Etc.getlogin).dir + '/.ssh/id_rsa'
else
  args
end

While you're at it, don't name the argument args: Name it keys, since that's what it is.
I haven't played around with Net::SCP, but if I'm reading the docs right, download will return immediately (i.e. before the file's been downloaded). And your next line closes the connection. As far as I can guess, you, in effect, just cancel all of your downloads as soon as you start them. What you want is probably download! (note the bang).
Incidentally, it's perhaps overkill to make a class for this. Net::SCP already has a download! class method. If we rewrite your class with this, we get:

class SSHOps
  def initialize(host, user=Etc.getlogin, *args)
    @host = host
    @user = user
    @keys = if args.empty?
      args << Etc.getpwnam(Etc.getlogin).dir + '/.ssh/id_rsa'
    else
      args
    end
  end

  def download_file(remote_path, local_path)
    options = {
      ssh: { keys: @keys },
      preserve: true
    }
    Net::SCP.download!(@host, @user, remote_path, local_path, options)
  end
end

At this point, the class is only adding defaults for username and keys. That's it. So it might be simpler to write a few simple helper methods:

module SSHOps
  module_function

  def default_key
    File.join(Etc.getpwnam(default_user).dir, ".ssh", "id_rsa")
  end

  def default_user
    Etc.getlogin
  end

  def download!(host, remote_file, local_file)
    options = {
      ssh: { keys: [default_key] }
      preserve: true
    }
    Net::SCP.download!(host, default_user, remote_file, local_file, options)
  end
end

Which you can then use like:

SSHOps.download!("example.com", "/some/remote/file", "/some/local/file")

I've intentionally left out some stuff. My hunch is that you almost always want to use your current username and keys, because that's the functionality that your current class adds. Anything else can basically be achieved just as simply with plain Net::SCP.download!, possibly using the two other helper methods in the module above.
Of course, if you plan to download multiple files in a row, then it'd make sense to use a class if you at least reuse your SSH session rather than opening one for each download.


Does this SQL code look okay to everyone? I'm new to coding SELECT Title
FROM Film F, Award A
WHERE F.Film = a.FilmID
AND Award_Category = "Best Documentary"
AND Award_Ceremony = "Galway Film Fleadh"
AND F.Year = 2008;

SELECt Title,Year,Genre
FROM Film F, Director D
WHERE D.DirectorID = F.DirectorID
AND D.Forename = "Neil"
AND D.Surname = "Jordan";

SELECT A.Forename, A.Surname
FROM Actor A, Film F, Role R
WHERE A.ActorID = R.ActorID
AND F.Film.ID = R.FilmID
AND Part = "Harry Waters"
AND Year = "2008"
AND Made_In_Country = "Ireland"
AND F.Title = "In Bruges";

SELECT F.Title
FROM Director D,Film F, Role R,Actor A
WHERE D.DirectorId = F.DirectorID
AND F.FilmID = R.FilmID
AND A.ActorID = R.ActorID
AND D.Forename = "John"
AND D.Surname = "Forde"
AND A.Forename = "John"
AND A.Surname = "Wayne";

SELECT COUNT(Language)
FROM Film
WHERE Made_In_Country = "Ireland"
AND Langauge = "Irish"
AND Year >= 1995;

SELECT Title
FROM Film
WHERE Genre = "Western"
AND Title LIKE "%Riders%";

SELECT DISTINCT A.Forename, A.Surname
FROM Actor A, Role R
WHERE A.ActorID = R.ActorID
AND Part = "James Bond"

DELETE FROM Actor
WHERE Actor.Forename = "Steven"
AND Actor.Surname = "Spielberg";

INSERT INTO Director (Forename,Surname)
VALUES ("Steven", "Spielberg");

Assuming no actor has the same name.

SELECT A.Forename, A.Surname
FROM Actor, Award
WHERE A.ActorID = AW.ActorID
AND AW.Award_Category = "Best Actor"
AND Award_Ceremony = "Oscars"
GROUP BY A.FOrename, A.Surname
HAVING (SELECT COUNT(A.Forename,A.Surname)
FROM Actor A,Award AW
WHERE A.ActorID = AW.ActorID AND AW.Award_Category = "Best Actor"
AND Award_Ceremony = "Oscars"
GROUP BY A.Forename, A.Surname
HAVING COUNT(A.Forename, A.Surname) > 1);

It is hard to tell without more details. Like @Paparazzi said, it is more clear if you do joins using the join syntax:

SELECT Title
FROM Film F
    INNER JOIN Award A
    ON F.Film = a.FilmID
WHERE
    Award_Category = "Best Documentary"
    AND Award_Ceremony = "Galway Film Fleadh"
    AND F.Year = 2008;

Generally speaking if you are building an app you might want to do your selects using a unique ID column instead. This will be faster because you can create better indexes(ms-sql, mysql) on your tables, plus you can avoid multiple conditionals:

SELECT Title
FROM Film F
    INNER JOIN Award A
    ON F.Film = a.FilmID
WHERE
    F.Film = 1234

This is the same for your delete and presumably your update too, what if you have two directors named Steven Spielberg? Doing data changes based on ID is much more reliable.

For this query it doesn't seem to actually need a join. Is any data being pulled/compared from the Role table? I would look at all your queries to see if they really need the join or not.

SELECT DISTINCT A.Forename, A.Surname
FROM Actor A, Role R
WHERE A.ActorID = R.ActorID
AND Part = "James Bond"

Instead of using LIKE with a wildcard character in the front(thus preventing any index from being used on this field), you might want to look into full text searching if you are using SQL Server.

 SELECT Title
 FROM Film
 WHERE Genre = "Western"
 AND Title LIKE "%Riders%";

The last query with the headline Assuming no actor has the same name. is very confusing, I've never seen a query like that, is that valid sql? I believe group by and having should always be at the end.

If you post your table structure we can probably offer more improvements because from your queries there might be room for normalization improvements as well.

For MySQL run: show create table my_table\G

For SQL Server: right click your table and select Script As then select Create To


Updating one model field based on the associated model's field I'm wondering if there is any way we can optimize the following code.
Scenario is Library's active field should be true if it has any available book.

class Book < ApplicationRecord
  belongs_to :library
  scope :available, -> { where.not(deleted: true) }

  after_commit :update_library_active, on: [:update, :create]

  def update_library_active
    self.library.update_active_status
  end

end

class Library < ApplicationRecord
  has_many :books

  def update_active_status
    self.update(active: books.available.present?)
  end

end

A couple of things:

I wouldn't do this in the after_commit handler. If you do it before the commit then an error here would cause the whole transaction to fail whereas doing it after committing could potentially result in an inconsistent database.
You also want to update the library when a destroy happens which you currently doing. Even though it looks like you are using soft deletion I would consider it a good idea to cover all your bases.
books.available.exists? usually performs a little better than books.available.present? in this situation. (Because I can almost guarantee from experience that you are going to completely destroy bad data manually for some reason)
If you are need to optimize for performance you might want to check if destroyed? || deleted_changed? before running the query.
Additionally you could be more intelligent and factor in the value of the deleted flag on the current record. i.e. if it is false then you can make the library active without running a second query.


Proper way to work with stored procedures in Entity Framework Core I need to work with stored procedures, with the help of Entity Framework Core. This is my function:

public async Task<bool> CheckIfUserRegistered(string phoneNumber, DateTime dateOfBirth)
    {
        if (string.IsNullOrWhiteSpace(phoneNumber))
        {
            return false;
        }
        using (var cmd = _dbContext.Database.GetDbConnection().CreateCommand())
        {
            cmd.CommandText = "dbo.CheckIfUserRegistered";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@phoneNumber", SqlDbType.NVarChar) { Value = phoneNumber });
            cmd.Parameters.Add(new SqlParameter("@dateOfBirth", SqlDbType.Date) { Value = dateOfBirth });

            cmd.Parameters.Add(new SqlParameter("@registered", SqlDbType.Bit) { Direction = ParameterDirection.Output });

            if (cmd.Connection.State != ConnectionState.Open)
            {
                cmd.Connection.Open();
            }

            await cmd.ExecuteNonQueryAsync();

            return (bool)cmd.Parameters["@registered"].Value;
        }
    }

I'm not sure, with the correctness of this function, is this the right way to work with stored procedures in EF Core? Don't I have problems with forgotten connections, memory leakings, etc?

The biggest thing I would change is to return the connection to the state you found it.

bool isOpen = cmd.Connection.State == ConnectionState.Open;
if (!isOpen)
{
    cmd.Connection.Open();
}

await cmd.ExecuteNonQueryAsync();

if (!isOpen)
{
    cmd.Connection.Close();
}

Then, from there, I would create a helper method to build the SqlParameter objets for you:

private SqlParameter BuildParamter(string name, SqlDbType type, object value, ParameterDirection? direction)
{
    var parameter = new SqlParameter(name, type);

    if (value != null)
    {
        parameter.Value = value;
    }

    if (direction.HasValue)
    {
        parameter.Direction = direction.Value;
    }

    return parameter;
}

Then your parameters go from:

cmd.Parameters.Add(new SqlParameter("@phoneNumber", SqlDbType.NVarChar) { Value = phoneNumber });
cmd.Parameters.Add(new SqlParameter("@dateOfBirth", SqlDbType.Date) { Value = dateOfBirth });

cmd.Parameters.Add(new SqlParameter("@registered", SqlDbType.Bit) { Direction = ParameterDirection.Output });

To:

cmd.Parameters.Add(BuildParameter("@phoneNumber", SqlDbType.NVarChar, phoneNumber));
cmd.Parameters.Add(BuildParameter("@dateOfBirth", SqlDbType.Date, dateOfBirth));

cmd.Parameters.Add(BuildParameter("@registered", SqlDbType.Bit, null, ParameterDirection.Output));

It's less verbose, but if you build a lot of SqlParameter objects it might be handy to have one method you can use for all of them. (You can optionally add a int? size parameter to the method as well.)

Then, extract a SetStoredProcedure method which would take the input SqlCommand and string, set the type and command text to "dbo." + name, then you add the parameters, then ExecuteStoredProcedure would do the connection checking and then you can return your cmd.Parameters["@registered"].Value as you are. In the end something like:

SetStoredProcedure("CheckIfUserRegistered", cmd):

cmd.Parameters.Add(BuildParameter("@phoneNumber", SqlDbType.NVarChar, phoneNumber));
cmd.Parameters.Add(BuildParameter("@dateOfBirth", SqlDbType.Date, dateOfBirth));

cmd.Parameters.Add(BuildParameter("@registered", SqlDbType.Bit, null, ParameterDirection.Output));

ExecuteStoredProcedure(cmd);

return (bool)cmd.Parameters["@registered"].Value;

Optionally with your async/await pattern.

This way, if you create more stored procedures it's less work to make them operate.


Grouping similar jQuery functions I want to group the two very similar jQuery functions into just one. Any idea?

HTML:

<input id="progress" type="text" class="spinner-input form-control" maxlength="3" readonly value="<?php echo $progreso['progress'] ?>">

    <button id="plus" type="button" class="btn spinner-up btn-xs btn-info">

    </button>
    <button id="minus" type="button" class="btn spinner-down btn-xs btn-info">

    </button>

jQuery:

$(document).on('click', '#plus', function(e){
    var progress = parseInt( $('#progress').val() ) + 5;
    if ( progress <= 100 ) {
        $('#progress').val( progress );
    }
    else{
        $('#progress').val( 100 );
    };
});

$(document).on('click', '#minus', function(e){
    var progress = parseInt( $('#progress').val() ) - 5;
    if ( progress >= 0 ) {
        $('#progress').val( progress );
    }
    else{
        $('#progress').val( 0 );
    };
});

First step would be to extract a function that updates the input:

function modifyProgress(delta) {
  var element = $('#progress');
  var progress = +element.val() + delta;
  element.val( isNaN(progress) ? 0 : progress < 0 ? 0 : progress > 100 ? 100 : progress;
);
}

BTW, never ever use parseInt with out its second parameter (radix). Some browsers interpret numbers starting with a leading 0 (zero) as octal, so that an input of "09" throws an error and "010" to returns 8. Better is to use the unary plus operator.

This simplifies the event handler:

$(document).on('click', '#plus, #minus', function(e){
   modifyProgress(5 * (this.id === "plus" ? 1 : -1));
})

EDIT: You should consider storing your progress value somewhere other inside the input such as a data model (see MVC). Keeping data/logic separate from the GUI is always a good thing. It also avoids needing to re-parse the number every time. And you can "hide" the checking of overflow or underflow inside the model.


I am trying to filter a queryset based on dates, I keep getting a duplicate error on the for loops,How do I refactor these code to remove duplicates? I am trying to filter the events table to get ongoing events and complete events, but pycharm keeps underlining my code because of duplicated code. How do I prevent for loop code duplicates on the two functions below?
Better yet, how do I optimally refactor these two functions?
Thanks

def get_ongoing_events():
    ongoing_events = Events.objects.filter(
            Q(event_begin_datetime__lte=current_time),
            Q(event_end_datetime__gt=current_time),
        )
    for event in ongoing_events:
        event.event_status = 'ongoing'
        event.save()

        event.venue.status = 'booked'
        event.venue.save()

        reserve_data = dict()
        reserve_data["sensor_id"] = event.venue.sensor_id
        reserve_data["status"] = event.venue.status

        return reserve_data

def get_complete_reservation():
    """
    Update reservations and sensors
    :return:
    """
    completed_events = Events.objects.filter(
            Q(reservation_begin_datetime__lt=current_time),
            Q(reservation_end_datetime__lte=current_time),
        )

    for event in completed_events:
        event.reservation_status ='complete'
        event.save()

        event.venue.status = 'free'
        event.venue.save()
        reserve_data = dict()
        reserve_data["sensor_id"] = event.venue.sensor_id
        reserve_data["status"] = event.venue.status
        return reserve_data
```

Factoring duplication out
Whenever I have (near-)duplicate code, what I do is take a look at the repeated code. The parts that change ever so slightly are going to be controlled with arguments to functions and etc, whereas the parts that remain the same will just be left more-or-less as-is.
Having said that, here is what I see:

the queries being used change, so those are function arguments;
the attributes of the event being updated change, so those are function arguments;
the final dict being generated is the same, so we leave it the same.

From your code alone, here is a suggested modification:
def filter_and_update_events(Qs, event_changes, venue_changes):
    for event in Events.objects.filter(*Qs)
        for attr, new_value in event_changes.items():
            setattr(event, attr, new_value)
        event.save()
        for attr, new_value in venue_changes.items():
            setattr(event.venue, attr, new_value)
        event.venue.save()

        reserve_data = dict()
        reserve_data["sensor_id"] = event.venue.sensor_id
        reserve_data["status"] = event.venue.status
        return reserve_data

def get_ongoing_events():
    return filter_and_update_events(
        [
            Q(event_begin_datetime__lte=current_time),
            Q(event_end_datetime__gt=current_time),
        ],
        {"event_status": "ongoing"},
        {"status": "booked"},
    )

def get_complete_reservation():
    """
    Update reservations and sensors
    :return:
    """
    return filter_and_update_events(
        [
            Q(reservation_begin_datetime__lt=current_time),
            Q(reservation_end_datetime__lte=current_time),
        ],
        {"reservation_status": "complete"},
        {"status": "free"},
    )

Notice that I used setattr docs to set the attributes of the event and the venue.
Also notice that my new function has a bit of duplication in the loops, but that is the easiest way to deal with the fact that venue is inside event and there is no obvious way to use setattr to deal with the nesting.
If you need to expand your function to update even more things inside event, then I would also recommend creating a helper function that takes an event and a "setting name" and sets it, so that filter_and_update_events doesn't need to take one dictionary per object inside event.
Does this make sense?


Review my F# QuickSort Program OK... last sort of the day and probably the most fun. F# is really awesome.

let rec quickSort list =
    match list with
    | [] -> []
    | [x] -> [x]
    | hd :: _ ->
        quickSort (List.filter (fun x -> x < hd) list) @ hd :: quickSort (List.filter (fun x -> x > hd) list)

[<EntryPoint>]
let main args =
    printfn "%s" (List.fold (fun acc x -> acc + " " + x.ToString()) "" (quickSort [10; 7; 1; 0; -1; 9; 33; 12; 6; 2; 3; 33; 34;]))
    0

let me know How I can improve this code. I am trying to think functionally and want my program to be most efficient, concise and functional.

I'd:

exclude unnecessary duplication (List.filter etc.)
drop separate match rule for the list of one element
rely on type inference
use more succinct form of pattern matching

Something like this:

let rec qsort = function
    | [] -> []
    | x::xs -> let lt, ge = List.partition ((>) x) xs
               qsort lt @ x :: qsort ge


Listing the weeks in a given month I need to take a month (defined as a start and end date) and return a set of date ranges for each week in that month.  A week is defined as Sunday through Saturday.  A good way to visualize it is if you double click on your Windows date in the start bar:

The month of October 2011 has 6 weeks:

  10/1-10/1

  10/2-10/8

  10/9-10/15

  10/16-10/22

  10/23-10/29

  10/30-10/31

I can describe each week as a struct:

   struct Range
   {
      public DateTime Start;
      public DateTime End;

      public Range(DateTime start, DateTime end)
      {
         Start = start;
         End = end;
      }
   }

I need to write a function that takes a month and returns an array of ranges within it.  Here's my first attempt, which appears to work and addresses the obvious edge cases:

public static IEnumerable<Range> GetRange(DateTime start, DateTime end)
{
   DateTime curStart = start;
   DateTime curPtr = start;
   do
   {
      if (curPtr.DayOfWeek == DayOfWeek.Saturday)
      {
         yield return new Range(curStart, curPtr);
         curStart = curPtr.AddDays(1);
      }

      curPtr = curPtr.AddDays(1);
   } while (curPtr <= end);

   if(curStart <= end)
      yield return new Range(curStart, end);
}

I would like to know if there's a cleaner or more obvious approach to do the same.  I'm not overly concerned about performance, but I'd like to improve code readability and make the algorithm a bit more concise.  Perhaps there's a very creative solution involving a single LINQ expression or something.

Well, first of all your range only has to store the start date, as the weeks are always the same length:

struct Range {

  public DateTime Start { get; private set; }

  public DateTime End { get { return Start.AddDays(6); } }

  public Range(DateTime start) {
     Start = start;
  }

}

Getting the weeks can simply be done by looking for sundays starting six days into the previous month:

public static IEnumerable<Range> GetRange(int year, int month) {
  DateTime start = new DateTime(year, month, 1).AddDays(-6);
  DateTime end = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
  for (DateTime date = start; date <= end; date = date.AddDays(1)) {
    if (date.DayOfWeek == DayOfWeek.Sunday) {
      yield return new Range(date);
    }
  }
}

To clarify: This returns the whole weeks that have days in the month, not partial weeks created from the days in the month by grouping them by what week they belong to.


Killing and restarting processes I am a beginner with Erlang and currently making my way through the awesome Joe Armstrong's book. The following are my answers to exercises 5 and 6 for the concurrency chapter. The code can probably be much better but at least it seems to work fine after some tests. I'm just happy to be able to understand this language, I'm def having to re-learn how to think about my programming logic, and I think that's a good thing.

5) Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, restart it.

ex5_start(FList) ->
    spawn(fun() ->
        [bring_back(F) || F <- FList]
        end).

bring_back(FID) ->
    spawn(fun() ->
        {Pid, Ref} = spawn_monitor(FID),
            io:format("Pid = ~p~n",[Pid]),
            receive
                {'DOWN', Ref, process, Pid, normal} -> void;
                {'DOWN', Ref, process, Pid, _Why} -> bring_back(FID)
            after infinity -> void
            end
        end).

6) Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, kill all the worker processes and restart them all.

ex6_start(Flist) when is_list(Flist) ->
    Size = length(Flist),
    spawn(fun() ->
            {Pid,Ref} = spawn_monitor(fun() ->
                                        start_and_monitor(Size,Flist),
                                        receive
                                        after infinity -> true
                                        end
                                    end),
            receive
                {'DOWN',Ref,process,Pid,_} -> io:format("All dead. Restarting.~n") ,
                ex6_start(Flist)
            end
        end).

start_and_monitor(1,Flist) ->
    Fun = lists:nth(1,Flist),
    Pid = spawn_link(Fun),
    io:format("Pid ~p created.~n",[Pid]);
start_and_monitor(N,Flist) ->
    Fun = lists:nth(N,Flist),
    Pid = spawn_link(Fun),
    io:format("Pid ~p created.~n",[Pid]),
    start_and_monitor(N-1,Flist).

For the first problem:

You are using more processes than strictly needed, since you

spawn a process A that
spawns a number of monitoring processes M that each
spawn a worker W and monitoring it.

If a worker fails, you spawn a new monitor 'M' and a new worker.

ex5_start(FList) ->
    spawn(fun() -> %% This is the spawn of process A
        [bring_back(F) || F <- FList] %% This is the list for B's
        end).

bring_back(FID) ->
    spawn(fun() -> %% This is the spawning of an M
        {Pid, Ref} = spawn_monitor(FID), %% This is the spawning of a W
            io:format("Pid = ~p~n",[Pid]),
            receive
                {'DOWN', Ref, process, Pid, normal} -> void;
                {'DOWN', Ref, process, Pid, _Why} ->
                    %% New M and W
                    bring_back(FID)
            after infinity -> void %% you can skip this entire line
            end
        end).

An after clause with a hardcoded infinity timeout is never going to be executed, so you can skip it.

You can think of a simpler solution, where you spawn_monitor the workers and associate their FIDs with a Pid and Ref (e.g. in a list comprehension) and then have a second phase in which whenever a DOWN message arrives you lookup the relevant worker PID and restart its FID. You don't even need a separate A process.

For the second problem:

Several things seem off:

You are using an intermediate process on which all others are linked
This intermediate process will block on this piece of code:

                                receive
                                after infinity -> true
                                end

you are not killing all processes on an error, just linking them all to die together with the intermediate process. This may not be what is needed, if e.g. some process is trapping exit signals.
If all processes exit normally, the intermediate process will remain blocked forever.

If you follow my suggestion for the previous question, it is easy to replace the second phase with a different one that does the correct thing (remember to also keep track of processes that have died normally).


Ensuring HttpClient can be used safely as a singleton There has been talk recently of how we should be handling the lifetime of the System.Net.Http.HttpClient.

This article http://byterot.blogspot.co.uk/2016/07/singleton-httpclient-dns.html says that we should use it as a singleton, but we need to be careful about ensuring the connections are properly closed otherwise DNS changes won't be honoured.

I came up with the following message handler which can be injected in to an HttpClient to take care of setting the connection lease for each distinct scheme + host combination.

public class ServicePointManagingMessageHandler : HttpClientHandler
{
    private readonly ConcurrentDictionary<Uri, ServicePoint> _uriCache = new ConcurrentDictionary<Uri, ServicePoint>();
    private readonly int _oneMinuteInSeconds = (int)TimeSpan.FromMinutes(1).TotalSeconds;

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.RequestUri.IsAbsoluteUri)
        {
            var baseUri = new Uri($"{request.RequestUri.Scheme}://{request.RequestUri.Host}");

            _uriCache.AddOrUpdate(baseUri, uri =>
            {
                var sp = ServicePointManager.FindServicePoint(uri);
                sp.ConnectionLeaseTimeout = _oneMinuteInSeconds;

                return sp;
            }, (uri, point) => point);
        }

        return base.SendAsync(request, cancellationToken);
    }
}

Usage:

var client = new HttpClient(new ServicePointManagingMessageHandler());

I am wondering if the concept of intercepting the URI's as they come in to the HttpClient will allow the HttpClient to safely be used as a singleton without any of the issues listed in that article.

This gets around needing to know all hostnames that you might connect to at startup by intercepting calls - if people agree with this approach then it seems like it should become the accepted way to use the HttpClient for standard cases.

Just a few things:

You have already named the variable _oneMinuteInSeconds - I'd say you don't gain much by initializing it via a TimeSpan the way you do it. Just saying _oneMinuteInSeconds = 60 would be good enough since it's quite clear what the 60 stands for.
Actually, according to MSDN the ConnectionLeaseTimeout is set in milliseconds as such your code is of by a factor of 1000 regarding the timeout (why the framework designers have not consistently used TimeSpan everywhere is a bit of a mystery to me).


(Codewars): Find the Unknown Digit Kata: https://www.codewars.com/kata/find-the-unknown-digit/train/python

  To give credit where credit is due: This problem was taken from the ACMICPC-Northwest Regional Programming Contest. Thank you problem writers.

  You are helping an archaeologist decipher some runes. He knows that this ancient society used a Base 10 system, and that they never start a number with a leading zero. He's figured out most of the digits as well as a few operators, but he needs your help to figure out the rest.

  The professor will give you a simple math expression, of the form

[number][op][number]=[number]

  He has converted all of the runes he knows into digits. The only operators he knows are addition (+),subtraction(-), and multiplication (*), so those are the only ones that will appear. Each number will be in the range from -1000000 to 1000000, and will consist of only the digits 0-9, possibly a leading -, and maybe a few ?s. If there are ?s in an expression, they represent a digit rune that the professor doesn't know (never an operator, and never a leading -). All of the ?s in an expression will represent the same digit (0-9), and it won't be one of the other given digits in the expression. No number will begin with a 0 unless the number itself is 0, therefore 00 would not be a valid number.

  Given an expression, figure out the value of the rune represented by the question mark. If more than one digit works, give the lowest one. If no digit works, well, that's bad news for the professor - it means that he's got some of his runes wrong. output -1 in that case.

  Complete the method to solve the expression to find the value of the unknown rune. The method takes a string as a paramater repressenting the expression and will return an int value representing the unknown rune or -1 if no such rune exists.

My Solution

import re, operator as op

parse_op = re.compile(r"(-?[0-9?]+)([-+*])(-?[0-9?]+)(=)(-?[0-9?]+)")  #For parsing the LHS.
ops = {"*": op.mul, "+": op.add, "-": op.sub}

def solve_runes(s):
    search = set("0123456789") - set(c for c in s if c.isnumeric())
    n = [0]*3
    n[0], op, n[1], x, n[2] = parse_op.search(s).groups()
    if any(len(x) > 1 and x[0] == "?" for x in n):
        search -= {"0"}
    for digit in sorted(search):
        v = [int(x.replace("?", digit)) for x in n]
        if ops[op](v[0], v[1]) == v[2]:
            return int(digit)
    return -1

Sample Test Case

test.assert_equals(solve_runes("1+1=?"), 2, "Answer for expression '1+1=?' ")
test.assert_equals(solve_runes("123*45?=5?088"), 6, "Answer for expression '123*45?=5?088' ")
test.assert_equals(solve_runes("-5?*-1=5?"), 0, "Answer for expression '-5?*-1=5?' ")
test.assert_equals(solve_runes("19--45=5?"), -1, "Answer for expression '19--45=5?' ")
test.assert_equals(solve_runes("??*??=302?"), 5, "Answer for expression '??*??=302?' ")
test.assert_equals(solve_runes("?*11=??"), 2, "Answer for expression '?*11=??' ")
test.assert_equals(solve_runes("??*1=??"), 2, "Answer for expression '?*11=??' ")

In this code, I find it misleading that n is first assigned zeros,
and then its content is replaced with strings.

n = [0]*3
n[0], op, n[1], x, n[2] = parse_op.search(s).groups()

I think it would be more clear this way:

num1, op, num2, _, num3 = parse_op.search(s).groups()
nums = [num1, num2, num3]

Notice that I replaced x with _. It's a common convention when a variable is unused.

Some doctests with example inputs and expected outputs would be great too,
making the code easier to digest, and play with.


Atbash Cipher in Rust - Exercism exercise So I'm working on an implementation of the Atbash Cipher for Rust - it is an exercise on exercism.io. I come from a little C experience and found my code to be rather round about and kind of tortured. Doing str and String manipulation in Rust is something I haven't really grokked yet. It seems like this would take up fewer lines of code in C.

Below is my code - am I going about this in the right way for Rust, or am I missing some important concept or way of manipulating the data? Is this as simple as it should be?

The exercise involves getting an input &str and outputting a String, with each character changed as per the Atbash cipher, adding a space every 5 characters. Included is also a decode function. This all goes in a lib.rs.

// "Encipher" with the Atbash cipher.
pub fn encode(plain: &str) -> String {
    let mut coded: String = plain.to_string();

    coded.retain(|c| c.is_ascii_alphanumeric());
    coded.make_ascii_lowercase();

    let coded_no_spacing = String::from_utf8(
        coded
            .bytes()
            .map(|c| {
                if c.is_ascii_alphabetic() {
                    122 - c + 97
                } else {
                    c
                }
            })
            .collect(),
    )
    .unwrap();

    spacer(coded_no_spacing)
}

/// "Decipher" with the Atbash cipher.
pub fn decode(cipher: &str) -> String {
    let mut out = encode(cipher);
    out.retain(|c| c.is_ascii_alphanumeric());
    out
}

fn spacer(coded_no_spacing: String) -> String {
    let mut coded_no_spacing = coded_no_spacing.chars();

    let mut temp_char = coded_no_spacing.next();
    let mut counter = 0;
    let mut coded_with_spaces = "".to_string();
    while temp_char.is_some() {
        if counter % 5 == 0 && counter != 0 {
            coded_with_spaces.push(' ');
        }
        coded_with_spaces.push(temp_char.unwrap());
        temp_char = coded_no_spacing.next();
        counter += 1;
    }
    coded_with_spaces
}

// "Encipher" with the Atbash cipher.
pub fn encode(plain: &str) -> String {
    let mut coded: String = plain.to_string();

    coded.retain(|c| c.is_ascii_alphanumeric());
    coded.make_ascii_lowercase();

    let coded_no_spacing = String::from_utf8(
        coded
            .bytes()
            .map(|c| {
                if c.is_ascii_alphabetic() {
                    122 - c + 97

You can b'z' and b'a' to refer to the ascii codes of the letters.

                } else {
                    c
                }
            })
            .collect(),
    )
    .unwrap();

    spacer(coded_no_spacing)
}

You are mixing two different approaches here. Firstly, you make a string out of the input and then modify it. Secondly, you use an iterator over the bytes of the string. This code would be more straightforward if you just iterated over the letters.

Here is my approach:

plain
    .chars()
    .filter_map(|c| {
        if c.is_ascii_alphabetic() {
            let letter = c.to_ascii_lowercase() as u8;
            Some(char::from(b'z' - letter + b'a'))
        } else if c.is_ascii_alphanumeric() {
            Some(c)
        } else {
            None
        }
    })
    .collect()

If you haven't seen it before, the filter_map function combines filtering and mapping. The closure can return either None, to remove the element or Some(x) to provide an element in the output.

/// "Decipher" with the Atbash cipher.
pub fn decode(cipher: &str) -> String {
    let mut out = encode(cipher);
    out.retain(|c| c.is_ascii_alphanumeric());
    out
}

It took me a bit to figure out why you were filtering the chars again. But I see it is remove the spacing. It would make more sense to split the basic ciphering and into its own function so you can call that without adding the spacing. Then you wouldn't have to filter it.

fn spacer(coded_no_spacing: String) -> String {
    let mut coded_no_spacing = coded_no_spacing.chars();

    let mut temp_char = coded_no_spacing.next();
    let mut counter = 0;
    let mut coded_with_spaces = "".to_string();

I would use String::new() to create an empty string. For "extra credit", you could use String::with_capacity to reserve the correct amount of space for the string, something like:

String::with_capacity(coded_no_spacing.len() + coded_no_spacing.len() / 5);

That's dubiously worthwhile, but sometimes it can be a helpful optimization.

Onwards:

    while temp_char.is_some() {

Firstly, there is a construct you can use when you want to iterate as long as something return Some instead of None.

while let Some(temp_char) = coded_no_spacing.next()

But in this case, this is just iterating over for the chars, so you should use a forloop

for temp_char in coded_no_spacing.chars()

        if counter % 5 == 0 && counter != 0 {
            coded_with_spaces.push(' ');
        }
        coded_with_spaces.push(temp_char.unwrap());
        temp_char = coded_no_spacing.next();
        counter += 1;

Instead of counting, use the enumerate() method on iterator. It will give you an index.

    }
    coded_with_spaces
}

Here is my version:

fn spacer(coded_no_spacing: &str) -> String {
    let mut coded_with_spaces = String::new();

    for (index, char) in coded_no_spacing.chars().enumerate() {
        if index % 5 == 0 && index != 0 {
            coded_with_spaces.push(' ');
        }
        coded_with_spaces.push(char);
    }

    coded_with_spaces
}


Counting penalties for each player by joining tables, where some of the data is null I have a table full of player names:

I also have a table full of player penalties:

I have to list all of the players names, player numbers, and the number of penalties that they've incurred.

To do that, I'm using this code:

select players.playerno, name, ifnull(`Penalty count`, 0) as `Penalty count` from players
left join
(select players.playerno, count(players.playerno) as `Penalty count` from players, penalties
where players.playerno = penalties.playerno
group by players.playerno) as `query1`
on players.playerno = query1.playerno
order by playerno

The code works. Here's the output table:

It seems like a lot of code just to merge two tables together. Is there a better way to do it?

I've also read online that keeping the NULL is generally a better practice than changing it to zero, but would that apply in this case, since it's supposed to be the total number of penalties? It seems like NULL would give the impression of "no data" or "unknown data", but in this case the number is known to be zero.

You should stay away from pre-ANSI92 join syntax, as it is more error-prone and more difficult to read. It's better to use explicit join syntax in all cases.

This join:

from players, penalties
where players.playerno = penalties.playerno

Should be written as:

from players
join penalties
  on players.playerno = penalties.playerno

The primary reasons for this are:

Avoid accidental cross/Cartesian joins if you forgot a WHERE clause.
Easier to read, since your join conditions are isolated in the ON clause instead of being mixed in with your filtering criteria in the WHERE clause.

Use meaningful table aliases to shorten column references. For instance, players AS ply and penalties AS pen would make for good aliases. Do avoid using single-letter aliases like p though, for readability.

select ply.playerno, ply.name, count(pen.playerno)
from players AS ply
left join penalties AS pen
...

Use vertical white space (i.e. new lines) to make statements, in particular SELECT clauses, easier to read:

select
    ply.playerno,
    ply.name,
    count(pen.playerno) as `Penalty count`
from ...

MySQL uses all lowercase for all table, columns, etc. identifiers, so using UPPER CASE for keywords makes it easier to tell SQL keywords from identifiers. Also, name is a reserved SQL keyword, so when you have a column called name (or any other SQL keyword) it should be quoted with back-ticks like:

SELECT ply.playerno, ply.`name` FROM players AS ply

There is a much simpler way to aggregate this than how you have done it, with no need for a nested sub-query with an additional join. COUNT(), like other SQL aggregate functions, will take care of handling potentially NULL aggregates to zero, as long as they are included in the query (in this case by using LEFT JOIN instead of INNER JOIN), so we can get the same result much more simply like this:

SELECT
    ply.playerno,
    ply.`name`,
    COUNT(pen.playerno) AS `Penalty count`
FROM players AS ply
LEFT JOIN penalties AS pen
    ON ply.playerno = pen.playerno
GROUP BY
    ply.playerno,
    ply.`name`
ORDER BY
    ply.playerno;


JS Custom Event System I've written the following custom event system module and I'm planning to use it in production in the future. Before I do that, I'd like to ask for general suggestions on how to improve it. Thanks a lot.
const event = (function() {

  let registry = {};

  function on(event, callback) {
    if(!registry[event]) registry[event] = [];
    registry[event].push(callback);
  }

  function once(event, callback) {
    if(!registry[event]) registry[event] = [];
    registry[event].push(function(message) {
      callback(message);
      off(event, callback);
    });
  }

  function off(event, callback) {
    if(registry[event]) {
      registry[event].splice(registry[event].indexOf(callback), 1);
      if(!registry[event].length) delete registry[event];
    }
  }

  function emit(event, message) {
    if(registry[event]) {
      registry[event].forEach(callback => {
        callback(message);
      });
    }
  }

  function getListeners(event) {
    return registry[event] ? registry[event] : null;
  }

  return {
    on: on,
    once: once,
    off: off,
    emit: emit,
    getListeners: getListeners
  }
})();

export { event };

Usage:
Add event listener:
event.on('someEvent', someEventhandler);

Remove event listener:
event.off('someEvent', someEventhandler);

Add event listener and remove it after first use:
event.once('someEvent', someEventhandler);

Fire the event:
event.emit('someEvent');

Get all eventhandlers for an event:
event.getListeners('someEvent');

While there are examples of how the code can be used, it would be helpful for anyone reading the code (including your future self) to have a comment block above each method to describe the purpose, parameters, return value and any possible error that could be thrown.

The question is tagged with performance- are you trying to optimize the code for speed? If so, it would be better to use a for loop instead of functional methods that use iterators - e.g. Array.prototype.forEach(), Array.prototype.indexOf().

Has the code been tested? Are there any unit tests for the module? If not, it would be wise to create tests to cover all aspects of the code.
Correct me if I am wrong but looking at how the off() method is implemented my presumption is that the call from once() will not actually remove any callback, given that a wrapped function is registered instead of the callback parameter.

There appears to be no validation that the callback is a function. This could lead to an error if some other type is passed in that parameter.

The shorthand property definition notation can be used to simplify the following lines:

 return {
    on: on,
    once: once,
    off: off,
    emit: emit,
    getListeners: getListeners
  }

To this:
return {
    on,
    once,
    off,
    emit,
    getListeners
  }

You may be interested in reading the responses I received on similar code I wrote- see Event emitter npm module


Airline/Hotel reservation system in Python I am trying to teach myself OOP in Python. I am picking up some projects from GitHub and trying it out on my own. I wrote a Airline/Hotel Reservation System, where I want to maintain the customer name, ID and maintain a record for Airline or Hotel or Both. I am not sure if my design is correct. I want some input on how to improve the design for my code.

class Reservation:
   def __init__(self,passenger_id,passenger_fname,passenger_lname):
      self.passenger_id = passenger_id
      self.passenger_fname = passenger_fname
      self.passenger_lname = passenger_lname
      self.cost = 0
      self.reservation_id = []
      self.passenger_record = {'p_name'  : self.passenger_fname + self.passenger_lname,
                             'p_id'    : self.passenger_id,
                             'p_wallet': self.cost,
                             'p_reservation_id': self.reservation_id,
                            }
      self.airline_seats = { 'Business Class' : 50,
                           'First Class'    : 50,
                           'Premium Economy': 100,
                           'Regular Economy': 150 }
      self.airline_price = { 'Business Class' : 2500,
                           'First Class'    : 2000,
                           'Premium Economy': 1800,
                           'Regular Economy': 1500 }
      self.hotel_room = {'Penthouse'             : 10,
                       'King Deluxe Bedroom'    : 20,
                       'Queen Deluxe Bedroom'   : 20,
                       'Kind Standard Bedroom' : 30,
                       'Queen Standard Bedroom': 50 }
      self.hotel_price = {'Penthouse'            : 1000,
                        'King Deluxe Bedroom'    : 700,
                        'Queen Deluxe Bedroom'   : 600,
                        'Kind Standard Bedroom' : 450,
                        'Queen Standard Bedroom': 350 }
   def currentStatus(self,option):
       if option == "Airline":
           for key, value in self.airline_seats.items():
              print key, value
       elif option == "Hotel":
           for key,value in self.hotel_room.items():
              print key, value

   def Total(self):
       print self.passenger_record['p_wallet']

class Airline(Reservation):
   def __init__(self,passenger_id,passenger_fname,passenger_lname,airline_seat_section,
         airline_departure_date):
       Reservation.__init__(self,passenger_id,passenger_fname,passenger_lname)
       self.airline_seat_section = airline_seat_section
       self.airline_departure_date = airline_departure_date

   def CheckAvailability(self):
       if  (self.airline_seats.get(self.airline_seat_section) != 0):
            self.airline_seats[self.airline_seat_section] -= 1
            self.passenger_record['p_wallet'] +=        self.airline_price[self.airline_seat_section]
            print "\n\nReserved Airline Ticket\n\n"

class Hotel(Reservation):
    def __init__(self,passenger_id,passenger_fname,passenger_lname,hotel_room_selection,
             hotel_check_in_date,hotel_check_out_date):
        Reservation.__init__(self,passenger_id,passenger_fname,passenger_lname)
        self.hotel_room_selection = hotel_room_selection
        self.hotel_check_in_date = hotel_check_in_date
        self.hotel_check_out_date = hotel_check_out_date

    def CheckAvailability(self):
        if (self.hotel_room.get(self.hotel_room_selection) != 0):
            self.hotel_room[self.hotel_room_selection] -= 1
            self.passenger_record['p_wallet'] += self.hotel_price[self.hotel_room_selection]
            print "\n\nReserved Hotel Room\n\n"

A1 = Airline("1","Arun","Raman","Business Class","07-07-2014")
A1.CheckAvailability()
A1.currentStatus("Airline")
H1 = Hotel("1","Arun","Raman","Penthouse","07-07-2014","07-10-2014")
H1.CheckAvailability()
H1.currentStatus("Hotel")

One obvious issue is that all of the data for hotels and airlines is stored in the base Reservation class. You should move it to the relevant sub-classes, and I would store it as class attributes (shared by all instances) rather than instance attributes (unique to each instance), otherwise you won't be tracking the correct numbers of free rooms:

class Hotel(Reservation):

    HOTEL_ROOM = {'Penthouse': 10,
                  'King Deluxe Bedroom': 20,
                  'Queen Deluxe Bedroom': 20,
                  'King Standard Bedroom': 30,
                  'Queen Standard Bedroom': 50}

Also, as it stands, your code effectively makes the booking before it checks the availability. If you try to book something when it's already booked up, you should be raising an error. The customer is too closely tied to e.g. the Hotel - think about it in real terms, do you have the names of all of the customers when you build a new hotel?

A better option would be to create a new class structure:

Reservation

HotelReservation
AirlineReservation

Bookable

Hotel
Airline

Customer

All Bookables (which you could extend to e.g. CarHire in the future) would implement check_availability and make_reservation. To make it clear that the sub-classes should implement these, you can put a stub in the parent:

class Bookable(object):

    def check_availability(self, *details):
        raise NotImplementedError

    def make_reservation(self, *details):
        raise NotImplementedError

The sub-classes would then have information specific to that type (e.g. a Hotel would have rooms, an Airline seats, etc.) and their implementations of those methods would reflect that.

The Reservation would then connect the Customer to a Bookable (you might even find you don't need the sub-classes there - what's the difference between an airline reservation and a hotel reservation?) This would go both ways - a Hotel needs to know when to expect whom, and a Customer needs to know what they have booked.

Your code might now look like:

a1 = Airline("Qantas")
h1 = Hotel("Mayfair")
c1 = Customer("Arun", "Raman")

if a1.check_availability("Business Class", "07-07-2014"):
    r1 = a1.make_reservation(c1, "Business Class", "07-07-2014")

if h1.check_availability("Penthouse", "07-07-2014", "07-10-2014"):
    r2 = h1.make_reservation(c1, "Penthouse", "07-07-2014", "07-10-2014")

print(c1.bookings)

Looking at that, I'm thinking:

Could we cut the repetition of booking details? Perhaps introduce a Booking class? (e.g. b1 = Booking(c1, details) then for h in hotels: if h.check_availability(b1): h.make_reservation(b1))
Make the dates actual datetime objects, not strings.

But I will leave it there for now.


Permutation generator with OR operator Problem: Given a vector of strings, I want to print out all possible permutations where the strings may contain an OR operator (the | character, as in regular expressions).

Example Input: the strings race and car|horse

Example Output:

race car
race horse
car race
horse race

This code uses -std=c++17 and helper code from other programmers (if this makes it off topic, I will recode these parts).

This is faster than the Python version from one of my questions on a sibling site.

Code:

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

// Begin helper function from https://stackoverflow.com/a/236803/10976976
template <typename Out>
void split(const std::string &s, char delim, Out result) {
    std::istringstream iss(s);
    std::string item;
    while (std::getline(iss, item, delim)) {
        *result++ = item;
    }
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, std::back_inserter(elems));
    return elems;
}
// End helper function from https://stackoverflow.com/a/236803/10976976

// Begin helper function from https://stackoverflow.com/a/17050528/10976976
std::vector<std::vector<std::string>> cart_product (const std::vector<std::vector<std::string>>& v) {
    std::vector<std::vector<std::string>> s = {{}};
    for (const auto& u : v) {
        std::vector<std::vector<std::string>> r;
        for (const auto& x : s) {
            for (const auto y : u) {
                r.push_back(x);
                r.back().push_back(y);
            }
        }
        s = std::move(r);
    }
    return s;
}
// End helper function from https://stackoverflow.com/a/17050528/10976976

int main() {
    std::vector vector_of_strings{"C++|Python|PHP", "Is|Is Not", "Good|Great|Excellent|Exceptional"};
    std::vector<std::vector<std::string>> vector_of_vector_of_strings;

    for (auto& word_possibilities_string : vector_of_strings) {
        auto word_possibilities = split(word_possibilities_string, '|');
        vector_of_vector_of_strings.push_back(word_possibilities);
    }

    // vector_of_vector_of_strings is now {{C++, Python, PHP}, {Is, Is Not}, {Good, Great, Excellent, Exceptional}}

    auto sentences = cart_product(vector_of_vector_of_strings);

    for (auto& sentence : sentences) {
        std::sort(sentence.begin(), sentence.end());

        do {
            const auto seperator = " ";
            const auto* sep = "";

            for (const auto& word : sentence) {
                std::cout << sep << word;
                sep = seperator;
            }

            std::cout << "\n";
        } while(std::next_permutation(sentence.begin(), sentence.end()));
    }
}

Output (I'm sure you'll agree with the statements below):

C++ Good Is
C++ Is Good
Good C++ Is
Good Is C++
Is C++ Good
Is Good C++
...
Exceptional Is Not PHP
Exceptional PHP Is Not
Is Not Exceptional PHP
Is Not PHP Exceptional
PHP Exceptional Is Not
PHP Is Not Exceptional

In the future, I will be reading in vector_of_strings from a file and passing in the starting permutation as arguments.

For example: ./permutation_generator words.txt PHP Exceptional "Is Not" will output:

PHP Exceptional Is Not
PHP Is Not Exceptional

user673679 already mentioned that a lot of string copying is going on. Indeed, std::string_view could be used here to just keep references to the original input strings, saving both time and space.

Give your variables meaningful names

Your variable names should tell you something about the contents of the variable, not of the type of the variable. So don't write std::vector<std::string> vector_of_strings, but give it a more descriptive name such as input if it's the input to your program, and possibilities instead of vector_of_vector_of_strings.

Also avoid variable names that are too alike, such as separator and sep in your main() function. In this case, you can avoid it by writing the code like so:

bool first = true;

for (const auto &word: sentence) {
    if (first)
        first = false;
    else
        std::cout << " ";

    std::cout << word;
}

Don't abbreviate too much, just write carthesian_product instead of cart_product. The latter abbreviation is not common and might confuse others that do not know that you mean Carthesian product here.

Use more algorithms?

Since you are already using some of the C++ standard library algorithms, why not use more? For example, instead of writing a for-loop to create the vector of vector of strings, write:

std::transform(input.begin(), input.end(),
               std::back_inserter(possibilities),
               [](std::string words){
                   return split(words, '|');
               });

Although arguably, it doesn't improve readability much here.

Split off more functionality into their own functions

The main() function could be cleaned up and made more readable if you moved some of its parts to properly named functions. For example, instead of creating the vector of vector of strings inline, it would be nice it you could just write:

auto possibilities = split_possibilities(input);

Also, consider creating a join() function, so writing out all the permutations could be written as:

for (auto &sentence: sentences) {
    std::sort(sentence.begin(), sentence.end());

    do {
        std::cout << join(sentence, " ") << '\n';
    } while(std::next_permutation(sentence.begin(), sentence.end());
}


Object map in JavaScript I want to make a map object that key is object.

But, JavaScript only allows string as a hash key. (at least before ECMAScript6 comes?)

So, I tried to write auxiliary functions to emulate, hash-ish (but actually linear search).
Are there any suggestions on improvement?

var tabInfo = {};
var tabInfoKey = 0;

function getTabInfoItem(tab) {
  console.log("getTabInfoItem", tab);
  for(var key in tabInfo) {
    if(tabInfo[key].tab === tab) {
      return tabInfo[key].info;
    }
  }
}

function setTabInfoItem(tab, info) {
  console.log("setTabInfoItem", tab, info);
  for(var key in tabInfo) {
    if(tabInfo[key].tab === tab) {
      tabInfo[key] = {
        tab: tab,
        info: info
      };
      return;
    }
  }
  tabInfoKey++;
  tabInfo[tabInfoKey] = {
    tab: tab,
    info: info
  };
}

function deleteTabInfoItem(tab) {
  console.log("deleteInfoItem", tab);
  for(var key in tabInfo) {
    if(tabInfo[key].tab === tab) {
      delete tabInfo[key];
      return;
    }
  }
}

I can't see a good use for this, but nonetheless:

Since you treat tabInfo as a list, why not have it be an array, this way you don't need tabInfoKey and you can use push instead. Arrays are objects too.
Don't use console.log for production code
tab is a terrible name, go for either the Spartan o or object
info is an unfortunate name, perhaps value ?
tabInfo is also meh, perhaps objectMap ?
you should have a constructor for this!

Something like this incorporates my feedback:

function ObjectMap() {
  this.entries = [];
}

ObjectMap.prototype.get = function( object ) {
  for( var i = 0 , length = this.entries.length ; i < length ; i++ ){
    if( this.entries[i].object === object ){
      return this.entries[i].value;
    }
  }
}

ObjectMap.prototype.set = function( object, value ) {
  //If we can find it, update it
  for( var i = 0 , length = this.entries.length ; i < length ; i++ ){
    if( this.entries[i].object === object ){
      this.entries[i].value = value;
      return;
    }
  }
  //Otherwise, generate an entry
  this.entries.push( { object : object , value : value } );
}

ObjectMap.prototype.remove = function( object ) {
  for( var i = 0 , length = this.entries.length ; i < length ; i++ ){
    if( this.entries[i].object === object ){
      this.entries.splice( i , 1 );
      return;
    }
  }
}

You can then

o = new ObjectMap();
o.set( o , "123" );
o.get( o ); //Gives "123"
o.remove( o );
o.get( o ); //Gives nothing

Furthermore you should consider whether you want to allow function chaining, right now none of these functions return anything and it seems a shame.


Parsing US address with Clojure The parser below is not designed for every single US address.  I am parsing through a file where each line may or may not be an address.  I am more focused on speed rather than robustness.

state-abbreviation-lookup and street-suffix-lookup are booth used for consistency (addresses will always be "ST" instead of "STREET" or "STR")
find-last-occurence-index-of searches through a list of string and finds the last string that matches a key in a hash-map.  This is used with state-abbreviation-lookup and street-suffix-lookup to find where in the address the state and or street is.
split-string removes commas, capitalizes everything and then splits on whitespace.

Next in the code is some checks for invalid values.  I finally have to split the address into the appropriate parts: street, city, state, zipcode.

Overall, it feels like too much is going on, but I'm not sure how best to make it the most Clojure-like.

(def
 ^{:const true
   :source "https://www.usps.com/send/official-abbreviations.htm"}
  state-abbreviation-lookup
  (hash-map
    "AL" "AL"
    "ALABAMA" "AL"
    "AK" "AK"
    "ALASKA" "AK"
    ;... removed for brevity
    ))

(def
 ^{:const true
   :source "https://www.usps.com/send/official-abbreviations.htm"}
  street-suffix-lookup
  (hash-map
    ;... removed for brevity
    "STREET" "ST"
    "ST" "ST"
    "STR" "ST"
    "STRT" "ST"
    ;... removed for brevity
    ))

(defrecord UsAddress [street city state zipcode])

(letfn
  [(find-last-occurence-index-of [lookup-map coll]
    (last (keep-indexed #(when (contains? lookup-map %2) %1) coll)))
   (split-string [s]
    ((comp #(clojure.string/split % #"\s+")
                     clojure.string/upper-case
                     #(clojure.string/replace % #"," ""))
     s))]
(defn extract-us-address [s]
  (let [parts (split-string s)]
    (when (re-matches #"^\d{5}$" (last parts))
      (let [state-index (find-last-occurence-index-of state-abbreviation-lookup parts)
            street-index (find-last-occurence-index-of street-suffix-lookup parts)]
        (when (and state-index street-index)
          (UsAddress.
            (clojure.string/join " " (take (inc street-index) parts))
            (clojure.string/join " " (drop (inc street-index) (take state-index parts)))
            (state-abbreviation-lookup (nth parts state-index))
            (last parts))))))))

Tests:

(deftest extract-us-address-test
  (testing "extract-us-address"
    (testing "should determine if string is a US address"
      (are [i o] (= (extract-us-address i) o)
        "3526 HIGH ST SACRAMENTO CA 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 HIGH ST SACRAMENTO, CA 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 HIGH ST SACRAMENTO California 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 HIGH ST SACRAMENTO, California 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 high st sacramento ca 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 high st sacramento, ca 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 CALIFORNIA ST SACRAMENTO CA 95838"  (UsAddress. "3526 CALIFORNIA ST" "SACRAMENTO" "CA" "95838")
        "3526 CALIFORNIA ST SACRAMENTO, CA 95838"  (UsAddress. "3526 CALIFORNIA ST" "SACRAMENTO" "CA" "95838")
        "3526 AVENUE ST SACRAMENTO CA 95838"  (UsAddress. "3526 AVENUE ST" "SACRAMENTO" "CA" "95838")
        "3526 AVENUE ST SACRAMENTO, CA 95838"  (UsAddress. "3526 AVENUE ST" "SACRAMENTO" "CA" "95838")
        "California"  nil
        "CA"  nil
        ""  nil
        "SACRAMENTO"  nil
        "95838"  nil
        "3526 HIGH STREET"  nil
        "304 867 5309" nil))))

split-string can be simplified

You're defining a function that takes an argument s and applies the composite of 3 different clojure.string functions to s within the body of the function. You could simplify this in 2 ways:

(require '[clojure.string] :as s) -- now you can call all three functions in a much more concise way, e.g. s/split.
(comp fn1 fn2 fn3 s) is already a function, so you could actually define split-string as just that, without needing to repeat s as part of the function. See below:

(require '[clojure.string :as s])

(def split-string
  (comp #(s/split % #"\s+") s/upper-case #(s/replace % #"," "")))

This is just a matter of preference, but I would find it easier to read if you used a threading macro instead:

(defn split-string [s]
  (-> s (s/replace #"," "") s/upper-case (s/split #"\s+")))

defn should only be at the top level

In your code, you have the equivalent of this:

(letfn [(foo [x] (bar x))]
  (defn baz [y] (foo y)))

(To be more specific, I'm talking about (letfn [(find-last-occurrence-index-of ...) (split-string [s] ...)] (defn extract-us address [s] ...)))

Having a defn inside of a let form is un-idiomatic, and can be a little bit confusing at first glance. The general rule is to only have def forms (including defn, defmacro, etc.) at the top level of your code. You can fix this by simply flipping it so that the letfn part is inside the defn part, like this:

(defn baz [y]
  (letfn [(foo [x] (bar x))]
    (foo y)))

This way, it is more clear that the functions being "let'd" are internal to the function.

Combine when/let bindings when possible

The main thing I notice, looking at your extract-us-address function, is that there are multiple let and when statements. Sometimes this is unavoidable, but often you can tidy up your code by combining multiple bindings into a single let form. You could do something like the code below. Notice also that I've included your "letfns" find-last-occurrence-index-of and split-string as anonymous functions within the let bindings.

(defn extract-us-address [s]
  (let [find-last-occurrence-index-of
        (fn [lookup-map coll]
          (last (keep-indexed #(when (contains? lookup-map %2) %1) coll)))

        split-string
        (fn [s]
          (-> s (s/replace #"," "") s/upper-case (s/split #"\s+")))

        parts (split-string s)]
    ...

Use helper functions

The other thing I notice is that you have one fairly complex function, where you could have one "main" function (extract-us-address) which relies on a handful of seperate "helper" functions. Doing it that way generally makes your code easier to read. Here's an idea of how you could refactor your code into several smaller functions:

; (to make it clearer which functions are helper functions, mark
; them as private functions by using defn- instead of defn)

(defn- find-last-occurrence-index-of [lookup-map coll]
  (last (keep-indexed #(when (contains? lookup-map %2) %1) coll)))

; You could rename split-string to parts, then refer to (parts s),
; thereby avoiding needing to bind (split-string s) to parts in a
; let binding. I think this more clearly describes what the function
; is doing, as well.
(defn- parts [s]
  (-> s (s/replace #"," "") s/upper-case (s/split #"\s+")))

(defn- zip-code [s]
  (re-matches #"^\d{5}$" (last (parts s))))

(defn- street-index [s]
  (find-last-occurrence-index-of street-suffix-lookup (parts s)))

(defn- state-index [s]
  (find-last-occurrence-index-of state-abbreviation-lookup (parts s)))

(defn extract-us-address [s]
  ; this let binding is here to help performance -- we only want to evaluate
  ; each of these once, and bind it to a symbol
  (let [zip-code (zip-code s)
        street-index (street-index s)
        state-index (state-index s)]
    (when (and zip-code street-index state-index)
      (UsAddress.
        (clojure.string/join " " (take (inc street-index) (parts s)))
        (clojure.string/join " " (drop (inc street-index) (take state-index (parts s))))
        (state-abbreviation-lookup (nth (parts s) state-index))
        zip-code))))

Is there a better way to do this?

I noticed that there are a couple of potential flaws with your algorithm:

It relies on the fact(/assumption?) that there are no street suffixes that overlap with state abbreviations. This might be OK (I can't think of any examples that would break this), but it seems like a potential problem. This is a really contrived idea, but what if the street suffix "Ca" for "calle" catches on? Your code wouldn't know how to tell apart CAlle from CAlifornia.
It doesn't return nil if the state is missing from where it's supposed to be, but present somewhere else, like in the street address. For example, try running your program on an address like "1000 NC HWY 70, RALEIGH, 27602." Assuming you have "HWY" listed as a suffix, you would expect nil (because the state is missing), but you would get #user.UsAddress{:street "1000 NC HWY", :city "", :state "NC", :zipcode "27602"}. The problem is that you're working with indices and the state-index has the potential to fall within the street address rather than after the city where you would expect it. This is only a problem if the state is missing from where it belongs, but it's still a problem.

I can think of two potential approaches that might be better:

A. Iterate through the address "parts" in reverse -- look at the last thing and see if it qualifies as a zip code -- if so, move on and look at the next-to-last thing -- does it qualify as a state or state abbreviation? if so, hang onto the state abbrevation and move on. Then you can separate the street address from the city by looking for the last thing that qualifies as a street suffix.

B. Use a parsing library such as Instaparse. This would be my preferred approach. I've found that using a parsing library tends to greatly simplify things, as the library does all of the hard work for you. All you have to do is specify a grammar and wrap it in a parser, then do (your-parser address-string) and it will return a structure (called a "parse tree") something like this:

[:address
  [:street-address "3526 HIGH" [:suffix "ST"]]
  [:city "SACRAMENTO"]
  [:state "CA"]
  [:zip "95838"]]

If you're new to defining a PEG grammar, there is a small learning curve, but it's actually surprisingly simple once you get the hang of it. Your grammar would look something like this:

address        = street-address <ows> city <ows> state <ows> zip
street-address = word+ suffix
city           = word+
word           = !suffix \w+ <ows>
suffix         = "ST" | "STREET" | "DR" | "DRIVE" (* etc. *)
state          = "AK" | "AL" | (* etc. *)
zip            = #"\d{5}"
ows            = #"[\s,]*"   (* optional whitespace / commas *)

(Note: I haven't tested the above, so it may or may not work properly.)

From there, it's easy to transform your parse tree into whatever form you'd like to represent each address. Personally I find this method easier, and it definitely makes your code look a lot cleaner and simpler.


Optimise compare and match method using scripting.dictionary in VBA In my previous post I was looking for a better solution to write a single column of a 2D array into a worksheet besides looping between code and worksheet and finally managed to achieve that.

On deploying my code, I found that the double loop to compare two arrays was inefficient when it came to comparing arrays of 5,000 or more and so I turned to the scripting.dictionary, for which I found the easiest instructions to follow here.

Here is an example that I have tested with arrays of 80,000 rows, returning results in seconds, but I am wondering if there might be some code I could cut or write better:

Option Explicit
Option Base 1

Public Sub arrayMatch()

    Dim firstArray As Variant
    With ThisWorkbook.Worksheets(1)
        firstArray = .Range("A1").CurrentRegion
    End With

    Dim secondArray As Variant
    With ThisWorkbook.Worksheets(2)
        secondArray = .Range("A1").CurrentRegion
    End With

    Dim i As Long
    Dim dictKeyForLookup As String
    Dim dictValueToReturn As String

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare

    For i = LBound(firstArray, 1) To UBound(firstArray, 1)
        dictKeyForLookup = firstArray(i, 4)
        dictValueToReturn = firstArray(i, 3)
        If Not dict.Exists(dictKeyForLookup) Then
            dict.Add Key:=dictKeyForLookup, Item:=dictValueToReturn
        End If
    Next i

    Dim arrayToPaste As Variant
    ReDim arrayToPaste(UBound(secondArray, 1), 1)
    For i = LBound(secondArray, 1) To UBound(secondArray, 1)
        If dict.Exists(secondArray(i, 1)) Then
            arrayToPaste(i, 1) = dict.Item(secondArray(i, 1))
        End If
    Next i

    With ThisWorkbook.Worksheets(1)
        .Range(.Cells(1, 4), .Cells(UBound(secondArray, 1), 4)).Value = arrayToPaste
    End With

End Sub

This implementation actually looks really solid. A couple stylistic and micro-performance issues I would personally address:

Array base: I'd remove Option Base 1 and explicitly declare your array dimensions. The problem with using Option Base 1 is that it is a module level option, and it "taints" all of the code in the module with a non-default setting.  I consider it similar to using #define foo bar in C - it alters the semantics of your code. There's not even really a reason to use it in this case because you are always using the LBound to initialize your loop counters anyway. Changing this line...

ReDim arrayToPaste(UBound(secondArray, 1), 1)

...to...

ReDim arrayToPaste(1 To UBound(secondArray, 1), 1 To 1)

...makes it immediately obvious that the array is 1 based without having to scroll to the top of the module or remember that the base is non-default.

Variable naming: firstArray and secondArray are about as meaningful as a1 and a2. Something like workingArray and comparisonArray would make it a little more obvious what your code is dealing with.

Worksheet references: You are currently using magic numbers to locate the worksheets that you're operating on, and the indexes are based on the ordinal of where the sheet is in the collection.  If this is intended to operate on two fixed worksheets, use their class names instead.  This has two benefits: first, you aren't using 2 procedure calls (Worksheets and the implicit Items) to get a reference that you already know and have access to .  Second, your Sub won't break the first time you add a new worksheet. For example, use With Sheet1 (or whatever it is) instead of With ThisWorkbook.Worksheets(1).

Binding:  There is no reason to late bind to the scripting runtime.  The interface hasn't changed in this century, and is unlikely to. This is a pretty good performance hit in exchange for absolutely zero upside. Add a reference to Microsoft Scripting Runtime and declare it explicitly:

Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary

Use With appropriately: You're doing this for your worksheets, but it doesn't actually do anything for you:

With ThisWorkbook.Worksheets(1)
    firstArray = .Range("A1").CurrentRegion
End With

You use it exactly once inside the block, so this is exactly the same thing as:

firstArray = ThisWorkbook.Worksheets(1).Range("A1").CurrentRegion
'...or even better (see above)...
firstArray = Sheet1.Range("A1").CurrentRegion

What With does is hold an object reference to avoid having to dereference it multiple times.  If you only use it once, it's reduced to 2 extra lines of code and 1 extra indentation level.

That said, the place where it is appropriate is with your Dictionary, and it isn't used there. This is much better:

With New Scripting.Dictionary   'You don't even need the variable.
    .CompareMode = vbTextCompare

    For i = LBound(firstArray, 1) To UBound(firstArray, 1)
        dictKeyForLookup = firstArray(i, 4)
        dictValueToReturn = firstArray(i, 3)
        If Not .Exists(dictKeyForLookup) Then
            .Add Key:=dictKeyForLookup, Item:=dictValueToReturn
        End If
    Next i

    Dim arrayToPaste As Variant
    ReDim arrayToPaste(1 To UBound(secondArray, 1), 1 To 1)
    For i = LBound(secondArray, 1) To UBound(secondArray, 1)
        If .Exists(secondArray(i, 1)) Then
            arrayToPaste(i, 1) = .Item(secondArray(i, 1))
        End If
    Next i
End With    'Dictionary goes out of scope here.

Named arguments: There is no reason to use them here:

dict.Add Key:=dictKeyForLookup, Item:=dictValueToReturn

If you are early bound, the name information is available via both Intellisense and the object browser.  If you are late bound, it actually adds more overhead for the runtime to resolve them. Just use the ordinal argument positions:

dict.Add dictKeyForLookup, dictValueToReturn

They're also a potential bug source because they are resolved at runtime for late bound objects (which is the same reason you take a performance hit).  That means that if you have a typo in the name (i.e. Keey:=foo), it won't be caught by the compiler.  It is also dependant on how the typelib is defined for the class.  For example it's possible for some late bound objects to introduce errors by specifying the same variable name multiple times.  Excel seems to be prone to this type of error:

Debug.Print WorksheetFunction.Sum(Arg1:=1, Arg1:=42) 'Prints 1


Expanding up or down This is a jQuery function that controls a
 to expand up or expand down. I am trying to simplify and optimize these lines of codes.

Scenerio

By default, it does not have any classes in
.

When I clicked on
, it adds .expand-up into this
 if there .expand-up class. When I clicked on
 it should remove .expand-up from
 and only remove if there is .expand-down.

$(document).ready(function() {
  $('.title-wrapper').click(function() {
    $(this).parent().toggleClass('active').delay('1500').promise().done(function() {
      var filterSearch = $(this).children('.title-wrapper');
      // Check if have expand-up classes
      if (filterSearch.hasClass('expand-up')) {
        filterSearch.removeClass('expand-up');
        filterSearch.addClass('expand-down');
      } else {
        // Remove expand down if the class is existed
        if (filterSearch.hasClass('expand-down')) {
          filterSearch.removeClass('expand-down');
        }
        filterSearch.addClass('expand-up');
      }
    });
  });
});
body {
  font-size: 62.5%;
  font-family: 'Roboto', sans-serif;
  color: #FFF;
}
.filter-search {
  background-color: #a78464;
}
.filter-search .wrapper {
  width: 100%;
  text-align: center;
  height: 10em;
  transition: height linear 1s;
}
.filter-search .wrapper .title-wrapper {
  display: inline-block;
}
.filter-search .wrapper .title-wrapper h2 {
  font-size: 3em;
  margin-bottom: 0;
}
.filter-search .wrapper .title-wrapper span {
  font-size: 1.4em;
  display: block;
  text-transform: uppercase;
  margin-bottom: 2em;
}
.filter-search .wrapper.active {
  height: 15em;
  transition: height linear 1s;
}
.filter-search .expand-up {
  -webkit-animation: moveUp ease-in 1;
  animation: moveUp ease-in 1;
  animation-fill-mode: forwards;
  animation-duration: .5s;
}
.filter-search .expand-down,
.filter-search .expand-up {
  -webkit-animation-fill-mode: forwards;
  -webkit-animation-duration: .5s;
}
.filter-search .expand-down {
  -webkit-animation: moveDown ease-out 1;
  animation: moveDown ease-out 1;
  animation-fill-mode: forwards;
  animation-duration: .5s;
}
@-webkit-keyframes moveUp {
  0% {
    margin-top: 0;
  }
  to {
    margin-top: -1em;
  }
  ;
}
@keyframes moveUp {
  0% {
    margin-top: 0;
  }
  to {
    margin-top: -1em;
  }
  ;
}
@-webkit-keyframes moveDown {
  0% {
    margin-top: -1em;
  }
  to {
    margin-top: 0;
  }
  ;
}
@keyframes moveDown {
  0% {
    margin-top: -1em;
  }
  to {
    margin-top: 0;
  }
  ;
}
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' type='text/css'>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    search

Filter Search

      Click to expand

As there is only two states, up and down, we can leave out .expand-up and let it be the default state. I refactored the css and js code to just add and remove the expand-down class, for the .css file,

body {
    font-size: 62.5%;
    font-family: 'Roboto', sans-serif;
    color: #FFF;
}
.filter-search {
    background-color: #a78464;
}
.filter-search .wrapper {
    width: 100%;
    text-align: center;
    height: 10em;
    transition: height linear 1s;
}
.filter-search .wrapper .title-wrapper {
    display: inline-block;
    animation-fill-mode: forwards;
    animation-duration: .5s;
    -webkit-animation-fill-mode: forwards;
    -webkit-animation-duration: .5s;
}
.filter-search .wrapper .title-wrapper.expand-down {
    -webkit-animation: moveDown ease-out 1;
    animation: moveDown ease-out 1;
}
.filter-search .wrapper .title-wrapper h2 {
    font-size: 3em;
    margin-bottom: 0;
}
.filter-search .wrapper .title-wrapper span {
    font-size: 1.4em;
    display: block;
    text-transform: uppercase;
    margin-bottom: 2em;
}
.filter-search .wrapper.active {
    height: 15em;
    transition: height linear 1s;
}
@-webkit-keyframes moveUp {
    0% {
        margin-top: 0;
    }
    to {
        margin-top: -1em;
    }
}
@keyframes moveUp {
    0% {
        margin-top: 0;
    }
    to {
        margin-top: -1em;
    }
}
@-webkit-keyframes moveDown {
    0% {
        margin-top: -1em;
    }
    to {
        margin-top: 0;
    }
}
@keyframes moveDown {
    0% {
        margin-top: -1em;
    }
    to {
        margin-top: 0;
    }
}

and for the .js file I changed click() to on(), in case the element will be added dynamically, click() would not work. Also assigning variable filterSearch earlier in the function, there should be no need to find the children with each click,

$(document).ready(function() {
    $('#filter-search').on('click', '.title-wrapper', function() {
        var filterSearch = $(this);

        filterSearch.parent().toggleClass('active').delay('1500').promise().done(function() {
            if (filterSearch.hasClass('expand-down')) {
                filterSearch.removeClass('expand-down');
            } else {
                filterSearch.addClass('expand-down');
            }
        });
    });
});


Alternating sort order within a sorted group When sorting by multiple keys, I need the second key to alternate between standard and reverse sorting.  This is to minimize the change in the second key.  For example, if I have a list of dictionaries, I want the first sort (group key) to be sorted and then the second sort (sort key) to alternate.  This should produce a sort like this:

[{'group': 'a', 'sort': 1},
 {'group': 'a', 'sort': 2},
 {'group': 'a', 'sort': 2},
 {'group': 'b', 'sort': 2},
 {'group': 'b', 'sort': 1},
 {'group': 'b', 'sort': 1},
 {'group': 'c', 'sort': 1},
 {'group': 'c', 'sort': 1},
 {'group': 'c', 'sort': 2}]

That limits the change in the field called "sort" as it alternates each time as the "group" changes.

I have looked around and did not see a standard way to accomplish this without rolling my own.  I think the code is fairly straight forward but curious if I might be missing something or an easier/faster way.

Any comments would be appreciated.

#!/usr/bin/env python3
""" Misc sort routines """
from operator import itemgetter
import pprint

def alternate_sort(data, group_key, sort_key,
        group_reverse=False, sort_reverse=False):
    """ Sort data within groups while alternating asc/desc on sort key. """
    partitions = []     # Tuples of start/end indexes per group
    last_key = None     # Remember when groups change
    group_start = 0     # Remember start index of group
    final_sort = []     # The final sorted listing

    # Make sure the data is sorted by group
    data = sorted(data, key=itemgetter(group_key), reverse=group_reverse)

    # Gather the group partitions
    for i, g in enumerate(data):

        # When the group changes
        if last_key != g[group_key]:

            # End the previous group partition if there is one
            if i > 0:
                partitions.append((group_start, i))

            # Start a new group partition
            group_start = i
            last_key = g[group_key]

    # Close the last group partition
    partitions.append((group_start, len(data)))

    # Go through the partitions, alternate the sort each time using sort key.
    for i, p in enumerate(partitions):
        part = data[p[0]: p[1]]
        if i % 2 == 0:
            final_sort += sorted(
                    part, key=itemgetter(sort_key), reverse=sort_reverse)
        else:
            final_sort += sorted(
                    part, key=itemgetter(sort_key), reverse=not sort_reverse)

    return final_sort

if __name__ == "__main__":
    unsorted_data = [
            {"group": "a", "sort" : 1},
            {"group": "a", "sort" : 2},
            {"group": "b", "sort" : 2},
            {"group": "b", "sort" : 1},
            {"group": "c", "sort" : 1},
            {"group": "a", "sort" : 2},
            {"group": "c", "sort" : 2},
            {"group": "b", "sort" : 1},
            {"group": "c", "sort" : 1}
    ]

    sorted_data = alternate_sort(unsorted_data, "group", "sort",
            group_reverse=True, sort_reverse=True)
    pprint.pprint(sorted_data)

    sorted_data = alternate_sort(unsorted_data, "group", "sort")
    pprint.pprint(sorted_data)

1. Quick review

This function returns a new list, like the built-in sorted. It does not update data in place, like the sort method on lists. So a name containing "sorted" would give a better hint at its behaviour.

The docstring is not detailed enough to explain how to call the function. What arguments do I pass for group_key and sort_key? What happens if I pass True for group_reverse or sort_reverse?

The function calls operator.itemgetter to make key functions. But this means that the function will only work when the keys are dictionary or sequence values. If you want to use object properties as keys, you're out of luck (that would need operator.attrgetter). And if you want to compute something more complicated by passing in your own function, that's no good either.
I would recommend accepting any function for group_key and sort_key and letting the caller use operator.itemgetter if that's what they need. This makes the function behave more like the built-in sorted and similar functions that take key arguments.

Extend a list using the extend method, which updates the list in-place. If you use augmented assignment +=, Python may have to create a new list and copy all the elements across.

2. Rewrite
The algorithm you've chosen is:

Sort data by the group key.

Iterate over the data, collecting the groups.

Iterate over the groups, sorting each one.

Steps 2 and 3 can be combined into one iteration using itertools.groupby. The alternation between ascending and descending can be implemented using itertools.cycle. These two iterations can be combined using zip, like this:
from itertools import cycle, groupby

def sorted_alternately(data, group_key, sort_key,
                       group_reverse=False, sort_reverse=False):
    """Sort data on group_key (in reverse order if group_reverse=True) but
    within each group of items, alternately sort in ascending and
    descending order on sort_key (in descending and ascending order in
    sort_reverse=True).

    >>> from itertools import product
    >>> from operator import itemgetter as get
    >>> sorted_alternately(product(range(3), repeat=2), get(0), get(1))
    [(0, 0), (0, 1), (0, 2), (1, 2), (1, 1), (1, 0), (2, 0), (2, 1), (2, 2)]

    """
    data = sorted(data, key=group_key, reverse=group_reverse)
    groups = groupby(data, key=group_key)
    reverses = cycle((sort_reverse, not sort_reverse))
    result = []
    for (_, group), reverse in zip(groups, reverses):
        result.extend(sorted(group, key=sort_key, reverse=reverse))
    return result