Order columns in R by substring I want to order columns of a dataframe using a substring of the column name only. Suppose my columns are named

df <- data.frame("x_b"=5,
                 "y_b"=2,
                 "x_a"=6,
                 "y_a"=3,
                 "y_c"=1,
                 "x_c"=4)

and I want to order them using a first-order and a second-order key. The first-order key would be first_order <- c("y", "x") and the second-order key be like second_order <- c("c", "b", "a").

I try kind of ugly code where I build my desired order in a loop:

order <- list()
for (first_key in first_order){
  for (second_key in second_order){
    order <- cbind(order, paste(first_key, second_key, sep="_"))
  }
}

The result is as I want:

> df[as.character(order)]
  y_c y_b y_a x_c x_b x_a
1   1   2   3   4   5   6

But I wouldn't say that my code is very easy, nor quick. Do you have a better suggestion?

Memory Growth Issues:

When working with data in R avoid using cbind and rbind as much as possible if there are loops involved. R Inferno dedicates a chapter to the memory growth issue.

Strings are king:

In this case, you only care about column order. The order of columns within a data.frame can be easily adjusted by supplying a vector containing all of the column names in your preferred order to the data.frame object. As a result, the process is not very computationally expensive if you operate solely with column names.

With this being said, we can simplify the process greatly using:

# Starting Data Frame
df <- data.frame("x_b"=5,
                 "y_b"=2,
                 "x_a"=6,
                 "y_a"=3,
                 "y_c"=1,
                 "x_c"=4)

m = names(df) # Extract column names.

r = strsplit(m,"_") # Split the column names based on the _

# Create a data.frame with two columns X1 being x or y
# X2 being a, b, or c
q = data.frame(matrix(unlist(r),nrow=length(m),byrow=T))

# Order q according to spec
q = q[order(q$X1,q$X2, decreasing = T),]

# Reformat names
m = paste0(q$X1,"_",q$X2)

# Rearrange columns
df = df[,m]

The order of q is:

 X1 X2
  y  c
  y  b
  y  a
  x  c
  x  b
  x  a

Thus, the columns of df look like:

 y_c y_b y_a x_c x_b x_a
   1   2   3   4   5   6

Edit
The responder has clarified that they would like the order to be slightly different in the last column e.g. (c,a,b) instead of (c,b,a). There are two ways to go about this: factor() or using match(). I'll opted to only present factor() in detail as the later is more convoluted.

Factors

In this case, you should turn both columns into factors and then order on the levels without the descend option. Using factors for both columns makes the code cleaner and more logical than before since the choice of levels is able to be done in their given order e.g. y,x and c,a,b.

If you were to modify the previous example that used descend, there would be an issue in the order of the X2 column. Most notably, the column would be sorted as 'b','a','c' instead of 'c','a','b'. The reason for this is due to levels being tied to numeric values, like 1,2,3, and the prior example used descend to sort both options. Thus, if we continued to use descend, we would of been sorting X2 on 'c' => 1, 'a' => 2, 'b' => 3. The fix to this is simply reversing the order of the levels - b, a, c - which may make everything a bit more confusing later on.

Thus, we have:

# Select sort order for X1: y, x
x1.values = c("y","x")
# Select sort order for X2: c, a, b
x2.values = c("c","a","b")

# Place call to factor for both columns
q = q[order(factor(q$X1, levels = x1.values), factor(q$X2, levels = alpha)),]

Giving q as:

 X1 X2
  y  c
  y  a
  y  b
  x  c
  x  a
  x  b

So that the columns of df are now:

 y_c y_a y_b x_c x_a x_b
   1   3   2   4   6   5


Verify a subnet mask for validity in Python I've written a small Python function to check whether a string is a valid IPv4 subnet mask.

It works but maybe it's too convoluted and terse? Or maybe it could be improved / optimised / rewritten in a cleverer way than just to check 1's in a string?..

IsIPv4Address is another function of mine (EDIT 1: added it into the question).
I specifically don't want to use any libraries / external functions as this is rather a study in Python :)

def IsIPv4Address(ipAdd):
    """Validate an IPv4 address"""
    octets = ipAdd.split(".")
    if len(octets) != 4:
        return False
    for octet in octets:
        if not IsInteger(octet):
            return False
        if int(octet) > 255 or int(octet) < 0:
            return False

    return True

def IsIPv4Mask(ipMask):
    """Validate an IPv4 subnet mask"""

    # Each mask looks like an IPv4 address and must pass the checks
    if not IsIPv4Address(ipMask):
        return False

    ipMaskBinary = ""
    ipMaskBinary = ipMaskBinary.join([bin(int(oct))[2:] for oct in ipMask.split(".")])

    isBitZero = ipMask[0] == "0"
    for bit in ipMaskBinary[1:]:
        if bit == "1" and isBitZero:
                return False

        if bit == "0":
            isBitZero = True

    return True

As recommended in PEP 8, the official style guide, function names should be lower_case_with_underscores unless you have a good reason for making an exception.

Functions like this are perfect places to write doctests, to explain how the function should behave while providing unit tests at the same time.

The IsIPv4Address() function is easy to implement.  I would take advantage of the all() function with a generator expression and a double-ended inequality.

def is_ipv4_address(dotquad):
    """
    Validate an IPv4 address in dotted-quad notation.

    >>> is_ipv4_address("1.2.3.4")
    True
    >>> is_ipv4_address("127.0.0.1/8")
    False
    >>> is_ipv4_address("1.2.3.4.5")
    False
    >>> is_ipv4_address("1.2.3")
    False
    >>> is_ipv4_address("1.2.3.256")
    False
    >>> is_ipv4_address("1.2.3.-4")
    False
    >>> is_ipv4_address("fe80::")
    False
    """
    octets = dotquad.split(".")
    return len(octets) == 4 and \
           all(o.isdigit() and 0 <= int(o) < 256 for o in octets)

The netmask verifier is trickier to write well.  You have chosen to use bin() to stringify the 32-bit number.  I'd avoid using strings for something that can be done arithmetically, since string manipulation is relatively inefficient.

Furthermore, I'd suggest that instead of writing just a validation function, you may as well write a function to tell you the length of the netmask, since it's nearly the same amount of work, but you can get more useful information that way.

def ipv4_mask_len(dotquad):
    """
    Finds the number of bits set in the netmask.

    >>> ipv4_mask_len("255.255.255.0")
    24
    >>> ipv4_mask_len("0.0.0.0")
    0
    >>> ipv4_mask_len("255.255.255.255")
    32
    >>> ipv4_mask_len("127.0.0.0")
    Traceback (most recent call last):
      ...
    ValueError: Invalid netmask: 127.0.0.0
    """
    if not is_ipv4_address(dotquad):
        raise ValueError("Invalid netmask: {0}".format(dotquad))
    a, b, c, d = (int(octet) for octet in dotquad.split("."))
    mask = a << 24 | b << 16 | c << 8 | d

    if mask == 0:
        return 0

    # Count the number of consecutive 0 bits at the right.
    # https://wiki.python.org/moin/BitManipulation#lowestSet.28.29
    m = mask & -mask
    right0bits = -1
    while m:
        m >>= 1
        right0bits += 1

    # Verify that all the bits to the left are 1's
    if mask | ((1 << right0bits) - 1) != 0xffffffff:
        raise ValueError("Invalid netmask: {0}".format(dotquad))
    return 32 - right0bits


How can I improve the following stored procedure? I have created the following stored procedure which duplicates a record in a table and also all its related records in other tables however since I am a newbie to SQL I would appreciate it if someone could review my code and show me how it could be improved and whether there are any hazards.

   USE [Neptune2Dev]
    GO
    /****** Object:  StoredProcedure [dbo].[DuplicateItemInBatch]    Script Date: 03/04/2013 17:55:47 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [dbo].[DuplicateItemInBatch] @batchID AS INT , @numInBatch AS INT

    AS

    declare @itemIdToBeDuplicated as int
    declare @duplicatedItemID as int
    declare @URI as varchar(max)
    declare @itemOrganisationID as int
    declare @duplicateItemOrganisationID as int

    BEGIN TRY
        BEGIN TRANSACTION;

           --increment all proceeding numbInbatch fileds to accomodiate the new item being duplicated
           UPDATE items  SET numinbatch = numinbatch + 1
        WHERE numinbatch > @numInBatch AND BatchID = @batchID

           select @itemIdToBeDuplicated = ID from items i where i.BatchID = @batchID and i.NumInBatch = @numInBatch
           select @URI = URI from ItemMedia where ID = @itemIdToBeDuplicated

           --duplicate the item and insert it into the table
           insert into items
           select
           i.SupplierID, i.Title, i.PubDate, i.Body, i.StatusID,
           i.IsRelevant, i.ClipDuration, i.ResearchDuration,
           i.Comments, i.ItemTypeID, i.PageNumber, i.BatchID,
           i.NumInBatch + 1, i.OverrideDate, i.MediaChannelID,
           i.Size, i.PreviouslyCompleted
           from items i where i.ID = @itemIdToBeDuplicated
           select @duplicatedItemID =  SCOPE_IDENTITY();

           select @itemOrganisationID = ID from ItemOrganisations where ItemID = @itemIdToBeDuplicated
           insert into ItemOrganisations
           select @duplicatedItemID, OrganisationID, comment, rating from ItemOrganisations where ID = @itemOrganisationID
           select @duplicateItemOrganisationID = SCOPE_IDENTITY();

           insert into ItemOrganisationMessages
           select @duplicateItemOrganisationID, MessageID from ItemOrganisationMessages where ItemOrganisationID = @itemOrganisationID

           insert into ItemOrganisationIssues
           select @duplicateItemOrganisationID, IssueID from ItemOrganisationIssues where ItemOrganisationID = @itemOrganisationID

           insert into ItemByLines
           select @duplicatedItemID, ByLineID from ItemByLines where ItemID = @itemIdToBeDuplicated

           insert into ItemDocumentLink
           select ItemDocumentID, @duplicatedItemID from ItemDocumentLink where ItemID = @itemIdToBeDuplicated

           insert into ProfileResults
           select ProfileId, @duplicatedItemID from ProfileResults where ItemID = @itemIdToBeDuplicated

           insert into ItemNotes
           select  @duplicatedItemID,Quote,Theme,Rating,Comment,IsBad from ItemNotes where ItemID = @itemIdToBeDuplicated

           IF @URI <> null
           BEGIN
                  insert into ItemMedia values (@duplicatedItemID, @URI)
           END
           ELSE
        PRINT  N'No Article to be duplicated '

        COMMIT TRANSACTION;
        END TRY
        BEGIN CATCH
    BEGIN
        PRINT
            ERROR_NUMBER() +' ' + ERROR_MESSAGE()
        ROLLBACK TRANSACTION;
    END;
END CATCH;

Here are some comments in no particular order:

Your CATCH block - including comments - is a copy and paste from the documentation. While it's always good to read the documentation, please remember that the examples are there to illustrate specific features and you shouldn't assume that they're usable as-is in production code
If an error occurs in the TRY block, your CATCH block commits if possible anyway, is this what you intended? XACT_STATE() tells you that the transaction can be committed, not that it should be. See this SO question for more information.
Your CATCH block doesn't examine or log the error message (using ERROR_NUMBER() and similar functions), so if an error does occur you will have no idea what it was
Always list all column names in an INSERT; this gives you some security if the table structure changes
You cannot compare NULL values with the standard comparison operators, you need to write IF @URI IS NULL instead
Always use schema names to reference objects in code
Using BEGIN and END to wrap the entire stored procedure body is not required but usually good practice, otherwise it's easy to forget where the procedure ends and accidentally add some code that you didn't mean to
Most procedures should SET NOCOUNT ON at the beginning

And please always mention your SQL Server version (2005, 2008, 2008R2, 2012) and edition (Standard, Enterprise, Express) because that determines which language features are available.


Rearranging an array such that positive and negative elements are at alternate positions We are given an array in which we have equal number of positive and negative elements.

We have to rearrange this array such that all positive and negative elements are at alternate positions and also, respective order should be maintained. N i.e. the size of array can be: 1<=N<=\$10^6\$ .  No additional data structure can be used

INPUT:

1 2 3 -1 -2 -3

OUTPUT:

1 -1 2 -2 3 -3

My code was accepted but it exceeded the time limit for a case. How can I make my code more efficient by reducing its time complexity?

My code:

import java.util.*;
 class A{
 public static void main(String args[])
 {
     Scanner s=new Scanner(System.in);
     int n=s.nextInt();
     int a[]=new int[n];
     for(int i=0;i<n;i++)
         a[i]=s.nextInt();
     rearrange(a);
     for(int i=0;i<n;i++)
         System.out.print(a[i]+" ");
 }

public static void rotateright(int a[],int l,int r)
{
    int temp=a[r];
    for(int i=r;i>l;i--)
    {
        a[i]=a[i-1];
    }
    a[l]=temp;
}
public static void rearrange(int a[])
{
    int n=a.length;
    int i=0,j=0;
    while(i<n)
    {
        if(i%2==0)    //even index should have positive element
        {
            if(a[i]>0)     //already positive
                i++;
            else               //for negative
            {
                j=i+1;
                while(j<n)      //finding next positive
                {
                    if(a[j]>0)
                        break;
                    j++;
                }
                rotateright(a,i,j);    //making even index positive
                i++;
            }
        }
        else            //odd index should have negative element
        {
            if(a[i]<0)   //already negative
                i++;
            else           //for positive
            {
                j=i+1;
                while(j<n)          //finding next negative
                {
                    if(a[j]<0)
                        break;
                    j++;
                }
                rotateright(a,i,j);     //making odd index negative
                i++;
            }
        }
    }
}
}

Worst case

Picturing the worst case helps understanding the problem.
The test failing probably uses an array of size n containing n/2 positive numbers followed by n/2 negative numbers (or vice-versa).

Current implementation

Note that when you find an element out of place, you are iterating twice through the indices, until you find the correct element: one time two found its position, another to move all elements in between.
You can combine both operations into one. Still this algorithm resembles the insertion sort. It will be quadratic in the worst case that I described (more specifically, (n/2)^2).

Using extra space

One efficient way to solve this is to build the correct array from the beginning. This requires O(1) of extra space.
You create 3 arrays: one to buffer positive numbers, other to buffer negative numbers, and a 3rd one with the final result.

When reading from stdin:

Place the number in the 3rd array if it matches the position, otherwise store it in the appropriate array;
If the number matches, try to use numbers stored in the positive/negative numbers arrays to keep filing the 3rd array (using FIFO).

What we are doing is essentially merging 3 sorted arrays: stdin, the array with positive numbers and the array with negative numbers.

This should run linearly, requiring 2 writes per number out of place.


Finding if a given number is in a given range based on a flag Question Description:

Given a number n, return True if n is in the range 1..10, inclusive. Unless outsideMode is True, in which case return True if the number is less or equal to 1, or greater or equal to 10.
in1to10(5, False) → **True**

in1to10(11, False) → **False**

in1to10(11, True) → **True**

The link to the problem is here.
Below is my first attempt.  Please feel free to review it based on best practices, style and any other efficient solution.
def in1to10(n, outside_mode):
    if(n>1 and n<10):
        return not outside_mode
    else:
        return outside_mode or n is 10 or n is 1

The logic is confusing. A direct translation of the problem specification is possible, and clearer.

Let's deal with the first half of the problem:

  Given a number \$n\$, return True if \$n\$ is in the range \$1 ..10\$, inclusive.

Then it's natural to write:

def in1to10(n):
    return 1 <= n <= 10

Now we can deal with the second half:

def in1to10(n, outside_mode):
    if outside_mode:
        return n <= 1 or n >= 10
    return 1 <= n <= 10


Transforming class names to method names I have a lot of filter classes which are named after the method names they filter by.

For example:

OrderByBestValueFilter corresponds to #best_value
OrderByPriceFilter corresponds to #price

and so on...

Since I'm doing a lot of these transformations, and the point of this set us is to make filters easy to add or remove, I have a base class where most of the work is done.  To extract the method name from the calling class, I have this method:

def criteria
  class_name = self.class.name.split('::').last
  class_name.sub!(/Order/, '')
  class_name.sub!(/By/, '')
  class_name.sub!(/Filter/, '')
  class_name.scan(/[A-Z][^A-Z]*/)
  class_name.map(&:downcase).join('_')
end

which I pared down to the following:

def criteria
  class_name = self.class.name.split('::').last
  name = class_name.scan(/[A-Z][^A-Z]*/) - %w[Order By Filter]
  name.map(&:downcase).join('_')
end

but this is still gross.  Any suggestions?

If this is Rails, you've got the #underscore mixin from ActiveSupport at your disposal, which'll at least take care of the last bit.

As for the naming in general, I'm wondering what purpose the full names serve, if so much of them is just dropped. I'm not saying it's wrong, I'm just wondering. Especially as it seems like the transformations are one-way.

What I mean is that the class OrderByBestValueFilter becomes just best_value, effectively "throwing away" a lot of information in the name. If said information can be thrown away, was it even necessary in the first place?

As for the transformations being one-way, it's just another indication that the class name → criterion* string rule is a little informal. The string best_value could come from a class called BestValue, ByBestValue, BestValueFilter, or some other combination. Yet I'd imagine an OrderByXyzFilter is semantically different than a ByXyzFilter: The former takes a collection and sorts its elements without removing anything, while the latter takes a collection and removes elements not matching some predicate. Yet despite being very different, both would just end being called xyz. I just find that a little suspicious.

My thinking is also that you can side-step the entire thing by, for instance, putting your classes in a Filters module. Within that namespace, they could just be called BestValue and so forth. Or each class can declare its "criterion name" in some explicit way, e.g. as a class method.

Again, I don't know your code. I'm just thinking out loud.

As for the way you're doing things now, it's not too bad, though using array subtraction is a bit much just to remove parts of a string. It could be made a little neater with a combined regexp:

name = self.class.name.split('::').last
name.gsub(/(^(Order)?(By)?|Filter$)/, '').gsub(/([a-z])([A-Z])/, '\1_\2').downcase

I've anchored matching to avoid something like ByFilterSizeFilter becoming just size.

*) it's criterion when it's singular; criteria is plural


Hackerrank Submission Optimisation for Melodious Password Given question from Hackerrank:

a password consists of exactly n lowercase English letters.
the password is melodious, meaning that consonants can only be next to
vowels and vowels can only be next to consonants. Example: bawahaha
the password cannot contain the letter y (because it's both a
consonant and vowel).
the first letter of the password can be either
a vowel or consonant.

Given the length, n, of the password,

print all of the possible passwords that meet the conditions above.

Input Format

The line of input contains the integer  (the length of the password).

Constraints

Output Format

Print each of the possible passwords, one per line. The order of the passwords does not matter.

My Code in Python:

import sys
import itertools

n = int(raw_input().strip())

consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']

test4 = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z', 'a', 'e', 'i', 'o', 'u']
answer = set(itertools.product(test4, repeat=n))

for letters in answer:
    for j in xrange(len(letters)):
        flag = 1
        if j != len(letters) - 1:
            if letters[j] in vowels and letters[j+1] in vowels:
                flag = 0
                break
            if letters[j] in consonants and letters[j+1] in consonants:
                flag = 0
                break

    if flag:
        for j in letters:
            sys.stdout.write(j)
        print ""

Can this code be optimized in any way?

Keeping the way that you're doing this at the moment, you can:

Change consonants to a string. This allows for easier readability, and may give better performance than a list.
Name constants in UPPER_SNAKE_CASE.
Using itertools.pairwise, you can remove all bar one if. This is as you can categorise each letter, l in consonants. And then compare if they are the same.
You should use a function, as it can be faster
You should use a if __name__ == '__main__' guard.
You should use print ''.join(letters), rather than for j in letters: sys.stdout.write(j).
You can yield from the function instead, so that if it's not fast enough, you can group prints. Or use it in other ways.

This can lead to:

import itertools

CONSONANTS = 'bcdfghjklmnpqrstvwxz'
VOWELS = 'aeiou'

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return izip(a, b)

def generate_answers(n):
    consonants = CONSONANTS
    for answer in itertools.product(consonants + VOWELS, repeat=n):
        letter_categories = (l in consonants for l in answer)
        if all(a != b for a, b in pairwise(letter_categories)):
            yield ''.join(answer)

if __name__ == '__main__':
    for answer in generate_answers(int(raw_input().strip())):
        print(answer)

However, this is based around an inefficient usage of itertools.product.
You instead want to pass it the arguments so that it'll create them efficiently.
This is easy to do when n is even:

def generate_answers(n):
    return chain(product(CONSONANTS, VOWELS, repeat=n//2),
                 product(VOWELS, CONSONANTS, repeat=n//2))

To, do this efficiently when n is odd, is also quite easy.
You want to do roughly the same thing, but if the first item of the products is not the same as the first character of the first argument, then stop looping.
And so you can use:

import itertools

CONSONANTS = 'bcdfghjklmnpqrstvwxz'
VOWELS = 'aeiou'

def product(a, b, repeat):
    if repeat % 2 == 0:
        for ret in itertools.product(a, b, repeat=repeat//2):
            yield ret
    else:
        for ret in itertools.product(b, a, repeat=repeat//2+1):
            if ret[0] != b[0]:
                break
            yield ret[1:]

def generate_answers(n):
    return itertools.chain(product(CONSONANTS, VOWELS, repeat=n),
                           product(VOWELS, CONSONANTS, repeat=n))

if __name__ == '__main__':
    for answer in generate_answers(int(raw_input().strip())):
        print(''.join(answer))


Nested routes and proper place for a function? I have a Rails app and in it I have two models, widget and votes. Votes are used to keep track of the desirability of a widget.

In my models I have:

class Vote < ActiveRecord::Base
    belongs_to :widget
end

class Widget < ActiveRecord::Base
    has_many :votes
end

I am trying to figure out the best way to route votes up and votes down. At the moment I am leaning towards this:

resources :widgets do
  member do
      put :vote_up
      put :vote_down
  end
end

Where the respective functions reside in the widgets' controller and it creates and saves votes in that controller. However, I realize that this doesn't really fit correctly with the MVC idea (votes should be created and built in their own controller). Is this acceptable or should I be doing something more like:

resources :widgets do
  resources :votes do
    member do
        put :vote_up
        put :vote_down
    end
  end
end

I would not create custom controller actions. up and down are attributes of a Vote, so I would do the following:

resources :widgets do
  resources :votes, only: [:new, :create]
end

And then send a POST to VotesController#create with params[direction: 'up'] and have an attribute on Vote called direction.

Then validate Vote#direction can only be up or down:

class Vote < ActionController:Base
  validates_inclusion_of :direction, in: %w(up down)
end

Your check for this kind of routing decision is to run rake routes and make sure the route aliases make sense, in this case we are really creating widget_votes, which looks like:

         Prefix Verb   URI Pattern                             Controller#Action
   widget_votes POST   /widgets/:widget_id/votes(.:format)     votes#create
new_widget_vote GET    /widgets/:widget_id/votes/new(.:format) votes#new


Kik bot made using Flask I created a Kik messenger bot using Flask microframework and python that accepts POST requests on the provided webhook and then responds appropriately. I have excluded custom module imports because they are not relevant in my problem.

import os
from flask import Flask, request, Response
from flask import Flask, request, Response, url_for
from kik import KikApi, Configuration
from kik.messages import LinkMessage, PictureMessage, VideoMessage
from kik.messages import StartChattingMessage, ScanDataMessage, StickerMessage
from kik.messages import SuggestedResponseKeyboard, TextResponse
from kik.messages import messages_from_json

app = Flask(__name__)
BOT_USERNAME = os.environ['BOT_USERNAME']
BOT_API_KEY = os.environ['BOT_API_KEY']
WEBHOOK = os.environ['WEBHOOK']

features = {'manuallySendReadReceipts': False,
            'receiveReadReceipts': True,
            'receiveDeliveryReceipts': False,
            'receiveIsTyping': False}

static_keyboard = SuggestedResponseKeyboard(
    responses=[TextResponse('PLACEHOLDER1'),
               TextResponse('PLACEHOLDER2')
               ])

kik = KikApi(BOT_USERNAME, BOT_API_KEY)
kik.set_configuration(Configuration(
    webhook=WEBHOOK, static_keyboard=static_keyboard, features=features))

@app.route('/incoming', methods=['POST'])
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        user = message.from_user
        chat_id = message.chat_id

        if isinstance(message, LinkMessage):
            # do something

        elif isinstance(message, PictureMessage):
            # do something

        elif isinstance(message, VideoMessage):
            # do something

        elif isinstance(message, StartChattingMessage):
            # do something

        elif isinstance(message, ScanDataMessage):
            # do something

        elif isinstance(message, StickerMessage):
            # do something

        elif isinstance(message, TextMessage):
            query = message.body
            query_words = query.split()
            chat_type = message.chat_type
            participants = message.participants

            if query.lower() in ['placeholder1', 'placeholder2']:
                # do something

            elif query_words[0] in ['placeholder3', 'placeholder4']:
                # do something

            elif query_words[0] in ['placeholder5'] and user in ['mamun']:
                # do something

            # a large number of more elif statements present in actual app
            else:
                # do something

    return Response(status=200)

if __name__ == '__main__':
    app.run(port=8000, debug=True)

What I have done so far is create separate modules for custom functionality that I created, but in the end they are consumed by the large number of elif statements which I don't like. Is there any way I can avoid the elif statement hell?

My actual bot is 100% complete, production ready and approved by kik, but the way I had to program it still bothers me when I look at it.

You could just build a dictionary mapping classes to functions to call:

class A:
    pass

class B:
    pass

def func_a(x, y):
    return x + y

def func_b(x, y):
    return x - y

if __name__ == "__main__":
    d = {LinkMessage: link_message,
         PictureMessage: picture_message,
         VideoMessage: video_message,
         StartChattingMessage: chatting_message,
         ScanDataMessage: data_message,
         StickerMessage: sticker_message}
    message = PictureMessage()
    funcs[message.__class__]()

Alternatively, if these classes are controlled by you, you could give them all a method called the same name which will be called, maybe handle_message:

class LinkMessage:
    ...
    def handle_message(self, *args):
        pass

if __name__ == "__main__":
    message = LinkMessage()
    message.handle_message(1, 2)


Text Analyzer - Properly implementing Java coding style As a new Java learner I would like to improve my coding style.
I wrote a program which gets as an input a file name, and asks for two file names for the output.

The first output file includes all the words from the input file with their number of occurrences.

The second output file includes the words in lexicographic order.

There is some code that is written twice, I think I can fix that by declaring a new method for this part of code, but I'm not sure how to do this properly.

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.io.*;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class TextAnalyzer {

    private static HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
    public static StringBuffer stringBuffer;

    public static void main(String[] args) throws IOException {

        if (args.length == 0) {

            System.out.println("Please specify input file as program argument");
            return;

        }

        getWordsCount(args[0]);

        String outputFileName;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter output file name:");
        outputFileName = scanner.nextLine();
        while (outputFileName.isEmpty()) {
            System.out
                    .println("Invalid file name ! Please re-enter output file name:\n");
            outputFileName = scanner.nextLine();
        }

        stringBuffer = new StringBuffer();
        for (Entry<String, Integer> word : wordCount.entrySet()) {
            stringBuffer.append(String.format("%s\t%d%n", word.getKey(),
                    word.getValue()));
        }
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFileName));
        bufferedWriter.write(stringBuffer.toString());
        bufferedWriter.close();

        Set<String> s = wordCount.keySet();
        List<String> l = new ArrayList<String>(s);
        Collections.sort(l);
        String s2 = "";
        for (int i = 0;  i < l.size(); i++) {

            s2 = s2 + l.get(i) + "\n";
        }

        System.out.println("Please enter output file name:");
        outputFileName = scanner.nextLine();
        while (outputFileName.isEmpty()) {
            System.out
                    .println("Invalid file name ! Please re-enter output file name:\n");
            outputFileName = scanner.nextLine();
        }

        bufferedWriter = new BufferedWriter(new FileWriter(outputFileName));
        bufferedWriter.write(s2);
        bufferedWriter.close();

        scanner.close();

    }

    /**
     * Updates the Hashmap wordCount by inserting a word as a key and its number
     * of occurrences as a value.
     *
     * @param filename
     *            the file to read from
     * @throws IOException
     */

    private static void getWordsCount(String filename) throws IOException {
        Scanner scanner = new Scanner(new File(filename));

        while (scanner.hasNext() == true) {
            String token = scanner.next();
            Integer tokenCount = wordCount.get(token);
            if (tokenCount == null) {
                wordCount.put(token, 1);
            } else
                wordCount.put(token, tokenCount + 1);
        }

        scanner.close();
    }// ENDD

}

Single responsibility principle

The main method does most of the job.
It would be better to split that up to smaller methods,
in a way that each method has a single responsibility.
You will end up with something more modular, reusable, testable.

Make variables local when possible

stringBuffer is only used within the main method,
so doesn't need to be a member variable.
Declare it right before you need it,
in fact, it's best at the time of initialization:

StringBuffer stringBuffer = new StringBuffer();

Avoid static variables when possible

None of the static variables were needed.
In general, avoid static variables as much as possible,
especially if they are mutable.

wordCount is not as simple to eliminate as stringBuffer,
but still easy enough:
make getWordsCount return a Map<String, Integer>.

Use the enhanced for-each loop

Instead of this:

for (int i = 0;  i < l.size(); i++) {
    s2 = s2 + l.get(i) + "\n";
}

Since you don't need the index values and it's just clutter,
the recommended writing style is this:

for (String word : l) {
    s2 = s2 + word + "\n";
}

This has another advantage that in this form the loop can work efficiently not only with an ArrayList, but with a LinkedList too,
because elements are no longer accessed by index.

Use boolean expressions directly

Instead of this:

    while (scanner.hasNext() == true) {

You can and should write this:

    while (scanner.hasNext()) {

Refer to types by interfaces

Instead of this:

private static HashMap<String, Integer> wordCount = new HashMap<String, Integer>();

This would be better:

private static Map<String, Integer> wordCount = new HashMap<String, Integer>();

Use Java 7

I'm guessing you're using an older version because of things like this:

List<String> l = new ArrayList<String>(s);

Starting from Java 7 you don't need to specify the type parameters at the right hand side of expressions, the compiler can figure them out most of the time, and you can use the diamond operator <> like this:

List<String> l = new ArrayList<>(s);

Unused imports

You have some unused imports:

import java.io.FileNotFoundException;
import java.util.Map;

I'm surprised your IDE doesn't warn about them.
In fact it probably does.
Strive to keep warnings to minimum, ideally down to zero.

Extremely poor names

In this code,
the variable names s, l, s2 are bordering obfuscation.

Set<String> s = wordCount.keySet();
List<String> l = new ArrayList<>(s);
Collections.sort(l);
String s2 = "";
for (int i = 0;  i < l.size(); i++) {
    s2 = s2 + l.get(i) + "\n";
}

Sure you can come up with better names for these,
which will make the code so much more readable.

Prefer StringBuilder over StringBuffer

StringBuffer synchronizes internally to make it thread safe.
This is rarely needed in practice,
and in this example it's completely unnecessary.
Use StringBuilder instead.

Btw, is there a benefit to accumulating the output in memory before producing the output? Probably not.
You could just write the output directly,
without building up a long string.

Put braces consistently

In this code, you put braces for the if, but not for the else

if (tokenCount == null) {
    wordCount.put(token, 1);
} else
    wordCount.put(token, tokenCount + 1);

At the minimum, be consistent.
The recommendation is to put braces always.


Instantiating widgets In my Tkinter projects I almost always end up with __init__() methods that look like this:

import tkinter as tk
from .common import ConfigPageFrame

class SystemInformationPageFrame(ConfigPageFrame):
    def __init__(self, parent, callback_dict):
        super().__init__(parent)

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.button_text = "Refresh"
        self.button_callback = callback_dict['btn_refresh']

        self.lbl_sys_desc_text = "System description:"
        self.lbl_model_text = "Model:"
        self.lbl_serial_text = "Serial number:"
        self.lbl_mac_text = "Burned in MAC:"
        self.lbl_soft_ver_text = "Software version:"
        self.lbl_os_text = "Operating system:"
        self.lbl_net_chip_text = "Network processing device:"

        self.btn_refresh = tk.Button(self, text=button_text,
                                command=button_callback)
        self.btn_refresh.grid(column=0, row=10, columnspan=2)

        self.lbl_sys_desc = tk.Label(self, text=lbl_sys_desc_text, anchor=tk.E)
        self.lbl_model = tk.Label(self, text=lbl_model_text, anchor=tk.E)
        self.lbl_serial = tk.Label(self, text=lbl_serial_text, anchor=tk.E)
        self.lbl_mac = tk.Label(self, text=lbl_mac_text, anchor=tk.E)
        self.lbl_soft_ver = tk.Label(self, text=lbl_soft_ver_text, anchor=tk.E)
        self.lbl_os = tk.Label(self, text=lbl_os_text, anchor=tk.E)
        self.lbl_net_chip = tk.Label(self, text=lbl_net_chip_text, anchor=tk.E)

        self.lbl_sys_desc.grid(column=0, row=0, sticky=tk.E)
        self.lbl_model.grid(column=0, row=1, sticky=tk.E)
        self.lbl_serial.grid(column=0, row=2, sticky=tk.E)
        self.lbl_mac.grid(column=0, row=3, sticky=tk.E)
        self.lbl_soft_ver.grid(column=0, row=4, sticky=tk.E)
        self.lbl_os.grid(column=0, row=5, sticky=tk.E)
        self.lbl_net_chip.grid(column=0, row=6, sticky=tk.E)

This sample is a GUI class from quite a large project, so I can't really show you the whole code (1700+ lines right now, tending towards much more).

As you can see, the overall structure of the widgets instantiation is very repetitive.

Is there a better way to widget instantiation? Maybe some less repetitive approach that doesn't seem to violate DRY?

The answer really depends on what you're building. For example, if you're building a grid of labels and entry widgets then a simple data structure and loop is all you need. For example:

fields = [
    {"id": "sys_desc", "label": "System description", "default_value": ""},
    {"id": "model", "label": "Model", "default_value": ""},
    ...
]
self.labels = {}
self.entries = {}
for field in fields:
    label = tk.Label(self, field["label"], ...)
    entry = tk.Entry(self, ...)
    entry.insert("end", field["default_value"])

    self.label[field["id"]] = label
    self.entry[field["id"] = entry

self.label["sys_desc"].grid(...)
self.entry["sys_desc"].grid(...)
...

Another solution is to create a helper class or helper function so that your code looks something like this:

self.add_widget(self, "sys_desc", "System Description", "default value...", row=1)
self.add_widget(self, "model", "Model", "default model", row=2)
self.add_widget(self, "serial", "Serial Number", "default serial value", row=3)
...

Or with classes:

self.sys_desc = LabelEntry(self, "System Description", ...)
self.model = LabelEntry(self, "Model", ...)
self.serial = LabelEntry(self, ...)
...

There is no single answer for all layouts. Complex layouts require complex code, simple layouts can be built with simple code. The bottom line is to look for patterns, and make helpers to help reduce repetitive code.


Support entitlement date check for customer assets I'm new to Java right now. Here is my following code snippet:

for(int i = (SelectedAssets.size()-1); -1 < i; i--){

    Double supportTime = 0;
    //Date class must be used. Cannot replace with another class
    Date oDate=SelectedAssets[i].Entitlement_End_Date__c;
    Date dateDifference = oDate.daysBetween(date.today());
    /****************************************************************************
        If the number of days between Entitlement End Date and Todays
        date is a positive number, then that means the support given to client is expired since
        entitlement end date happened before todays date.
    *****************************************************************************/
    if(dateDifference>0){
        supportTime=((dateDifference/365.00));
        //If the number of days is greater than one year, I want
        //to find out exactly the amount of days it's gone over in decimals.
        if(supportTime>1){
            supportTime=1;
            supportTime+=(date.today().daysBetween(TheEndDate)/365.00);
        }
    }
    else{
        //if it hasn't gone over a year, find out how much time has elapsed in years.
        supportTime=oDate.daysBetween(TheEndDate)/365.00;
    }
}

Is there any redundancies anywhere that I'm overlooking? Is there an easier way of doing this with fewer lines?

First thing would be to scan your code with Sonar. This will hit all the formatting complaints, magic numbers, etc.. Likewise, set up your IDE to auto format on save action to save lots of time fixing those Sonar findings.

The next thing to simplify would be to use Calendar instead of Date.


Simple Configuration Manager below I have coded a simple configuration manager that loads config elements from a file straight into a dictionary, and also has a function for getting an element by its key in the dictionary. I just wondered if there is anything I can do to improve this..

using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Apple_Server.Application.Base.Core.Config
{
    class ConfigManager
    {
        private readonly Dictionary<string, string> configValues = null;
        private readonly FileInfo configFile = null;
        private readonly ILog _log = null;
        private bool _initialized = false;

        public ConfigManager(string filePath)
        {
            this.configValues = new Dictionary<string, string>();
            this.configFile = new FileInfo(filePath);
            this._log = LogManager.GetLogger(typeof(ConfigManager));
        }

        public void Initialize()
        {
            if (!this._initialized)
            {
                try
                {
                    foreach (string line in File.ReadLines(this.configFile.ToString()).Where(s => !string.IsNullOrWhiteSpace(s) && !s.StartsWith("#") && s.Contains("=")))
                    {
                        this.configValues[line.Split('=')[0]] = line.Split('=')[1];
                    }
                }
                catch (FileNotFoundException)
                {
                    this._log.Error("Unable to find the config file.\nPress any key to exit.");
                    Console.ReadKey(true);

                    Environment.Exit(Environment.ExitCode);
                }
                catch (Exception)
                {
                    Console.WriteLine("opppppps");
                }
            }

            this._initialized = true;
        }

        public string GetConfigElement(string Key)
        {
            return configValues[Key];
        }
    }
}

You're not consistent with your private fields:

private readonly Dictionary<string, string> configValues = null;
private readonly FileInfo configFile = null;
private readonly ILog _log = null;
private bool _initialized = false;

Several things:

If you're going to use an _underscore prefix, then don't use a redundant this qualifier to refer to the field names later: it defeats the purpose.
If you're not going to use an _underscore prefix for private fields, then don't use one for any private field. Be consistent. Either you this or you don't.
The 3 readonly fields are initialized in the constructor. Why are they also statically initialized then?
Why bother initializing a field to its default value? Reference types are null, and a bool is false by default. The static initialization is redundant.

    private readonly Dictionary<string, string> _configValues;
    private readonly FileInfo _configFile;
    private readonly ILog _log;
    private bool _initialized;

    public ConfigManager(string filePath)
    {
        _configValues = new Dictionary<string, string>();
        _configFile = new FileInfo(filePath);
        _log = LogManager.GetLogger(typeof(ConfigManager));
    }

The first condition in the Initialize method could be inverted to eliminate a whole level of nesting:

if (_initialized)
{
    return;
}

This has the added benefit of avoiding a redundant assignment, since you don't need to set _initialized to true when it's already true.

Don't do this:

Environment.Exit(Environment.ExitCode);

The configuration manager shouldn't be allowed to terminate its client. That's a big, huge no-no right there.

Instead, throw some ConfigurationUnavailableException and let the client code deal with it - if it wants to terminate when configuration is unavailable, let it do so. If it wants to work off default values, allow it to do so. Don't just let that one component pull the plug because it's not happy with the execution path!

This isn't useful either:

catch (Exception)
{
    Console.WriteLine("opppppps");
}

I'd let System.Exception bubble up here, and catch a more generic System.IOException after dealing with the FileNotFoundException - perhaps the file was found, but the logged-in user can't read-access it?

Ideally you would just catch IOException and log the exception type instead of... wait a minute. That's not a logger, it's a console wrapper! How confusing!

this._log.Error("Unable to find the config file.\nPress any key to exit.");
Console.ReadKey(true);

Does the user-friendly message get output to the Console? If so, then what do you need ILog for? Your class is already coupled with System.Console! Or it's a logger, but you're assuming the output is configured to go to the console? Logging shouldn't interact with your code in any way, and seeing "press any key to exit" in a log file is a bit awkward.

I think I'd do this instead:

try
{
    // load configuration
}
catch(Exception exception)
{
    _log.Error(exception); // assuming overload that takes an exception.
    throw new ConfigurationUnavailableException(exception);
}

So we get a log trace of the actual exception, and bubble it up to the caller via a new ConfigurationUnavailableException that can be caught and dealt with at the call site, which would be responsible for the "press any key to continue" part.


Using JavaScript promises to display weather and location information This is the first time I'm trying to use promises in JavaScript so I'm not sure if I have done it correctly, but it seems to work. The problem is that I have ended up with a "nested when" and it doesn't look that great. There probably is a nicer solution out there. I would really appreciate some feedback on how I can improve my code.

I am using the navigator.geolocation to get the position and then I'm using two different APIs to get the current weather and the address of the location.

What I would like it to look like would be something like:

$.when(getPosition())

.then(getWeather(position),getLocationName(position))

.done(displayWeather);

But it doesn't seem to work with two calls in then() like you can have in when().

This is my current solution:

var displayWeather = function(weatherData, locationData) {

  $('#userLocation').text(locationData.results[3].formatted_address);

  $('#weatherDescription').text(weatherData.currently.temperature);

  $('#temperature').text(weatherData.currently.summary);

}

var getPosition = function() {

  var deferred = $.Deferred();

  navigator.geolocation.getCurrentPosition(deferred.resolve, deferred.reject);

  return deferred.promise();

};

var getWeather = function(position) {

  return $.getJSON('https://api.forecast.io/forecast/{APIKEY}/' + position.coords.latitude + ',' + position.coords.longitude + '?callback=?')
     .then(function(data) {
        return data;
    });

}

var getLocationName = function(position) {

  return $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&key={APIKEY}')
    .then(function(data) {
        return data;
  });

}

$(document).ready(function() {

  $.when(getPosition())

    .done(function(position) {

      $.when(getWeather(position), getLocationName(position)).done(displayWeather);

    });

});

$.when(getPosition())

$.when is only used when listening to multiple promises. Since getPosition is just one and it already returns a promise, $.when isn't required and you can simply chain then to getPosition().

var getWeather = function(position) {

  return $.getJSON('https://api.forecast.io/forecast/{APIKEY}/' + position.coords.latitude + ',' + position.coords.longitude + '?callback=?')
     .then(function(data) {
        return data;
    });

}

var getLocationName = function(position) {

  return $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&key={APIKEY}')
    .then(function(data) {
        return data;
  });

}

Attaching then which just returns the resolved data data is unnecessary. $.getJSON already returns a promise-like object that resolves to data. Any then attached to it will get data in the same way this then receives it.

Additionally, suggesting you use then instead of the jQuery-specific done. then is standard, and allows you to easily move over to the standard Promises.

I usually recommend pushing off the "flow logic" of promises to the caller instead of spreading it across different functions. This allows you to easily write functions as promise-returning operations while keeping all the "flow logic" in one place.

On other stuff, suggesting you move the url into a variable. This keeps your AJAX operation short and free from the string concatenation madness. A;so recommending using named function instead of function expressions. They're easier to debug as their names appear in the stack trace.

Your code could be simplified into:

function getPosition () {

  return $.Deferred(function(deferred){
    navigator.geolocation.getCurrentPosition(deferred.resolve, deferred.reject);
  }).promise();

};

function getWeather (position) {
  var url = 'https://api.forecast.io/forecast/{APIKEY}/' + position.coords.latitude + ',' + position.coords.longitude + '?callback=?'
  return $.getJSON(url);
}

function getLocationName (position) {
  var url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&key={APIKEY}';
  return $.getJSON(url);
}

$(document).ready(function() {

  getPosition().then(function(position){

    return $.when(getWeather(position), getLocationName(position));

  }).then(function(weatherData, locationData){

    $('#userLocation').text(locationData.results[3].formatted_address);
    $('#weatherDescription').text(weatherData.currently.temperature);
    $('#temperature').text(weatherData.currently.summary);

  });

});

If you can write using ES6, the code becomes simpler and you can drop the jQuery dependency for the data gathering functions. ES6 now has native promises as well as template strings, and modern browsers have fetch. This reduces jQuery footprint to only the DOM-interacting operations.

function getPosition() {
  return new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition(resolve, reject));
};

function getWeather(position) {
  const url = 'https://api.forecast.io/forecast/${APIKEY}/${position.coords.latitude},${position.coords.longitude}?callback=?';
  return fetch(url).then(response => response.json());
}

function getLocationName(position) {
  const url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.coords.latitude},${position.coords.longitude}&key=${APIKEY}';
  return fetch(url).then(response => response.json());
}

$(document).ready(function() {

  getPosition()
    .then(position => Promise.all(getWeather(position), getLocationName(position)))
    .then(function(data){
      const weatherData = data[0];
      const locationData = data[1];

      $('#userLocation').text(locationData.results[3].formatted_address);
      $('#weatherDescription').text(weatherData.currently.temperature);
      $('#temperature').text(weatherData.currently.summary);
    });

});


Mapping Index to a String in C Please excuse my potentially noob-ish question.  I haven't touched strings in C (or C in general) in a while, and I seem to recall there being different ways you can return a C string from a function (as discussed here).

I am currently implementing a weird driver API that I inherited. Long story short, I get passed in a "device index", and then return the device name that will be used to open() the device.

Here is my implementation:

static const char* getDeviceName(uint8_t device_index) {
  static const char* const device_names[] =
    {"", "/dev/some_device", "/dev/some_other_device", "", "", "", "", "", ""};
  if (device_index > 8) {
    return "";
  } else {
    return device_names[device_index];
  }
}

Long story short, I am provided an index (as a uint8_t for some reason) and then need to convert it to a string.  As such, I create a constant array of constant strings, which is static.  Note that many of these indexes are empty since they currently do not map to a device, but may in the future.

If the device index is out of bounds, I return the empty string.  If the index is in bounds, I index into my constant array and return that value.

Since my C is rusty, I'm wondering if any of the above is UB, or if there are better ways of doing this.  I know I can have the function return void and have the caller pass in a char* for me to populate, but I think the above is the cleanest way, since I can do things like "open(getDeviceName(index));".

In addition to my questions about UB, I also wanted to make sure that the code is const correct.

At any rate, let me know your thoughts.  Thanks in advance for the help.

Your code is completely safe and free of undefined behavior.

You have used const wherever it is useful and good style.

That's great. :)

One little source of confusion, though. The list of device names contains 9 entries, but the code compares something with an 8. This 8 is confusing since the last valid index in an array is just an implementation detail. (In other programming languages like Lua or Pascal, it could be different.) Contrary, the number of devices is more interesting to any reader. Therefore, readers expect to read that number. Whatever number you write in the code, make sure it's an interesting number.

Therefore, it's better to use the idiomatic code below:

size_t size = sizeof device_names / sizeof device_names[0];
if (device_index < size) {
    return device_names[device_index];
}
return "";

This code doesn't give any clue about the actual number of devices, which makes the code more robust when a device name is added to the list.


Sidebar with slide-out feature I made a sidebar that has a slide-out feature. When you click on it, it shows more items. I made it with JS and HTML but I think the code can be done more efficiently. How can I clean the code up?

$('.slide-out').on('click', function() {
    let data = 'slideout-item';
    if($(this).data(data)) {
        let item = $('.slide-out-' + $(this).data(data));
        if(item.hasClass('slideout-active')) {
            item.hide("slide", { direction: "left" }, 250);
            item.removeClass('slideout-active');
            $('.slide-out-overlay').fadeOut()
        } else {
            item.show("slide", { direction: "left" }, 250);
            item.addClass('slideout-active');
            $('.slide-out-overlay').fadeIn()
        }
    }
});

$('.slide-out-overlay').on('click', function () {
    let items = ['content', 'system', 'account', 'other'];
    let item = '.slide-out-';
    for (i = 0; i < items.length; i++) {
        if($(item + items[i]).hasClass('slideout-active')) {
            $(item + items[i]).hide("slide", { direction: "left"}, 250);
            $(item + items[i]).removeClass('slideout-active');
            $('.slide-out-overlay').fadeOut();
        }
    }
});

{{ __('Information') }}

{{ __('Dashboard') }}

{{ __('System') }}

Content

System

Account

Other

{{ __('Content') }}

{{ __('Pages') }}

{{ __('Blocks') }}

{{ __('Layouts') }}

It has been a while since I worked with jQuery so I may not get specific API's correct.

You are repeating ("slide", { direction: "left"}, 250), if you ever changed one of the properties I would assume you'd want them to be consistent with each other. You can set an array then destructure that when calling show or hide. You can also apply this theory to your strings such as slide-out-overlay and slideout-active for example, if you find yourself typing the same strings out, generally you want to put them in a variable (ideally a const)

// OLD
$('.slide-out').on('click', function() {
    ...
    item.hide("slide", { direction: "left" }, 250);
    ...
});

$('.slide-out-overlay').on('click', function () {
    ...
    item.hide("slide", { direction: "left" }, 250);
});

// NEW
const toggleArguments ["slide", { direction: "left" }, 250]
$('.slide-out').on('click', function() {
    ...
    item.hide(...toggleArguments);
    ...
});

$('.slide-out-overlay').on('click', function () {
    ...
    item.hide(...toggleArguments);
});

It's common practice to use guard clauses, to reduce nesting. Closely related is early return's too, you should never really need the else statement.

// OLD
$('.slide-out').on('click', function() {
    let data = 'slideout-item';
    if($(this).data(data)) {
        let item = $('.slide-out-' + $(this).data(data));
        if (something) {
            ...
        } else {
            ...
        }
    }
});

// NEW
$('.slide-out').on('click', function() {
    let data = 'slideout-item';
    if (!$(this).data(data)) {
        return;
    }

    if (item.hasClass('slideout-active') {
        ...
        return;
    }

    // do code for !item.hasClass('slideout-active')
});

It is sometimes clearer to put a $ in front of variables that are jQuery objects

// OLD
let item = $('.slide-out-' + $(this).data(data));

// NEW
let $item = $('.slide-out-' + $(this).data(data));

In your .slide-out-overlay click function, you are finding .slide-out-overlay again within the function block, when you already have the element in this

// OLD
$('.slide-out-overlay').on('click', function () {
    ...
    $('.slide-out-overlay')...
});

// NEW
$('.slide-out-overlay').on('click', function() {
    $(this)...
});

In your .slide-out-overlay click function you are looping over any array of strings and then checking if the relevant element has class slideout-active. Could you not just look for elements that have slideout-active?

// OLD
$('.slide-out-overlay').on('click', function () {
    let items = ['content', 'system', 'account', 'other'];
    let item = '.slide-out-';
    for (i = 0; i < items.length; i++) {
        if($(item + items[i]).hasClass('slideout-active')) {
            ...
});

// NEW
$('.slide-out-overlay').on('click', function () {
    const $items = $('.slideout-active');
    $items.hide("slide", { direction: "left"}, 250); // .hide works on an array of elements, as do most jQuery methods
    ...
});

You seem to be using let where you can use const. Only ever use let if you are modifying the value later on. Otherwise use const
String interpolation is also an option to concatante your strings. Although with jQuery may look a little confusing

// OLD
let item = $('.slide-out-' + $(this).data(data));

// NEW
let item = $(`.slide-out-${$(this).data(data)}`);

I would also challenge you to write this without jQuery and use vanilla javascript and CSS transitions on the classes.

Hopefully that helps!


Subclassing Profile.Profile to use it as a context manager I was profiling my code and annoyed by the continuous calls of

Profile.run(my_function())
Profile.run(my_next_function())

so I decided to make a context manager instead.  This seems pretty straightforward but I wanted to make sure nothing about it was bad - I was a little surprised that you couldn't use it as a context manager to begin with which makes me suspect someone had a reason to not implement it.

try:
    import cProfile as Profile
except ImportError:
    import profile as Profile
finally:
    import pstats
    import sys

class context_profiler(Profile.Profile):

    def __init__(self, sortby='cumulative', stream=sys.stdout, **kwargs):
        super(context_profiler, self).__init__(**kwargs)
        self.sortby = sortby
        self.stream = stream

    def __enter__(self):
        self.enable()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.disable()
        self.print_data()

    def print_data(self):
        ps = pstats.Stats(self, stream=self.stream).sort_stats(self.sortby)
        ps.print_stats()

if __name__ == '__main__':
    with context_profiler() as pr:
        for i in xrange(2):
            for j in range(10000):
                pr.stream.write(str(i+j))

An __exit__ method should analyze the exc_type parameter. If there really was an exception, the collected profile is most likely not representative, and should not be accumulated. At least provide an option for such behaviour.

Otherwise looks pretty good.


Named operators in C++ A post by Yakk alerted me to  the idea of named operators in C++. This look splendid (albeit very unorthodox). For instance, the following code can be made to compile trivially:

vector<int> vec{ 1, 2, 3 };

cout << "3 in " << vec << ": " << (3 <in> vec) << '\n'
     << "5 in " << vec << ": " << (5 <in> vec) << '\n';

Of course the whole thing has to be generic so any binary function-like thing can be used to define operators, e.g.

auto in = make_named_operator(
    [](int i, vector<int> const& x) {
        return find(begin(x), end(x), i) != end(x);
    });

I’d like to know whether the following implementation is sufficient to handle all “interesting”1 cases, and whether it’s robust. For instance, I’m storing the operands in references. That should work since they’re only stored until after the expression has completed, and thus should never go stale. I’m especially interested in feedback on the return types of the operator functions below and on the design rationale of using the <…> syntax for named operators.2

It seems to handle templates as well as a mixture of different types (and cv-qualification).

#include <utility>

template <typename F>
struct named_operator_wrapper {
    F f;
};

template <typename T, typename F>
struct named_operator_lhs {
    F f;
    T& value;
};

template <typename T, typename F>
inline named_operator_lhs<T, F> operator <(T& lhs, named_operator_wrapper<F> rhs) {
    return {rhs.f, lhs};
}

template <typename T, typename F>
inline named_operator_lhs<T const, F> operator <(T const& lhs, named_operator_wrapper<F> rhs) {
    return {rhs.f, lhs};
}

template <typename T1, typename T2, typename F>
inline auto operator >(named_operator_lhs<T1, F> const& lhs, T2 const& rhs)
    -> decltype(lhs.f(std::declval<T1>(), std::declval<T2>()))
{
    return lhs.f(lhs.value, rhs);
}

template <typename T1, typename T2, typename F>
inline auto operator >=(named_operator_lhs<T1, F> const& lhs, T2 const& rhs)
    -> decltype(lhs.value = lhs.f(std::declval<T1>(), std::declval<T2>()))
{
    return lhs.value = lhs.f(lhs.value, rhs);
}

template <typename F>
inline constexpr named_operator_wrapper<F> make_named_operator(F f) {
    return {f};
}

For the interested, a full example implementation is on GitHub.

1 <insert your definition of “interesting” here>

2 I considered other alternatives, such as %…% which is used by R, and allowing different operators (as done by Yakk) to allow for different operator precedences but I decided against that because I think it makes operator precedence even more complicated than it already is in C++.

I would add rvalue reference support with moving of temporaries.

<op> seems to be too low precidence to be practical - you end up having to (bracket) everything (as demonstrated above).  % at least binds tightly.

I do like a <op>= b.  Better than my a +op= b.

Forwarding operator() from the operator to the function lets you forget the function behind the operator entirely:  in(3, vec) -- very Haskell.

N ary infix operators that defer application of f allow s <append> s2 <append> s3 to run as efficiently as possible.  But doing that cleanly might be hard.

Not sure what inline is intended to do above.

For an interesting test case, implement (std::future<T> %then% [](T)->U)->std::future<U> (where that lambda is a placeholder for a functor)

Block some copy and move ctors to prevent persistance, and friend the approriate operators.

As noted, I allowed arbitrary binary operators (chosen when you make_infix) to bracket the named operator: the precidence of the resulting named operator exactly matches the bracketing operators.  So +append+ has precidence of + and *in* has precidence of *.  Of the 3 first use cases (lin alg, container append, then) for two of them the named operators where variants of existing operators, and matching their precidence seemed useful.


Remove contiguous elements in array in a more functional way I try to remove elements in an array if the number of contiguous element is greater than two.

Here are the tests:

test('delete pieces if number of piece contiguous greater than two', t => {
    t.deepEqual([null, null, null], removeIdenticalPieces([1, 1, 1]));
    t.deepEqual([null, null, null, null], removeIdenticalPieces([1, 1, 1, 1]));
    t.deepEqual([null, null, null, null, 4], removeIdenticalPieces([1, 1, 1, 1, 4]));
    t.deepEqual([4, null, null, null, null], removeIdenticalPieces([4, 1, 1, 1, 1]));
    t.deepEqual([1, 1, 4, 1, 1], removeIdenticalPieces([1, 1, 4, 1, 1]));
    t.deepEqual([1, 1], removeIdenticalPieces([1, 1]));
});

Here is a working function:

function removeIdenticalPieces(line) {
    const newLine = [];
    while (line.length !== 0) {
        const firstPiece = line.shift();
        let nbContiguousPieces = 0;
        for (let i = 0; i < line.length; i++) {
            let currentPiece = line[i];
            if (firstPiece !== currentPiece) {
                break;
            }
            nbContiguousPieces += 1
        }
        if (nbContiguousPieces >= 2) {
            newLine.push(null);
            for (let j = 0; j < nbContiguousPieces; j++) {
                line.shift();
                newLine.push(null)
            }
        } else {
            newLine.push(firstPiece);
            for (let k = 0; k < nbContiguousPieces; k++) {
                newLine.push(line.shift())
            }
        }
    }
    return newLine;
}

Does a more "functional" way exist to do the same?

Edit: thank you for your solutions.

Here the jsperf https://jsperf.com/removeidenticalpieces3.

I take the solution of @lilobase because it is faster and more readable.

One neat thing about array.reduce is that the carry doesn't need to be your resulting value. You can actually hold a record of previous runs on it by carrying an object.

I would think something along the lines of:

line.reduce((carry, current, index) => {
  // If current is same a previous, increase repeats
  // If repeats === 3, splice the last 3  in result and replace with null,
  // Else, add current to the result
  // update previous and repeats a
  // return updated carry
}, {
  result: [],
  previous: null,
  repeats: 0
}).result;


Ternary operation in Java - isn't this abuse? I think the below code is difficult to understand.  I also feel it abuses Java's ternary operator.

String name = ((this.getAllNamesAsDelimitedString().contains(incomingName) ?
               incomingName:
               (CollectionsUtils.isEmptyCollection(this.getEntityOperationMap()) ?
               null :
               this.getEntityOperationMap.get(incomingName))));

Above getAllNamesAsDelimitedString will return a comma (,) delimited String.

I'd prefer something instead of such a nested ternary operator, if it looks cleaner and easier to understand.  It would also be easy to sort out merge issue in, say, SVN.

N.B: There are even more nested ternary conditions in the code that I just have taken over.

Is there any general guideline which suggests the number of levels a ternary operator should be allowed?  In other words, any guideline suggesting when you should break your ternary operator for better code readability?

I think it's important to note that nested ternary operators can be formatted to look good:

String name = isConditionA ? "first"
            : isConditionB ? "second"
            : isConditionC ? "third"
                           : "fourth";

This isn't the most readable option in your case, because you have longer method calls, but I think it's better when the conditions are kept short and meaningful.


Submitting form after validations using jQuery This is my simple jQuery form validation/submit logic and it is working perfectly fine. But still I am posting this to see if someone check the logic and suggest me if there is any other simple way to get the same results.

In my form I put all input boxes and select into .valid1 class, all checkbox and radio buttons to .valid2 class. I am just wondering is there any way we can do this by putting all input sources under a single class.

    $(document).ready(function(){

        $("#sbutton").click(function(){
           var submitflag = false;
           var validflag = true;
           validform();
//           alert(submitflag);
           if (submitflag){
              $("form").submit();
           }
           function validform(){
              $(".valid1").each(function(){
                 if ($(this).find("input").val() === ''){
//                    alert("I am input");
                    $(this).find(".error1").html($(this).find("label").html() +" " + "is required");
                    validflag = false;
                 }else{
                    $(this).find(".error1").html("");
                 }
                 if ($(this).find("select").val() === ''){
//                    alert("I am select");
                    $(this).find(".error2").html($(this).find("label").html() +" " + "is required");
                    validflag = false;
                 }else{
                    $(this).find(".error2").html("");
                 }

              });
              $(".valid2").each(function(){
                 if (!$(this).find("input:checked").val()){
//                    alert("I am cbox");
                    $(this).find(".error3").html($(this).find("label").html() +" " + "is required");
                    $(this).find(".error4").html("Agree terms and conditions");
                    validflag = false;
                 }else{
                    $(this).find(".error3, .error4").html("");
                 }
              });
              if(validflag){submitflag = true;}
           }
         });
});

There is no need for submitflag. The validform function could simply return the value of validflag, which should be declared inside that function, not in the outer scope.

  In my form I put all input boxes and select into .valid1 class, all checkbox and radio buttons to .valid2 class. I am just wondering is there any way we can do this by putting all input sources under a single class.

Sure. You just need to adjust some of the dom selectors a little bit, so that they are specific enough to match the right kind of input, for example by adding a condition on the type attribute, to make sure that text input and checkboxes are correctly distinguished.


0-1 Knapsack problem - implementation Given a set of items with a weight and a value, this problem gives the subset of items which maximize value so that their combined weights is less or equal than a given maximum weight. This solution runs in \$O(w\cdot n)\$ where \$n\$ is the number of items and \$w\$ is the max weight.

#[derive(Debug, Clone)]
struct Item {
    value: usize,
    weight: usize,
}

impl Item {

    fn new(pvalue: usize, pweight: usize) -> Item {
        Item { value: pvalue, weight: pweight }
    }
}

#[derive(Debug, Clone)]
struct Info {
    ks_value: usize,
    added_weight: usize,
    included: bool,
}

impl Info {
    fn new(pks_value: usize, padded_weight: usize, pincluded: bool) -> Info{
        Info {
            ks_value: pks_value,
            added_weight: padded_weight,
            included: pincluded,
        }
    }
}

impl std::cmp::Ord for Info {
    fn cmp(&self, other: &Info) -> std::cmp::Ordering {
        self.ks_value.cmp(&other.ks_value)
    }
}

impl PartialOrd for Info {
    fn partial_cmp(&self, other: &Info) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Info {
    fn eq(&self, other: &Info) -> bool {
        self.ks_value == other.ks_value
    }
}

impl Eq for Info {}

fn _0_1_knapsack_items<'a>(items: &'a[Item], max_weight: usize, subproblems: &[Vec<Info>]) -> Vec<&'a Item>{
        (1..items.len() + 1).rev()
        .scan(max_weight, |w, i| {
                let sub    = &subproblems[i][*w];
                let result = (i, sub.included);
                *w -= sub.added_weight;
                Some(result)
        })
        .filter(|&(_, inc)| inc)
        .take_while(|&(i, _)| i > 0)
        .map(|(i, _)| &items[i - 1])
        .collect::<Vec<&Item>>()
}

fn _0_1_knapsack<'a>(items: &'a [Item], max_weight: usize) -> Vec<&'a Item>{
    let mut subproblems = vec! [ vec! [ Info::new(0, 0, false);
                                       max_weight + 1 ];
                                 items.len() + 1 ];
    for i in 0..items.len() {
        for w in 0..max_weight + 1 {
            let w_i      = items[i].weight;
            let exc_cost = subproblems[i][w].ks_value;
            subproblems[i + 1][w] = if  w < w_i {
                Info::new(exc_cost, 0, false)
            }
            else {
                let inc_cost = subproblems[i][w - w_i].ks_value
                               + items[i].value;
                std::cmp::max(Info::new(exc_cost, 0, false),
                              Info::new(inc_cost, w_i, true))
            }
        }
    }
    _0_1_knapsack_items(items, max_weight, &subproblems)
}

fn main() {
    let items = [ Item::new(92, 23),  //1
                  Item::new(57, 31),  //1
                  Item::new(49, 29),  //1
                  Item::new(68, 44),  //1
                  Item::new(60, 53),  //0
                  Item::new(43, 38),  //1
                  Item::new(67, 63),  //0
                  Item::new(84, 85),  //0
                  Item::new(87, 89),  //0
                  Item::new(72, 82) ];//0

    for i in _0_1_knapsack(&items, 165){
        println!("{:?}", i);
    }
}

Check out Rustfmt.
There's a Clippy warning for zero_one_knapsack: explicit lifetimes given in parameter types where they could be elided.
Don't prefix every parameter with p. There's no naming conflict and it adds confusion to everyone that tries to use the API. Especially for variables like padded_weight, where "padded" is another English word!
Introduce a key method to DRY up Ord / PartialEq / Hash implementations.
A leading _ means that item is unused but must be present for some reason; don't call your methods that. Switch to words since identifiers can't start with numbers
Start iteration in zero_one_knapsack_items at 0. This simplifies the logic and shows that take_while can be removed.
This also leads to using iter and enumerate instead of operating on a range.
In turn, this leads to removing the need for indexing into items.
Remove the result temporary variable. It doesn't introduce a useful name and doesn't need to occur in a different temporal location.
There is a filter_map that does two operations in one, but I like the separation of filter and map here. You almost want a scan_map.
There's no need to specify type on collect; it's inferred from the return type of the function.
I'm not a fan of the truncated variable names. Computers don't care about long names, but humans do care about short names. This is especially true when there are overlapping meanings for prefixes like inc (included or inclusive).
Prefer iterating on a slice instead of on a range of numbers. If you need the number, use enumerate; this avoids out-of-bounds checking on each index operation.
Implement Default for your type if there's an appropriate value.
Import Ord and max to make that code a bit cleaner to read.

use std::cmp::{Ord, max};

#[derive(Debug, Clone)]
struct Item {
    value: usize,
    weight: usize,
}

impl Item {
    fn new(value: usize, weight: usize) -> Item {
        Item {
            value: value,
            weight: weight,
        }
    }
}

#[derive(Debug, Clone)]
struct Info {
    ks_value: usize,
    added_weight: usize,
    included: bool,
}

impl Info {
    fn new(ks_value: usize, added_weight: usize, included: bool) -> Info {
        Info {
            ks_value: ks_value,
            added_weight: added_weight,
            included: included,
        }
    }

    fn key(&self) -> usize {
        self.ks_value
    }
}

impl Ord for Info {
    fn cmp(&self, other: &Info) -> std::cmp::Ordering {
        self.key().cmp(&other.key())
    }
}

impl PartialOrd for Info {
    fn partial_cmp(&self, other: &Info) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Info {
    fn eq(&self, other: &Info) -> bool {
        self.key() == other.key()
    }
}

impl Eq for Info {}

impl Default for Info {
    fn default() -> Info {
        Info::new(0, 0, false)
    }
}

fn zero_one_knapsack_items<'a>(items: &'a [Item],
                               max_weight: usize,
                               subproblems: &[Vec<Info>]) -> Vec<&'a Item>
{
    items.iter().enumerate()
        .rev()
        .scan(max_weight, |w, (i, item)| {
            let subproblem = &subproblems[i+1][*w];
            *w -= subproblem.added_weight;
            Some((item, subproblem.included))
        })
        .filter(|&(_, included)| included)
        .map(|(item, _)| item)
        .collect()
}

fn zero_one_knapsack(items: &[Item], max_weight: usize) -> Vec<&Item> {
    let mut subproblems = vec![vec![Info::default(); max_weight + 1]; items.len() + 1];

    for (i, item) in items.iter().enumerate() {
        for w in 0..max_weight + 1 {
            let w_i = item.weight;
            let exclusive_cost = subproblems[i][w].ks_value;
            subproblems[i + 1][w] = if w < w_i {
                Info::new(exclusive_cost, 0, false)
            } else {
                let inclusive_cost = subproblems[i][w - w_i].ks_value + item.value;
                max(Info::new(exclusive_cost, 0, false),
                    Info::new(inclusive_cost, w_i, true))
            }
        }
    }

    zero_one_knapsack_items(items, max_weight, &subproblems)
}

fn main() {
    let items = [Item::new(92, 23),  // 1
                 Item::new(57, 31),  // 1
                 Item::new(49, 29),  // 1
                 Item::new(68, 44),  // 1
                 Item::new(60, 53),  // 0
                 Item::new(43, 38),  // 1
                 Item::new(67, 63),  // 0
                 Item::new(84, 85),  // 0
                 Item::new(87, 89),  // 0
                 Item::new(72, 82)]; // 0

    for i in zero_one_knapsack(&items, 165) {
        println!("{:?}", i);
    }
}


PHP Filesystem JSON Files DB Regarding the use of the file system as a database to simply hold JSON files.

Any input on this matter from people who know will be appreciated...

class JDB{

    public $path;

    function JDB( $path = __DIR__.'/jdb/' ){
        $this->path = $path;
        if( !file_exists($this->path) ) mkdir($this->path);
    }

    function p($t){
        return $this->path.$t.'.json';
    }

    function get($t){
        return json_decode(file_get_contents( $this->p($t) ));
    }

    function set($t,$c){
        return file_put_contents( $this->p($t), json_encode($c,JSON_PRETTY_PRINT) );
    }

    function create( $t, $d = [] ){
        $s = file_put_contents( $this->p($t), json_encode($d) );
        return $s;
    }

    function destroy(){
        $files = glob($this->path.'*'); // get all file names present in folder
        foreach($files as $file){ // iterate files
        if(is_file($file))
            unlink($file); // delete the file
        }
    }

    function delete( $t ){
        $s = unlink( $this->p($t) );
        return $s;
    }

    function insert( $t, $d = null ){
        if($d) $d['__uid'] = $t.'_'.$this->uid();
        $c = $this->get($t);
        array_push($c,$d);
        $s = $this->set($t,$c);
        if($s) return $d['__uid'];
    }

    function update($t,$conditions,$u){
        $c = $this->get($t);
        $this->search($c,$conditions,function($object) use (&$c,$u){
            foreach ($u as $key => $value) {
                $object->$key = $value;
            }
        });
        $this->set($t,$c);
    }

    function remove($t,$conditions){
        $c = $this->get($t);
        $this->search($c,$conditions,function($object,$key) use (&$c){
            unset($c[$key]);
        });
        $this->set($t,$c);
    }

    function search( $c, $conditions = [], $fn ){
        $l = count($conditions);
        foreach ($c as $key => $object) {
            $f = 0;
            foreach ($conditions as $k => $v) {
                if( property_exists($object,$k) && ($object->$k == $v) ){
                    $f++;
                    if( $f==$l ) $fn($object,$key);
                }else break;
            }
        }
    }

    function select( $t, $conditions = [] ){
        $c = $this->get($t);
        $r = [];
        $this->search($c,$conditions,function($object) use (&$r){
            array_push($r,$object);
        });
        if (count($r) == 0) return false;
        if (count($r) == 1) return $r[0];
        return $r;
    }

    function count($t){
        $c = $this->get($t);
        return count($c);
    }

    function uid($length = 20) {
        $c = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $cl = strlen($c);
        $uid = '';
        for ($i = 0; $i < $length; $i++) {
            $uid .= $c[rand(0, $cl - 1)];
        }
        return $uid;
    }

}

/*

$db = new JDB();

$db->create('users');
$db->create('pages');

$user_uid = $db->insert('users',[
    'name' => 'a',
    'password' => 'hello world',
    'pages'  => []
]);

$user_uid = $db->insert('users',[
    'name' => 'b',
    'password' => 'hello world',
    'pages'  => []
]);

_log($user_uid,'1');

$page_uid = $db->insert('pages',[
    'name' => 'page 1',
    'content' => 'hello world',
    'users'  => [$user_uid]
]);

_log($page_uid);

$user = $db->select('users',['name'  => 'a']);
$page = $db->select('pages',['users'  => [$user_uid]]);

$db->update('users',['name'  => 'b'],['pages' => [$page->__uid]]);
$db->remove('users',['name'  => 'a']);

_log($user);
_log($page);

*/

The only good thing about this code is your desire to invent. It is a very good desire, only ones possessing it make good programmers. You just made the very first step towards inventing your own database, just like every aspiring newbie programmer does. And that's a very good sign per se.

Everything else about this code - let me be frank - is bad. From the main idea to the minute syntax issues. To outline some misconceptions:

The premise. I know, I know, you have a million reasons not to use a relational database. All of them are wrong though. Beside an aspiration, a good programmer possesses a thing called common sense. Which is bound to tell them that generations of programmers created and polished a thing called a relational database for a reason.
the above leads to the number of consequences:

scalability. By no means it is good for any project you would call "large". All these manual loops in the memory will become unbearably slow. A good database never loads the entire file in the memory, it reads a file by chunks. And uses indexes to speed up all the operations dramatically.
race condition. With your database you will learn the hard way such things like file locking and a race condition. In concurrent environments a file must be locked when operated with, in order to prevent other files from accessing it. Or it will lead to data corruption and other unwanted consequences.
features. SQL is one of the greatest inventions of the last century. In a relatively short sentence that is close to natural English it lets us to do the data filtering, ordering, aggregation. How many lines of code you will have to write to get the overall salary for all employees? Grouped by departments? For the certain period? It's just a single line in SQL mind you.

naming. What do remove(), delete() and destroy() functions do? Can you tell from looking at them used in the code?
OOP. Not to mention the ancient constructor definition (it was discouraged from using for decades!), the overall class structure is flat. It's just a collection of functions. There is no delegation, no abstraction, no separation of concerns. At least there should be two classes, one operating at the filesystem level and one operating at the single json file level.
syntax in general. Again, it seems to be inevitable for many people to pass such a stage, trying to make a code easier to write, making names gibberish as a result. It takes time to realize that reading is much more important than writing, and such names as p(), $d and such is a blasphemy. Every variable and method should have a meaningful name.
if (count($r) == 1) return $r[0]; is my favorite. I learned the hard way that such a magic will lead to a situation when your code expects a 2-dimensional array of rows but gets just a single row. It's funny to see the result when you are trying to loop over it and then access distinct fields inside each element. there must be explicit methods to get you certain result types, you want to look at PDOStatement for inspiration
error reporting. at least for json_encode() you have to implement a wrapper that will produce a meaningful error message

function jsonDecode($json, $assoc = false)
{
    $ret = json_decode($json, $assoc);
    if ($error = json_last_error())
    {
        throw new Exception(json_last_error_msg(), $error);
    }
    return $ret;
}


Simple "nullable" template class. Are there weaknesses in the implementation? The goal is to have fields in a class which are optional and can be determined if they are set in order to be able to leave them out of serialization.

template<typename T>
class Nullable
{
public:
    Nullable() : m_value(), m_isSet(false) {}
    Nullable(T value) : m_value(value), m_isSet(true) {}
    Nullable(const Nullable& other) : m_value(other.m_value), m_isSet(other.m_isSet) {}

    friend void swap(Nullable& a, Nullable& b)
    {
        using std::swap;
        swap(a.m_isSet, b.m_isSet);
        swap(a.m_value, b.m_value);
    }

    Nullable& operator=(Nullable other)
    {
        swap(*this, other);
        return *this;
    }

    T operator=(T value) { set(value); return m_value; }
    bool operator==(T value) { return m_isSet && value == m_value; }
    operator T() const { return get(); }

    T get() const
    {
        if (m_isSet) return m_value;
        else throw std::logic_error("Value of Nullable is not set.");
    }

    bool is_set() const { return m_isSet; }

    void reset() { m_isSet = false; m_value = T(); }

private:
    void set(T value) { m_value = value; m_isSet = true; }

private:
    T m_value;
    bool m_isSet;
};

Any comments are welcome.

Don't see the point in:
using std::swap;

It adds a line. It is also longer to type than just prefix each swap with std::
As pointed out by @Matt below. There is a good reason to do this.
Read his links below for a more detailed description.
No point in doing copy-swap idiom for a class that is not managing resources.
So really there is no need for the copy constructor or the assignment operator: the compiler-generated versions will work perfectly well.
If you can compare against a value:
bool operator==(T value) { return m_isSet && value == m_value; }

Why can't you compare against Nullable<T>? The cast operator does not help you here - operator T() const { return get(); } - as it potentially throws. Yet it is still logical to be able to compare or it should throw if either side has m_isSet as false.
Nullable<int>   x(5);
Nullable<int>   y;

if (y == x){} // works as expected (always false as y is not set).
if (x == y){} // throws an exception.

Also operator== should be const.
Cast and get methods should be returning a reference (big T objects are expensive to copy). You will also want const versions of these functions.
On a reset:
void reset() { m_isSet = false; m_value = T(); }

Why reset the m_value when it can not be accessed anyway when m_isSet is false. Also the cost of setting T here may be expensive for some classes.
As a general comment.
I don't see the point. Each class should have its own serialization operators (>> and <<) and you will need to serialize the whole state for this to work symmetrically. Anything that is not needed for serialization is already marked as mutable (i.e. it is not part of the logical state of the object). Everything else is part of the logical state of the object. Anything that is optional has its own serialize operator and understands when not to serialize its own state.


Giving multiple choices that lead to different scenarios I'm doing a Java text based game as a course project.

Everything is fine but the part where it shows a conversation, then gives you 2-4 options, then each actions will lead to different text and stats changes.

For now I can only come up with declaring a string array to store all the text, looping through the text until the multiple choice is given, then declaring an int to store the choice of the player, switch the choice to give different text and stats bonuses.

This is quite inefficient and takes a lot of lines, so I wonder if there is a better way to do that.

int[] statsChanged = new int[] {0, 0, 0, 0};
int i;
String[] event = eventDial.getFirstNight();
for (i = 0; i < 7; i++) {
    say(event[i]);
    next();
}
int choice = -1;
while (choice > 2 || choice < 0) {
    try {
        say(event[7]);
        choice = input.nextInt();
    } catch (InputMismatchException e) {
        next();
    }
    switch (choice) {
        case 0:
            say(event[8]); say(event[9]);
            statsChanged[0] = 2;
            break;
        case 1:
            say(event[10]); say (event[11]);
            statsChanged[1] = 2;
            break;
        case 2:
            say(event[12]);
            break;
    }
}
say(event[13]);
return statsChanged;

event is the string array that stores the text. statchanges stores all the bonuses to 4 main stats. next() is just an empty input. (input.nextLine())
say(str) is System.out.println(String str);

Style:
Avoid multiple statements in one line, as you did here:

say(event[8]); say(event[9]);

Variable naming:

String[] event = ...;

It would be better to name the array events or eventArray, as you are storing multiple events.

int[] statsChanged = new int[] {0, 0, 0, 0};

statsChanged sounds like you only have true or false options, however you are assigning integer values to the elements, which have more than two options. Therefore a name such as statsLevels would be more appropriate.

Iterating through an array. Instead of:

int i;
for (i = 0; i < 7; i++) {
    say(event[i]);
    next();
}

do

for (String e:event) {
    say(event);
    next();
}


Bubble sort in C (for strings) What do you think of this bubble sorting function in C, for a string array? I would like to improve the readability, performance, and any good practices.

void         sort_entries(char **entries, int reverse)
{
    char     **next;
    char     **previous;
    char     *t;
    int      value;

    previous = tab;
    while (*(next = previous + 1))
    {
        value = strcasecmp(*previous, *next);
        if ((!reverse && value > 0)
            || (reverse && value < 0))
        {
            t = *previous;
            *previous = *next;
            *next = t;
            previous = entries;
            continue ;
        }
        previous++;
    }
}

Portability
The function strcasecmp() is a POSIX standard and not a in the C programming standard as pointed out in this stack overflow question. Therefore the sort_entries() function may not compile or link on some systems. It would be better if the program that contained the sort_entries() function also contained a version of strcasecmp().

Performance
Generally a bubble sort will be implemented as nested loops, the inner loop going over the whole input list to perform as many swaps as possible in a single pass. This implementation restarts at the beginning after a single swap requiring more passes. There is no performance improvement by this single loop over the nested loop implementation, and there may be a performance hit.

If the code swapped the pointers rather than the strings themselves there might be an improvement in the performance.

Variable Scope
It is better from a maintainability perspective and overall code comprehension to create variables as needed rather than create all the variables at the top of the function. It would be better if the variables t, next and value were defined within the loop rather than at the top of the function. The variables t and next are only needed within the if statement.


Rolling totals in a view I have a view that performs some rolling totals. In this instance, it must be in a view. The issue is that it takes about 10 minutes to run, returning 2700 records. There should be a faster way, but I am not privy at the moment. I asked a question here in order to get this far.

I am running SqlServer 2008 R2, so advanced over() functionality doesn't work, just Partition by Order by)

The difference between my question and what code I have below is that my requirements changed slightly, requiring that the OutOfPocket not be a total, but rather simply reflect the amount of the deduction (IssCost) once the $400 is exhausted. The only exception is on the deduction that exhausts the $400, the leftover is displayed, not the full deduction. A CROSS APPLY was used to achieve this effect. I couldn't quite figure out how to achieve the new requirement based upon the answer I selected in my question linked above, so I used a different answer that worked.

The concept of the view is that someone starts with $400 to spend. Every deduction (IssCost in the code), deducts from the initial $400. If a person starts going over the $400, the money will come from their own pocket (OutOfPocket).

Some sample data and the view code are as follows:

CREATE TABLE Payroll (
EmployeeID int,
PlanCode varchar(10),
IssCost int NULL
)
GO

INSERT INTO Payroll (EmployeeID, PlanCode, IssCost)
VALUES (1, 'Medical', 200)
  ,(1, 'Dental', 250)
  ,(1, 'Vision', 300)
  ,(2, 'Medical', 100)
  ,(2, 'Dental', 150)
  ,(2, 'Vision', 100)
  ,(2, 'Disability', 100)
  ,(2, 'Life', 140)

  --View starts here
  WITH C AS (
    SELECT EmployeeID
          ,PlanCode
          ,IssCost
          ,rownum = ROW_NUMBER() over (Partition BY EmployeeID Order by PlanCode)
    FROM Payroll

), C2 AS (
    SELECT EmployeeID
          ,PlanCode
          ,IssCost
          ,T.Ytd
    FROM C
    CROSS APPLY (SELECT ytd = SUM(IssCost)
                 FROM C CC
                 WHERE C.EmployeeID = CC.EmployeeID
                    AND C.rownum >= CC.rownum) T(ytd))

SELECT EmployeeID
        ,PlanCode
        ,IssCost
        ,OutOfPocket = CASE WHEN ytd < 400 THEN 0
                            WHEN (ytd > 400) AND (ytd < (400 + IssCost)) THEN ytd - 400
                            ELSE IssCost
                            END
FROM C2

I think this will work you have to use an inline select statement to get the running total, essentially this is what SUM() OVER function does in 2012+ except the engine was designed to handle the function faster.

WITH C AS (
    SELECT EmployeeID
            ,PlanCode
            ,IssCost
            ,(SELECT SUM(IssCost) FROM Payroll as b WHERE a.EmployeeID = b.EmployeeID AND a.PlanCode >= b.plancode) as YTD
    FROM Payroll as a
)
SELECT  EmployeeID
    ,PlanCode
    ,IssCost
    ,YTD
    ,(YTD - 400 + abs(IssCost - 400))/2 AS OutOfPocket
FROM C
ORDER BY EmployeeID, PlanCode